Mastering the Python List extend() Method: A Step-by-Step Guide
Python List extend() method
Python List extend() method extends the list with items from given iterable.
In this tutorial, you will learn the syntax of, and how to use List extend() method, with examples.
Syntax of List extend()
The syntax of List extend() method is
list.extend(iterable)
You can read the above expression as list extended with items from the iterable.
Parameters
extend() method can take one parameter. Let us see the parameter, and its description.
Parameter | Description |
---|---|
iterable | The items in this iterable shall be appended to the list. An iterable can be, for example, a list, a tuple, a set, keys in a dictionary, values in a dictionary, characters in a string, etc. |
Return value
extend() method returns None.
Please note that the extend() method modifies the original list.
Examples
1. Extent list with items from another list in Python
In the following program, we take a list my_list with some string values. We have to extend this list with items from an another list another_list. This another_list has two items in it.
Call extend() method on the list my_list, and pass another_list as argument to the method.
Python Program
my_list = ['apple', 'banana', 'cherry']
another_list = ['mango', 'fig']
my_list.extend(another_list)
print(my_list)
Output
['apple', 'banana', 'cherry', 'mango', 'fig']
my_list is extended with the items from another_list.
Also an observation: my_list is modified, while another_list remains unchanged.
2. Extent list with items from a tuple in Python
In the following program, we take a list my_list with some string values. We have to extend this list with items from a tuple my_tuple. This my_tuple has two items in it.
Call extend() method on the list my_list, and pass my_tuple as argument to the method.
Python Program
my_list = ['apple', 'banana', 'cherry']
my_tuple = (22, 44)
my_list.extend(my_tuple)
print(my_list)
Output
['apple', 'banana', 'cherry', 22, 44]
my_list is extended with the items from my_tuple.
Summary
In this tutorial of Python Examples, we learned about List extend() method, how to use extend() method to extend the list with the items from an iterable, with syntax and examples.
We have seen examples for how to extend a list with items from another list, or tuple. The method is same to extend a list with items from a set, characters from a string, or any iterable.