PickupBrain

Python List Append() Method

Append() method is in-build Python method operating on list. Append method of python helps to add an object at the end of the existing list. It does not return the new list but instead modifies the original.

Syntax of the Append()

list.append(element)

How Does Append() Method Works

The method takes a single argument.
element – an element to be added at the end of the list
The element can be numbers, strings, dictionaries, another list, and so on. The method doesn’t return any value.

Append a Single Element at the End of List

# Creating a list
list_example = [1,2,3,'PickupBrain']
print("List: ",list_example)

# Adding "Learn Python" in list
list_example.append("Learn Python")

# Updated list is
print('Updated list: ', list_example)

The output will be

[1, 2, 3, 'PickupBrain']
Updated list:  [1, 2, 3, 'PickupBrain', 'Learn Python']

Adding List in List

The problem of inserting a number at any index is a quite common one. But sometimes the requirement to insert the whole list into another list. These kinds of problems occur in Machine Learning while playing with data. This is also known as Nested List.

#Creating a First List
List_1 = [1,2,3,4,5]
print("First List: ",List_1)
print("The Length of First List: ",len(List_1))

# Creating a Second List
List_2 = ['PickupBrain', "Learn Python",123]
print("Second List: ",List_2)
print("The Length of Second List: ",len(List_2))

# Appending List_2 to the List_1 
List_1.append(List_2)
print('Updated List: ', List_1)
print("The Length of Updated List: ",len(List_1))

The output will be

Output:
First List:  [1, 2, 3, 4, 5]
The Length of First List:  5
Second List:  ['PickupBrain', 'Learn Python', 123]
The Length of Second List:  3
Updated List:  [1, 2, 3, 4, 5, ['PickupBrain', 'Learn Python', 123]]
The Length of Updated List:  6

Conclusion

Adding an element at the end of the List is very simple and easy in Python. However if you try to append a list into another list using this method, the entire list is added as a single element to the original list. Irrespective of the size of appended data, length of the original list is always increased by one. To avoid this problem, use extend method.

Also read :
Length of List in Python

List in Python

Leave a Reply