Adding Items to a List in python
Python lists are dynamic, which means you can add new items to them whenever needed. Python provides several built-in methods to add items to a list, including append(), insert(), and extend().
In this tutorial, you'll learn how to use these methods with practical examples.
Using append()
The method adds a single item to the end of a list.
append()
Syntax
list_name.append(item)
Example
fruits = ["Apple", "Banana", "Mango"]
fruits.append("Grapes")
print(fruits)
Output:
['Apple', 'Banana', 'Mango', 'Grapes']
The new item "Grapes" is added to the end of the list.
Using insert()
The method adds an item at a specific position in the list.
insert()
Syntax
list_name.insert(index, item)
Example
fruits = ["Apple", "Banana", "Mango"]
fruits.insert(1, "Orange")
print(fruits)
Output:
['Apple', 'Orange', 'Banana', 'Mango']
The item "Orange" is inserted at index 1, and the existing items shift to the right.
Using extend()
The method adds multiple items from another list (or iterable) to the end of the current list.
extend()
Syntax
list_name.extend(iterable)
Example
fruits = ["Apple", "Banana"]
fruits.extend(["Orange", "Grapes", "Mango"])
print(fruits)
Output:
['Apple', 'Banana', 'Orange', 'Grapes', 'Mango']
The items from the second list are added to the end of the original list.
Difference Between append() and extend()
Using append()
fruits = ["Apple", "Banana"]
fruits.append(["Orange", "Grapes"])
print(fruits)
Output:
['Apple', 'Banana', ['Orange', 'Grapes']]
Using extend()
fruits = ["Apple", "Banana"]
fruits.extend(["Orange", "Grapes"])
print(fruits)
Output:
['Apple', 'Banana', 'Orange', 'Grapes']
adds the entire list as a single item, while append() adds each item individually.
extend()
| Method | Description |
|---|---|
append()
|
Adds a single item to the end of a list |
insert()
|
Adds an item at a specific position |
extend()
|
Adds multiple items from another iterable |