SoFunction
Updated on 2024-11-12

Python list append method for appending elements to a list.

The Python list append method appends elements to a list.

descriptive

The append function adds a new object to the end of the list. The function has no return value, but modifies the list.

vocabulary

(object)
name (of a thing) clarification note
list List of elements to be added  
object The object to be added to the list Non-Omitted Parameters

give an example

1. Add integers, floating point numbers and strings to the list:

test = ['Python', 'C', 'Java']
 
(5)
(23.6)
('HTML')
 
print(test)

The output result is:

['Python', 'C', 'Java', 5, 23.6, 'HTML']

2. Add lists, tuples and dictionaries to the list:

test = ['Python', 'C', 'Java']
 
(['Windows', 2018, 'OpenStack'])
(('Huawei', 'Tencent'))
({'Nova':'virtual compute service', 'Neutron':'net service'})
 
print(test)

The output result is:

['Python', 'C', 'Java', ['Windows', 2018, 'OpenStack'], ('Huawei', 'Tencent'), {'Nova': 'virtual compute service', 'Neutron': 'net service'}]

3. Adding empty elements to the list

test = ['Python', 'C', 'Java']
 
(None)
 
print(test)

The output result is:

['Python', 'C', 'Java', None]

caveat

The object argument cannot be omitted or Python will report an error:

test = ['Python', 'C', 'Java']
 
()
 
print(test)
Traceback (most recent call last):
  File "/Users/untitled3/", line 3, in <module>
    ()
TypeError: append() takes exactly one argument (0 given)

If you want to add an empty element to the end of the list, you should write None as the argument.

Four ways to add elements to a list list

Four ways to add elements to a list list (append, extend, insert, "+" sign)

1. append()

Appends a single element to the end of the List, accepting only one argument, which can be of any data type .

2. extend() 

Add each element of a list to another list, accepts only one argument, and the argument can only be in the form of a list.

     

  

3. insert(index,value)

Inserting an element into a list has two parameters, the first parameter index is the index point, i.e. the position of the insertion, and the second parameter value is the element to be inserted. Where index starts at 0.

4. The "+" sign

Joining two lists list will return to a new list object.

Note: (append, extend, insert) to the list to add elements of the operation, is a direct modification of the original data object, there is no return value; "+" sign is to add two lists, returned to a new list, you need to create a new list object." +" sign can be seen as a deep copy.

The above is a personal experience, I hope it can give you a reference, and I hope you can support me more.