How to Append Objects in a List in Python
Last Updated :
27 Nov, 2024
Improve
The simplest way to append an object in a list using append() method. This method adds an object to the end of the list.
a = [1, 2, 3]
#Using append method to add object at the end
a.append(4)
print(a)
Output
[1, 2, 3, 4]
Let's look into various other methods to append object in any list are:
Table of Content
Using extend() Method
If we want to add each item from one list to another, we can use the extend() method. This method adds each element from the second list to the first list individually.
a = [1, 2, 3]
# list 'a' by adding elements from the list
a.extend([4, 5])
print(a)
Output
[1, 2, 3, 4, 5]
Using += Operator
Another way to append items from one list to another is by using the += operator. This works like extend() and adds each element of the second list to the first.
a = [1, 2, 3]
b = [4, 5]
#Using += operator to add element
a += b
print(a)
Output
[1, 2, 3, 4, 5]
Using List Comprehension
List comprehension is a shorter way to append objects while performing some operation on them. It is useful when we want to create a new list based on an existing one.
a = [1, 2, 3]
#Using list comphrehension
#Adds [3, 4] to the end of 'a'
a += [x + 3 for x in range(2)]
print(a)
Output
[1, 2, 3, 3, 4]