AppDividend
Latest Code Tutorials

Python List Extend Example | extend() Method Tutorial

0

Python List Extend Example | extend() Method Tutorial is today’s topic. Python extend() method adds the specified list elements (or any iterable) to the end of the current list.  The extend() extends the list by adding all items of the list (passed as an argument) to an end.

Python List Extend Example

The syntax for python list extend() method is following.

list.extend(iterable)

An iterable parameter is required, and it is iterable like set, tuple, list. The extend() method does not return any value but add the content to the existing list.

Let us take an example. My current version of Python is 3.

# app.py

GoT = ['Daenerys', 'Jon', 'Tyrion']
Friends = ['Rachel', 'Monica', 'Phoebe']
GoT.extend(Friends)
print(GoT)

Run the file.

python3 app.py

 

Python List Extend Example | extend() Method Tutorial

So, we have added one list to the other, and the output will be six items of the list. It is entirely different behavior then python list append() method example. In that case, we have only four elements, and the 4th one is added as a whole item. So, if you kind of merge to lists then list extend() method is beneficial.

Add Elements of Tuple To List

Let us extend a tuple to the list.

# app.py

GoT1_list = ['Daenerys', 'Jon', 'Tyrion']
Friends1_tuple = ('Rachel', 'Monica', 'Phoebe')
GoT1_list.extend(Friends1_tuple)
print(GoT1_list)

In the above example, we have taken one list and one tuple. Now, we try to add the tuple to a list. The output is following. It will become a single list.

 

Add Elements of Tuple To List

Add Elements of Set To List

Now, we take a Set and add to the List.

# app.py

MJSongs_list = ['Dangerous', 'Smooth criminal', 'Bad']
DrakeSongs_set = {'In my feelings', 'Mia'}
MJSongs_list.extend(DrakeSongs_set)
print(MJSongs_list)

 

 

Add Elements of Set To List

It becomes one list and includes all the elements in a single list. 

The Python native datatypes like tuple and set passed to extend() method is automatically converted to a list. And, the items of the list are appended to the end.

Finally, Python List Extend Example | extend() Method Tutorial is over.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.