Python – Add List Items
In Python, you can add new items to a list using several built-in methods. Lists are mutable, which means you can change them by appending, inserting, or extending.
Visualizing the List Structure
Given:
fruits = ["apple", "banana", "cherry"]
Index mapping:
Index: 0 1 2
Items: "apple" "banana" "cherry"1. append() – Add an Item to the End
The append() method adds a single item at the end of the list.
Example:
fruits = ["apple", "banana", "cherry"]
fruits.append("orange")
print(fruits)Output:
['apple', 'banana', 'cherry', 'orange'] append() does not insert into a specific position.
2. insert() – Add an Item at a Specific Position
The insert(index, item) method allows you to insert an item at any index.
Example:
fruits = ["apple", "banana", "cherry"]
fruits.insert(1, "mango")
print(fruits)
Output:
['apple', 'mango', 'banana', 'cherry']Here, "mango" is inserted at index 1, shifting the other items forward.
3. extend() – Add Multiple Items from Another List
The extend() method adds each item from another iterable (like a list) to the end.
Example:
fruits = ["apple", "banana"]
tropical = ["pineapple", "papaya"]
fruits.extend(tropical)
print(fruits)Output:
['apple', 'banana', 'pineapple', 'papaya']extend() unpacks the iterable and adds each element.
4. Add Items Using + Operator (Concatenation)
You can also use + to merge two lists.
Example:
list1 = ["a", "b"]
list2 = ["c", "d"]
result = list1 + list2
print(result)Output:
['a', 'b', 'c', 'd']This creates a new list, it does not modify list1.
5. Add Items Using Loop
You can add items one by one using a loop and append().
Example:
numbers = []
for i in range(3):
numbers.append(i)
print(numbers)Output:
[0, 1, 2]Negative Index Reminder (Doesn't Apply Here)
When adding, you cannot use negative indexes like -1 with insert() to put items at the end. Use append() instead.
Example:
fruits.insert(-1, "grape")
print(fruits)May not behave as expected if you're thinking it adds to the end — it actually inserts before the last item.
Summary of Methods
| Method | Description | Syntax Example |
|---|---|---|
append() | Adds item to end | fruits.append("orange") |
insert() | Adds item at specific index | fruits.insert(1, "mango") |
extend() | Adds multiple items from iterable | fruits.extend(["pine", "papaya"]) |
+ operator | Joins lists into a new list | list1 + list2 |