Add Elements to Python List
Lists are the most basic and useful containerized typed data structure in Python.
In this post, we'll learn about the different ways to add elements to a Python list.
1. append() function
The append()
method is the most basic function to add a new element to a list.
The append()
method adds a new element to the end of the list.
my_list = [1, 2, 3]
my_list.append(4)
print(my_list) # Output: [1, 2, 3, 4]
2. Append to the front of the list
If you want to add a new element to the front of the list, you can use the insert()
method.
The insert()
method can be used to add a new element at any index you want.
To add an element to the front, enter the index 0
, as shown in the example below.
my_list = [1, 2, 3]
my_list.insert(0, 0)
print(my_list) # Output: [0, 1, 2, 3]
3. How to add using a loop
To add multiple elements to a list, you can use a loop. Using the for
statement, you can easily add multiple elements to a list.
my_list = [1, 2, 3]
for i in range(4, 7):
my_list.append(i)
print(my_list) # Output: [1, 2, 3, 4, 5, 6]
4. Adding multiple Python list elements
To add multiple elements to a list at once, you can use the extend()
method.
my_list = [1, 2, 3]
my_list.extend([4, 5, 6])
print(my_list) # Output: [1, 2, 3, 4, 5, 6]
5. Python list append input
It's very simple to take input from a user and add it to a list. The code below is an example of taking input from a user and adding it to a list.
my_list = []
user_input = input("Please enter a value to add to the list: ")
my_list.append(user_input)
print(my_list) # Output: [value entered by user]
6. Deduplicate Python list additions
To remove duplicates when adding elements to a list, you need to use the in
keyword to check if the element already exists in the list before adding it.
my_list = [1, 2, 3]
new_item = 3
if new_item not in my_list:
my_list.append(new_item)
print(my_list) # output: [1, 2, 3]
7. Adding a list to a Python list
To add another list to a list, you can use the extend()
method that we used earlier to add multiple elements.
my_list1 = [1, 2, 3]
my_list2 = [4, 5, 6]
my_list1.extend(my_list2)
print(my_list1) # Output: [1, 2, 3, 4, 5, 6]
8. Adding a Python dictionary list
To add a list to a dictionary, simply specify the keys of the dictionary and add the list as a value.
Lists are not immutable data structures, so they cannot be used as keys in a dictionary.
For more information on the immutability of container types, see this post.
my_dict = {"key1": 1, "key2": 2}
my_dict["key3"] = [3, 4, 5]
print(my_dict) # Output: {"key1": 1, "key2": 2, "key3": [3, 4, 5]}
Conclusion
In this article, we learned about different ways to add elements to a Python list. Python provides a variety of methods and functions that make it easy to accomplish these tasks.
I hope you found this post useful, because once you learn a basic technique, you'll use it for life.
