Add List Items
What You'll Learn: In this tutorial, you'll discover how to add items to a list in Python. Lists are like containers that you can fill with different items.
Append Items
To add an item to the end of the list, use the append() method.
Example Code:
thislist = ["apple", "banana", "cherry"]
thislist.append("orange")
print(thislist)
Output: ['apple', 'banana', 'cherry', 'orange']
What's Happening Here?
thislist.append("orange")adds 'orange' to the end of the list.
Insert Items
To insert a list item at a specified index, use the insert() method.
Example Code:
thislist = ["apple", "banana", "cherry"]
thislist.insert(1, "orange")
print(thislist)
Output: ['apple', 'orange', 'banana', 'cherry']
What's Happening Here?
thislist.insert(1, "orange")inserts 'orange' at the second position.
Extend List
To append elements from another list to the current list, use the extend() method.
Example Code:
thislist = ["apple", "banana", "cherry"]
tropical = ["mango", "pineapple", "papaya"]
thislist.extend(tropical)
print(thislist)
Output: ['apple', 'banana', 'cherry', 'mango', 'pineapple', 'papaya']
What's Happening Here?
thislist.extend(tropical)adds the elements oftropicalto the end ofthislist.
Add Any Iterable
The extend() method can also append elements from any iterable object, such as tuples, sets, or dictionaries.
Example Code:
thislist = ["apple", "banana", "cherry"]
thistuple = ("kiwi", "orange")
thislist.extend(thistuple)
print(thislist)
Output: ['apple', 'banana', 'cherry', 'kiwi', 'orange']
What's Happening Here?
thislist.extend(thistuple)adds the elements ofthistupletothislist.
Try It Yourself: Fun Exercises
- Build Your Fruit Basket:
- Start with an empty list.
- Use
append()andinsert()to add different fruits to your basket.
- Combine Snack Lists:
- Create two lists with different snacks.
- Use
extend()to combine them into one big list.
Summary:
In this Python tutorial, we learned how to add items to a list using append(), insert(), and extend(). Lists are flexible and allow you to organize and update your items easily. Keep experimenting and have fun with lists in Python!