Here is the general syntax to append your item to the end of a list:
list_name.append('new item')
Let’s now see how to apply this syntax 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, let’s create a list of products in Python:
product_list = ['Oven', 'Toaster', 'Dishwasher', 'Microwave', 'Refrigerator'] print(product_list)
Once you run the code in Python, you’ll get the following list:
['Oven', 'Toaster', 'Dishwasher', 'Microwave', 'Refrigerator']
Step 2: Append an item to a list
To append an item to the end of the list, you may use the following template:
list_name.append('new item')
For example, let’s say that you want to append the product ‘Blender’ to the product_list.
You may then use the following code to append the item:
product_list = ['Oven', 'Toaster', 'Dishwasher', 'Microwave', 'Refrigerator'] product_list.append('Blender') print(product_list)
Notice that the new item (i.e., ‘Blender’) was added to the end of the list:
['Oven', 'Toaster', 'Dishwasher', 'Microwave', 'Refrigerator', 'Blender']
Appending Multiple Items to a List in Python
Let’s suppose that you want to add 3 products to the original list:
- Blender
- Juicer
- Mixer
In that case, you may use extend to add the 3 products to the original list:
product_list.extend(['Blender', 'Juicer', 'Mixer'])
So the complete Python code would look like this:
product_list = ['Oven', 'Toaster', 'Dishwasher', 'Microwave', 'Refrigerator'] product_list.extend(['Blender', 'Juicer', 'Mixer']) print(product_list)
You’ll now see the 3 new products at the end of the list:
['Oven', 'Toaster', 'Dishwasher', 'Microwave', 'Refrigerator', 'Blender', 'Juicer', 'Mixer']