Append Multiple Items to a List in Python

In Python, you can append multiple items to a list in several ways. Here are the 5 most common approaches:

(1) Using extend()

The extend() method allows you to add all the elements from an iterable such as another list, tuple, or set to the end of the list. This method modifies the original list.

For example:

my_list = [5, 10, 15]

my_list.extend([20, 25, 30])
print(my_list) # Output: [5, 10, 15, 20, 25, 30]

This is the most straightforward and efficient method to add multiple items to the list.

(2) Using + operator

You can concatenate two or more lists using the + operator. This creates a new list.

For example:

my_list = [5, 10, 15]

new_list = my_list + [20, 25] + [30, 35, 40]
print(new_list) # Output: [5, 10, 15, 20, 25, 30, 35, 40]

(3) Using unpacking operator

The unpacking operator (*) is used to unpack elements from an iterable, such as a list, tuple, set, or dictionary into individual elements.

You can use the unpacking operator to combine elements from an existing list (or other iterable) with new elements.

For example:

my_list = [5, 10, 15]
new_items = [20, 25, 30]

# Create a new list using unpacking
new_list = [*my_list, *new_items]
print(new_list) # Output: [5, 10, 15, 20, 25, 30]

# Another example with individual elements
another_list = [*new_list, 35, 40]
print(another_list) # Output: [5, 10, 15, 20, 25, 30, 35, 40]

(4) Using append() in a loop

The append() method adds a single element to the end of the list. However, you can use it within a loop to add multiple items.

For example:

my_list = [5, 10, 15]
new_items = [20, 25, 30]

for item in new_items:
    my_list.append(item)

print(my_list)  # Output: [5, 10, 15, 20, 25, 30]

This approach is less efficient compared to using extend() method.

(5) Using += operator

The += operator is a shorthand for extending a list. This modifies the original list.

For example:

my_list = [5, 10, 15]

my_list += [20, 25, 30]
print(my_list)  # Output: [5, 10, 15, 20, 25, 30]