TracksPractical Coding FoundationsWorking With DataAdding and Removing Items(3 of 9)

Adding and Removing Items

Lists aren't static — they grow and shrink as your program runs. Python provides several methods (functions attached to lists) for modifying their contents.

Adding Items

The most common way to add an item is append(), which adds to the end:

fruits = ["apple", "banana"]
fruits.append("cherry")
print(fruits)  # ['apple', 'banana', 'cherry']

If you need to add at a specific position, use insert():

fruits = ["apple", "cherry"]
fruits.insert(1, "banana")  # Insert at index 1
print(fruits)  # ['apple', 'banana', 'cherry']

The first argument is the index where the new item should go. Everything at that position and after shifts to make room.

Removing Items

To remove an item by its value, use remove():

fruits = ["apple", "banana", "cherry"]
fruits.remove("banana")
print(fruits)  # ['apple', 'cherry']

If the value appears multiple times, remove() only deletes the first occurrence. If the value isn't in the list, you'll get a ValueError.

To remove by position and get the item back, use pop():

fruits = ["apple", "banana", "cherry"]
last = fruits.pop()      # Removes and returns 'cherry'
first = fruits.pop(0)    # Removes and returns 'apple'
print(fruits)            # ['banana']
print(last)              # cherry

Without an argument, pop() removes the last item. With an index, it removes that specific position.

Checking Length

Always know how long your list is with len():

fruits = ["apple", "banana", "cherry"]
print(len(fruits))  # 3

fruits.append("date")
print(len(fruits))  # 4

This is essential before accessing items by index — you can't access fruits[5] if the list only has 4 items.

Combining Lists

You can join two lists with the + operator or extend():

fruits = ["apple", "banana"]
more_fruits = ["cherry", "date"]

all_fruits = fruits + more_fruits
print(all_fruits)  # ['apple', 'banana', 'cherry', 'date']

# Or modify in place:
fruits.extend(more_fruits)
print(fruits)  # ['apple', 'banana', 'cherry', 'date']

The difference: + creates a new list, while extend() modifies the original.

See More

Further Reading

You need to be signed in to leave a comment and join the discussion