In this section, we will learn what the List append() method is and how to use it in Python.
Python adding to a List: append() Function in Python
The Python List append() method is used to append (add) a new element to the end of a list object.
Python List append() Method Syntax:
List append() Method Parameters:
The method takes one argument and that is the element we want to add to the end of the target list.
Note that if the target element is itself another list, the list will be added as a single element to the list object that invoked the method. This means the target list will have a sub-list as part of its elements.
List append() Method Return Value:
The method does not return a value.
Example: append to a list in python
list1 = [1,2,3,4] list1.append(5) list1.append(6) list1.append(7) print(list1)
[1, 2, 3, 4, 5, 6, 7]
Append a List in Python
As mentioned before, the element we add to a list using the `append()` method could be anything from a value of basic data type to another list.
But if we set a list as the argument of the append() method, that list becomes a single element in the target list. This means the index position where the sub-list is assigned there is just a pointer to the actual list that we’ve passed as the argument. So using this index position, we can access the target list and change its values and this change will be seen using the variable of the target list as well, because both pointers are pointing to the same array.
Example: appending a list in python
list1 = [1,2,3,4] list2 = [5,6,7,8,9] list1.append(list2) list1 = "Elon" print(list1) print(list2)
[1, 2, 3, 4, ['Elon', 6, 7, 8, 9]] ['Elon', 6, 7, 8, 9]