In Python, lists are dynamic which means that they allow further adding elements unlike many other languages. In this article, we are going to explore different methods to add elements in a list. For example, let's add an element in the list using append() method:
a = [1, 2, 3]
a.append(4)
print(a)
Output
[1, 2, 3, 4]
Explanation: append() method adds one element to the end of a list, hence a.append(4) adds 4 to the end of the list a.
Let’s explore the different methods to add elements to a list.
Using extend() to add multiple elements
To add multiple elements at once, use the extend() method. It appends each item from an iterable (like a list) to the existing list.
a = [1, 2, 3]
a.extend([4, 5, 6])
b = [x for x in range(7, 10)]
a.extend(b)
print(a)
Output
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Explanation:
- extend([4, 5, 6]) adds each item from the list to a.
- b is created using list comprehension and added using extend(b).
Using insert() to add elements at a specific position
If we want to add an element at a specific index in the list then we can use insert() method.
a = [1, 2, 3]
a.insert(1, 100)
print(a)
Output
[1, 100, 2, 3]
Explanation: insert(1, 100) inserts 100 at index 1, shifting the existing elements right.
Using List Concatenation
We can also add elements by combining two lists using the + operator. This creates a new list with the combined values.
a = [1, 2, 3]
a = a + [4, 5]
print(a)
Output
[1, 2, 3, 4, 5]
Explanation: [4, 5] is joined to a using the + operator.
Note: This creates a new list, unlike append() and extend() which modify the list in place.
Related articles: