Computer >> Computer tutorials >  >> Programming >> Python

How to append objects in a list in Python?


To add a single element to a list in Python at the end, you can simply use the append() method. It accepts one object and adds that object to the end of the list on which it is called. 

example

my_list = [2, 3, 1, -4, -1, -4]
my_list.append(8)
print(my_list)

Output

This will give the output −

[2, 3, 1, -4, -1, -4, 8]

If you want to insert an element at a given position, use the insert(pos, obj) method. It accepts one object and adds that object at the position pos of the list on which it is called. 

example

my_list = [2, 3, 1, -4, -1, -4]
my_list.insert(1, 0)
print(my_list)

Output

This will give the output −

[2, 0, 3, 1, -4, -1, -4]

You can also concatenate 2 lists using the extend method. It accepts one list and adds all objects of that list to the end of the list on which it is called. 

example

my_list = [2, 3, 1, -4, -1, -4]
another_list = ["a", "b"]
my_list.extend(another_list)
print(my_list)

Output

This will give the output −

[2, 3, 1, -4, -1, -4, "a", "b"]