Append Items
The append() method puts a new item at the end of a list:
Example
Add "orange" with append():
Prompt
Create a list of fruits and use the append() method to add "orange" to the end. Print the list.
Output: complete Python program
main.py
thislist = ["apple", "banana", "cherry"]
thislist.append("orange")
print(thislist)
Insert Items
When the item belongs at a particular index, reach for insert() instead.
You give it the index and the item, and the item goes in at that spot:
Note: The list in the append() example and the list here each end up with 4 items.
Example
Put "orange" in the second position:
Prompt
Create a list of fruits and use the insert() method to add "orange" as the second item. Print the list.
Output: complete Python program
main.py
thislist = ["apple", "banana", "cherry"]
thislist.insert(1, "orange")
print(thislist)
Extend List
The extend() method takes the elements of another list and adds them to the current one.
They land at the end, after the existing elements.
Example
Add everything from tropical to thislist:
Prompt
Create two lists of fruits. Use the extend() method to add all elements from the second list to the first. Print the result.
Output: complete Python program
main.py
thislist = ["apple", "banana", "cherry"]
tropical = ["mango", "pineapple", "papaya"]
thislist.extend(tropical)
print(thislist)
Add Any Iterable
extend() isn't limited to lists. Any iterable object will work, including tuples, sets and dictionaries.
Example
Extend a list with the contents of a tuple:
Prompt
Create a list of fruits and a tuple with two more fruits. Use extend() to add the tuple elements to the list. Print the list.
Output: complete Python program
main.py
thislist = ["apple", "banana", "cherry"]
thistuple = ("kiwi", "orange")
thislist.extend(thistuple)
print(thislist)