How to add an element to a list in Python
Published on Aug. 22, 2023, 12:15 p.m.
To add an element to a list in Python, you can use the append()
method or the insert()
method.
Here’s an example using the append()
method:
my_list = [1, 2, 3]
my_list.append(4)
print(my_list) # Output: [1, 2, 3, 4]
In this example, the append()
method is used to add the number 4 to the end of the my_list
list.
Here’s an example using the insert()
method:
my_list = [1, 2, 3]
my_list.insert(1, 4)
print(my_list) # Output: [1, 4, 2, 3]
In this example, the insert()
method is used to add the number 4 to index 1 of the my_list
list, pushing the original element at that position and subsequent elements one index to the right.
You can also use the extend()
method to append multiple elements from another list to the end of the current list.
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list1.extend(list2)
print(list1) # Output: [1, 2, 3, 4, 5, 6]