To append an item at the end of a list:
list_name.append("new item")
To add multiple items to a list:
list_name.extend(["item_1", "item_2", "item_3", ...])
Steps to Append an Item to a List in Python
Step 1: Create a List
To start, create a list in Python. For instance:
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
For example, to append the product “Blender” to the product_list:
product_list = ["Oven", "Toaster", "Dishwasher", "Microwave", "Refrigerator"]
product_list.append("Blender")
print(product_list)
Notice that the new item (“Blender'”) was added at the end of the list:
['Oven', 'Toaster', 'Dishwasher', 'Microwave', 'Refrigerator', 'Blender']
Appending Multiple Items to a List in Python
For example, to add 3 products to the original list:
- Blender
- Juicer
- Mixer
In that case, use extend to add the 3 products to the original list:
product_list.extend(["Blender", "Juicer", "Mixer"])
The complete Python code:
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']