How to Use the Python List extend() Method

09/09/2021

Contents

In this article, you will learn how to use the Python list extend() method.

Python List extend() Method

The extend() method is a built-in function of Python lists, which means it’s always available for use, without the need for any import statement. This method is called on a list object and takes an iterable object as an argument, which can be a list, tuple, string, or any other iterable object. The method appends all the elements of the iterable object to the end of the list.

Syntax

Here’s the syntax for the extend() method:

list.extend(iterable)
Parameters
  • list: The list object
  • iterable: The list, tuple, or any other iterable object that you want to add to the list.
Example

Here’s an example of using the extend() method:

fruits = ['apple', 'banana', 'cherry']
more_fruits = ['orange', 'mango', 'grapes']
fruits.extend(more_fruits)
print(fruits)

#Output:
#['apple', 'banana', 'cherry', 'orange', 'mango', 'grapes']

As you can see, the extend() method has added all the elements of the more_fruits list to the end of the fruits list.

Here are a few additional things to keep in mind when using the extend() method:

Modifying a List

The extend() method modifies the original list in place, i.e., it extends the original list and doesn’t return a new list. If you need a new list, you can use the + operator to concatenate two lists, or you can use the extend() method followed by slicing.

Appending Elements

The extend() method appends all the elements of the iterable object to the end of the list. The elements are added in the order they appear in the iterable object.

Performance

The extend() method is faster than using the + operator to concatenate two lists because it modifies the original list in place, rather than creating a new list. However, this performance gain comes at the cost of memory usage, as the extend() method modifies the original list, whereas the + operator creates a new list.

Iterating Over Iterables

If you want to add elements from an iterable object to a list, the extend() method is an easy and efficient way to do so. Simply pass the iterable object as an argument to the extend() method, and all its elements will be added to the end of the list.

In conclusion, the extend() method is a useful and versatile tool for working with lists in Python. Whether you’re concatenating two lists or adding elements from an iterable object to a list, the extend() method provides a simple and efficient way to do so.