Python List extend()

The extend() method in Python is used to add all the elements of an iterable (like a list, tuple, or set) to the end of the list. It modifies the original list in place and doesn’t return a new list.

Syntax

list.extend(iterable)

Parameter

iterable : Any iterable object such as another list, tuple, set, or string whose elements will be added to the list.

Return Value

None : The method modifies the list in place and does not return anything.

Example 1: Adding a list to another list

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

list1.extend(list2)
print(list1) # Output: [1, 2, 3, 4, 5, 6]

The extend() method doesn’t create a nested list but adds individual elements from the iterable to the list.

If you want to create a nested list, you can use the append() method instead.

Example 2: Adding a tuple to the list

my_list = [1, 2, 3]
my_tuple = (4, 5, 6)

my_list.extend(my_tuple)
print(my_list) # Output: [1, 2, 3, 4, 5, 6]

Example 3: Adding a string to the list

my_list = ["a", "b"]
my_str = "cd"

my_list.extend(my_str)
print(my_list) # ['a', 'b', 'c', 'd']

When you extend a list with a string using the extend() method, each character of the string is added as an individual element to the list because strings are iterable in Python.

The += Operator

The += operator is a shorthand for the extend() method. It modifies the list and doesn’t create a new list. It can add elements from any iterable, such as a list, tuple, set, or string to the list.

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

list1 += list2
print(list1) # Output: [1, 2, 3, 4, 5, 6]

Python List extend() vs append()

The extend() method unpacks the iterable and adds its individual elements to the list.

The append() method adds the entire iterable as a single element to the end of the list.

For example:

list1 = [1, 2, 3]
list1.extend([4, 5])
print(list1) # Output: [1, 2, 3, 4, 5]

list2 = [1, 2, 3]
list2.append([4, 5])
print(list2) # Output: [1, 2, 3, [4, 5]]