There are many ways in Python to add items to the list. List most used method append adds the item to the end of an existing list.
- append(): add item end of the list.
- insert(): inserts the item before the given index.
- extend(): extends the list by adding elements from the iterable.
- List Concatenation: Use + operator to concatenate multiple lists.
Example code add to list in Python
Let’s see all the above methods example code and its purpose.
1. Adds an element to the end of a list
Use the append() method:
alpha = ["A", "B", "C"]
alpha.append("D")
print(alpha)
Output:
2. Insert a list item at a specified index
To insert a list item at a specified index, use the insert() method.
num_list.insert(index, num)
num_list = [1, 2, 3, 4, 5]
num_list.insert(2, 9)
print(num_list)
Output:
[1, 2, 9, 3, 4, 5]
3. Append elements from another list to the current list
The extend() method does not have to append lists, you can add any iterable object (tuples, sets, etc.).
list1 = ["A", "B", "C"]
tuple1 = (1, 2, 3)
list1.extend(tuple1)
print(list1)
Output:
[‘A’, ‘B’, ‘C’, 1, 2, 3]
4. Concatenate multiple lists
This will create a new list and the original lists will remain unchanged.
evens = [2, 4, 6]
odds = [1, 3, 5]
nums = odds + evens
print(nums)
Output:
[1, 3, 5, 2, 4, 6]
Do comment if you have any doubts and suggestions on this Python list topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.