Python List extend()

The extend() method adds all the items of a specified iterable (such as lists, dictionaries or any custom iterable) to the end of a list. Here's a quick example.

numbers1 = [3, 4, 5]
numbers2 = (10, 20)

# Extend numbers1 list by adding all the items from numbers2
numbers1.extend(numbers2)

print(f"numbers1 = {numbers1}")
print(f"numbers2 = {numbers2}")

Output

numbers1 = [3, 4, 5, 10, 20]
numbers2 = (10, 20)

extend() Syntax

The syntax of extend() is:

my_list.extend(iterable)

Arguments

The extend() method takes a single iterable object, such as lists, strings or any custom iterable. If we pass a value other than an iterable, we'll get TypeError.

Return Value

The method doesn't return any value (it returns None).


Example: Passing a Non-Iterable Object

numbers = [3, 4, 5]

# This results in TypeError
numbers.extend(6)

print(numbers)

Output

Traceback (most recent call last):
  File "<main.py>", line 4, in <module>
TypeError: 'int' object is not iterable

Example: Passing Dictionaries to extend()

If we pass a dictionary to extend(), its keys are added to the list.

words = ["apple", "ball"]
alphabets_words = {"c": "cat", "d": "dog"}

words.extend(alphabets_words)

print(words)

Output

['apple', 'ball', 'c', 'd']

If we need to add values instead of keys, we can pass alphabets_words.values(). And if we need to add both keys and values, we can use alphabets_words.items(), which adds the key-value pair as a tuple.

words1 = ["apple", "ball"]
words2 = ["apple", "ball"]
alphabets_words = {"c": "cat", "d": "dog"}

words1.extend(alphabets_words.values())
print(words1)

words2.extend(alphabets_words.items())
print(words2)

Output

['apple', 'ball', 'cat', 'dog']
['apple', 'ball', ('c', 'cat'), ('d', 'dog')]

Example: Passing Strings to extend()

If we pass a string to extend(), individual characters of the string are added to the list. If we need to add the string itself as an item, use the append() method.

characters = ["a", "b"]
characters.extend("cde")

print(characters)

# Output: ['a', 'b', 'c', 'd', 'e']

Using + to Extend a List

We can also extend a list using the + operator. The difference is that using + creates a new list, rather than modifying the existing list.

a = [1, 2]
b = [3, 4]

result = a + b

print(a) # Output: [1, 2]
print(result) # Output: [1, 2, 3, 4]
Did you find this article helpful?