Skip to content
Home » Extending Lists in Python

Extending Lists in Python

Spread the love

Today we’ll learn how to extend lists with elements from other lists, tuples and strings.

Here’s the video version of this article:

If you use the append method to append a list to another list, the whole list is added as an element of the other list, like in this example:

>>> main_list = [2, "ooops", 1]
>>> list_of_numbers = [1, 4]
>>> main_list.append(list_of_numbers)  
>>> main_list
[2, 'ooops', 1, [1, 4]]

But what if you want to add all the elements of the other list separately to the other list? Well, this is what extending a list means.

We use the extend method to add all the elements of a list, tuple or string (the characters) to a list:

>>> main_list = [2, "ooops", 1]
>>> list_of_numbers = [1, 4]
>>> main_list.extend(list_of_numbers)  # adds elements of the list
>>> main_list
[2, 'ooops', 1, 1, 4]

You can also add all the elements of a string to a list, so all the characters one by one:

>>> just_a_string = "wow"
>>> main_list.extend(just_a_string)  # adds elements of the string
>>> main_list
[2, 'ooops', 1, 1, 4, 'w', 'o', 'w']

or all the elements of a tuple:

>>> tuple_of_acronyms = ("CNN", "FBI")
>>> main_list.extend(tuple_of_acronyms)  # adds elements of the tuple
>>> main_list
[2, 'ooops', 1, 1, 4, 'w', 'o', 'w', 'CNN', 'FBI']

An alternative way to extend a list is by means of the += operator:

>>> main_list += [1, 2, 3]
>>> main_list
[2, 'ooops', 1, 1, 4, 'w', 'o', 'w', 'CNN', 'FBI', 1, 2, 3]

Your Panda3D Magazine

Make Awesome Games and Other 3D Apps

with Panda3D and Blender using Python.

Cool stuff, easy to follow articles.

Get the magazine here (PDF).

Python Jumpstart Course

Learn the basics of Python, including OOP.

with lots of exercises, easy to follow

The course is available on Udemy.

Blender Jumpstart Course

Learn the basics of 3D modeling in Blender.

step-by-step, easy to follow, visually rich

The course is available on Udemy and on Skillshare.


Spread the love
Tags:

Leave a Reply