Add Elements to a List in Python
Add List Items in Python
In Python, lists are dynamic data structures that allow you to store multiple items. This lesson will cover various methods to add items to a list, including appending items, inserting items at specific positions, and extending lists with elements from other collections.
1. Append Items
To add an item to the end of a list, you can use the append()
method. This method modifies the original list by adding the specified item to the end.
Example:
Using the append()
method to add an item:
python
1thislist = ["apple", "banana", "cherry"]
2thislist.append("orange") # Adding "orange" to the end of the list
3print(thislist) # Output: ['apple', 'banana', 'cherry', 'orange']
2. Insert Items
If you want to insert a list item at a specific index instead of appending it to the end, you can use the insert()
method. This method allows you to specify the index where you want to add the new item.
Example:
Insert an item in the second position:
python
1thislist = ["apple", "banana", "cherry"]
2thislist.insert(1, "orange") # Inserting "orange" at index 1
3print(thislist) # Output: ['apple', 'orange', 'banana', 'cherry']
Note:
After using the examples above, the lists will now contain four items.
3. Extend List
To append elements from another list to the current list, you can use the extend()
method. This method adds each element of the iterable to the end of the list.
Example:
Add the elements of tropical
to thislist
:
python
1thislist = ["apple", "banana", "cherry"]
2tropical = ["mango", "pineapple", "papaya"]
3thislist.extend(tropical) # Appending elements from tropical to thislist
4print(thislist) # Output: ['apple', 'banana', 'cherry', 'mango', 'pineapple', 'papaya']
4. Add Any Iterable
The extend()
method is versatile and can be used to add elements from any iterable object, not just lists. This includes tuples, sets, and dictionaries.
Example:
Add elements of a tuple to a list:
python
1thislist = ["apple", "banana", "cherry"]
2thistuple = ("kiwi", "orange")
3thislist.extend(thistuple) # Appending elements from the tuple to thislist
4print(thislist) # Output: ['apple', 'banana', 'cherry', 'kiwi', 'orange']