Skip to Content

4 Ways to Add to a List in Python!

4 Ways to Add to a List in Python!

Python provides multiple methods to add item(s) to a list. Let’s go through each of them in the following tutorial on how to add a list in Python. I will highlight each method with an example code snippet in Python and show you the output.

Let’s start with append().

 

How to add to a list in Python – append()

 

my_list=["cricket", "football", "hockey"]

#append an item
my_list.append("tennis")
print("Updated list:",  my_list)

 

Output

 

Updated list: ['cricket', 'football', 'hockey', 'tennis']

 

How to add to a list in Python – insert()

 

What if you want to add an item at a specific index? No worries, because Python has got you covered. The insert() method takes an index and an element as its arguments.

It adds an item at that index, and the rest of the elements get shifted to the right. Let’s see.

 

my_list=["cricket", "football", "hockey"]
#insert an item at index 1
my_list.insert(1, "tennis")
print("Updated list:",  my_list)

 

Output

 

Updated list: ['cricket', 'tennis', 'football', 'hockey']

 

If you provide an index that is greater than the length of the list, then the item would get appended to the list, i.e.,

 

my_list=["cricket", "football", "hockey"]
#insert an item at index 6
my_list.insert(6, "tennis")
print("Updated list:",  my_list)

 

Output

 

Updated list: ['cricket', 'football', 'hockey', 'tennis']

 

How to add to a list in Python – extend()

The extend() method takes an iterable and adds its element to the end of the list. Consider the following example.

 

my_list=["cricket", "football", "hockey"]
my_list.extend(["tennis", "basketball"])
print("Updated list:",  my_list)

 

Output

 

Updated list: ['cricket', 'football', 'hockey', 'tennis', 'basketball']

 

How to add to a list in Python – Slicing and Concatenation

We can also add elements to a list using slicing and the concatenation operator (+). Let’s see how.

my_list=["cricket", "football", "hockey"]

my_list[3:5] = ('tennis', 'basketball') #using slicing
print("Updated list using slicing:",  my_list)

my_list +=  ["volleyball", "badminton"] + ["table tennis"] #concatenation operator, only adds list to list
print("Updated list using +:",  my_list)

Conclusion

I hope these 4 ways to add a list in Python come in handy. Adding to a list is often used in (Python) programming and hope the outlined methods and the example syntax will help you to use it in your code and projects.

Happy coding!

Server Member Count
Previous
How to Check the Member Count on Discord (Desktop/Mobile)
How to Reverse A String in Python
Next
3 Ways to Reverse a String in Python