← Back to Articles
Tutorial

How to Extend a List in Python

Learn how to effectively use the extend() method in Python to add multiple elements to a list.

Python is a versatile programming language, widely used for various applications. One of its fundamental data structures is the list, which can dynamically grow as needed. In this article, we'll explore how to extend a list in Python efficiently.

The extend() method in Python is specifically designed for adding multiple elements to an existing list. Unlike append(), which adds its argument as a single element, extend() takes an iterable and adds each element to the list individually. For example, if you have a list [1, 2, 3] and you want to add elements [4, 5, 6], using extend() will result in [1, 2, 3, 4, 5, 6].

When using extend(), it's important to ensure that the argument is an iterable, such as a list, tuple, or string. This method is optimal for list concatenation, as it modifies the original list in place, which is more memory efficient than creating a new list. Additionally, consider using extend() when you have a large number of elements to add, as it is generally faster than appending each element individually in a loop.

A common mistake when using extend() is passing non-iterable objects, which will result in a TypeError. Always verify the data type of the object you're passing to avoid such errors. Another pitfall is confusing extend() with append(), which can lead to unexpected results if not used correctly.

Code Examples

Example 1

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

Example 2

fruits = ['apple', 'banana']
fruits.extend(['cherry', 'date'])
print(fruits)  # Output: ['apple', 'banana', 'cherry', 'date']

More Python Tutorials