There are several ways to to add an element to a python list, such as list.append(), list.extend(), +, += or itertools.chain(). list.append(), list.extend(), + and += are most common used in python script. What about the differences among them? In this tutorial, we will discuss this topic.
list.append()
append(self, object: Any) -> None
This function will add an object (any types) to the end of a list.
Here is an example:
l = [] #add a integer l.append(1) #add a string l.append('tutorialexample.com') #add a list l.append(['Tutotial', 'Example']) print(l)
The l is:
[1, 'tutorialexample.com', ['Tutotial', 'Example']]
In this example, we create an empty python list l first. Then, we will add an integer, a string and a list to the end of list l one by one.
list.extend()
extend(self, iterable: Iterable) -> None
This function will receive an iterable object, then add each element in this iterable object to the end of list one by one.
Here is an example:
l = [] #python list l1 = [1, 'tutorialexample.com'] l.extend(l1) #python tuple l2 = (2, 'https://www.tutorialexample.com') l.extend(l2) print(l)
The python list l is:
[1, 'tutorialexample.com', 2, 'https://www.tutorialexample.com']
In this example, we create an empty python list l first. Then,we create two iterable objects, a python list l1 and a python tuple l2. Finally, we will add the elements in l1 and l2 to the end of l1 one by one.
Notice: you should notice list.append() and list.extend() will return None.
+ operation
__add__(self, value: List) -> List
Python + operation will recevie a list object, then return a new list, which is very similar to python.extend() except it will return a new python list.
We will use an example to explain it.
l = [1, 2] #python list l1 = [1, 'tutorialexample.com'] l_new = l + l1 print(l) print(l_new)
The result is:
old python list l: [1, 2]
new pythn list l_new: [1, 2, 1, ‘tutorialexample.com’]
In this example, we use + operation to add l and l1, which will add the elements in l1 to the end of l one by one, then return a new python list l_new to save all elements and the l is not changed.
+= operation
__iadd__(self, value: Iterable) -> None
This function will recevie an iterable obect, which is similar to python list.extend()
Here is an example:
l = [1, 2] #python list l1 = [1, 'tutorialexample.com'] l += l1 print(l)
Run this python script, python l is: [1, 2, 1, ‘tutorialexample.com’], which means l += l1 is equivalent to l.extend(l1).
To summarize:
Operation | Function | Return Value |
list.append() | Add any type data to the end | return None |
list.extend() | Add elements in an iterable to the end one by one | return None |
+ | like list.extend() | return new python list |
+= | is same to list.extend() | return None |