Need to append an item to a list in Python?
If so, you may use the following template to append your item to the end of a list:
ListName.append(new item to be added)
Let’s now see how to apply this template in practice.
Steps to Append an Item to a List in Python
Step 1: Create a List
If you haven’t already done so, create a list in Python.
For illustration purposes, I created the following list of names in Python:
Names = ['Jon', 'Bill', 'Maria', 'Jenny', 'Jack'] print(Names)
Once you run the code in Python, you’ll get the following list:
Step 2: Append an item to your list
To append an item to the end of your list, you may use the following template:
ListName.append(new item to be added)
For example, let’s say that you want to append the name ‘Jill’ to the Names list.
You may then use the following code to append the item:
Names = ['Jon', 'Bill', 'Maria', 'Jenny', 'Jack'] Names.append('Jill') print(Names)
Notice that the new item (i.e., ‘Jill’) was added to the end of the list:
What if you want to append multiple items to your existing list?
In the final section of this guide, I’ll show you how to append multiple items to a list.
Appending Multiple Items to a List in Python
Let’s suppose that you want to add 3 names to the original list:
- Jill
- Elizabeth
- Ben
In that case, you may use extend to add the 3 names to the original list:
Names.extend(['Jill','Elizabeth','Ben'])
So the complete Python code would look like this:
Names = ['Jon', 'Bill', 'Maria', 'Jenny', 'Jack'] Names.extend(['Jill','Elizabeth','Ben']) print(Names)
You’ll now see the 3 names at the end of the list:
Conclusion
You just saw how to append item/s to a list in Python.
At times, you may need to modify an existing item within a list. If that the case, you may then want to check the following source the explains the steps to modify an item in a list.