API Navigator Logo

Appending Items to a Python List

Author: Newtum

This guide explains how to add items to the end of a list in Python using the `append()` and `extend()` methods.

Using `list.append()` to Add a Single Item

The `.append()` method adds a single element to the end of the list. The list is modified in-place.

my_list = [1, 2, 3]
print(f"Original list: {my_list}")

my_list.append(4)
print(f"After appending 4: {my_list}")

# You can append any object, including another list
my_list.append([5, 6])
print(f"After appending a list: {my_list}")

Using `list.extend()` to Add Multiple Items

The `.extend()` method iterates over an iterable (like another list) and adds each of its elements to the end of the list. This is different from `append()`, which would add the iterable as a single nested element.

list_a = [1, 2, 3]
list_b = [4, 5, 6]
print(f"List A: {list_a}")
print(f"List B: {list_b}")

list_a.extend(list_b)
print(f"List A after extend: {list_a}")

Using the `+` Operator

You can also use the `+` operator to concatenate two lists, which creates a new list. This is less memory-efficient than `extend()` if you don't need to preserve the original list.

list1 = [1, 2, 3]
list2 = [4, 5, 6]

new_list = list1 + list2
print(f"New concatenated list: {new_list}")