Python - Add List Items
Append Items
To add an item to the end of the list, use theappend() method:
Example
Using theappend()
method to append an item:
thislist.append("orange")
print(thislist)
Insert Items
To insert a list item at a specified index, use theinsert()
method.
Theinsert()
method inserts an item at the specified index:
Example
Insert an item as the second position:
thislist.insert(1, "orange")
print(thislist)
Note: As a result of the examples above, the lists will now contain 4 items.
Extend List
To append elements fromanother list to the current list, use theextend()
method.
Example
Add the elements oftropical
tothislist
:
tropical = ["mango", "pineapple", "papaya"]
thislist.extend(tropical)
print(thislist)
The elements will be added to theend of the list.
Add Any Iterable
Theextend()
method does not have to appendlists, you can add any iterable object (tuples, sets, dictionaries etc.).
Example
Add elements of a tuple to a list:
thistuple = ("kiwi", "orange")
thislist.extend(thistuple)
print(thislist)