Python List Comprehension – With Examples

In python, list comprehension is a concise way to create lists. In this tutorial, we’ll cover what are list comprehensions, their use-cases along with some examples.

Before we proceed, here’s a quick refresher on python lists – Lists are used to store an ordered collection of items. These items can be any type of object from numbers to strings or even another list. This makes lists are one of the most versatile data structures in python to store a collection of objects. For more, check out our guide on lists and other data structures in python.

As stated above, list comprehensions offer a concise way to create a list. They are particularly useful when creating a list using another iterable (for example, list, tuple, string, dict, etc). General syntax for creating a list using list comprehension –

new_list = [expression for member in iterable]

Here, each item in the new list is the result of the expression. The following example makes it clear:

Example: Create a list storing square of values from another list.

ls = [1,2,3,4]
# new list using list comprehension
new_ls = [i*i for i in ls]
# print the lists
print("Numbers:", ls)
print("Their Squares:", new_ls)

Output:

Numbers: [1, 2, 3, 4]
Their Squares: [1, 4, 9, 16]

In the above example, we create a new list new_ls using a list comprehension where each element of the new list is the square of the corresponding element in the list ls resulting from the expression i*i.

Generally, list comprehensions can be used as a good alternative for loops, mapping, or filtering purposes. They are more Pythonic in the sense that the same simple construct can be used for different use-cases.

📚 Data Science Programs By Skill Level

Introductory

Intermediate ⭐⭐⭐

Advanced ⭐⭐⭐⭐⭐

🔎 Find Data Science Programs 👨‍💻 111,889 already enrolled

Disclaimer: Data Science Parichay is reader supported. When you purchase a course through a link on this site, we may earn a small commission at no additional cost to you. Earned commissions help support this website and its team of writers.

If you want to create a new list from another iterable, you first have to instantiate an empty list, then use a loop to iterate over the items of the iterable, perform your operations on each item, and then append the result to the new list. This process can be reduced to a single line using list comprehension.

Example: List creation comparison

ls = [1,2,3,4]
# new list using the traditional method
new_ls1 = []
for i in ls:
    new_ls1.append(i*i)

# new list using list comprehension
new_ls2 = [i*i for i in ls]

# print the lists
print("Numbers:", ls)
print("New List ls1:", new_ls1)
print("New List ls2:", new_ls2)

Output:

Numbers: [1, 2, 3, 4]
New List ls1: [1, 4, 9, 16]
New List ls2: [1, 4, 9, 16]

In the above example, we can see that to create a new list of squares, list comprehension took just one line while it required three lines using the traditional method.

Note that, the purpose of list comprehension should not be to just reduce the number of lines, the idea is to use it to make to code clean and readable.

We can use conditionals inside list comprehensions to filter out the items we don’t want. This makes list comprehensions quite versatile and gives you more control over what you want to keep inside your lists.

Example: Create a new list with only the even numbers

ls = [1,2,3,4,5,6,7,8]
# new list of only even numbers using list comprehension
new_ls = [i for i in ls if i%2==0]
# print the lists
print("Original list:", ls)
print("New list:", new_ls)

Output:

Original list: [1, 2, 3, 4, 5, 6, 7, 8]
New list: [2, 4, 6, 8]

In the above example, the conditional if i%2==0 is added at the end inside the list comprehension to filter for the even numbers. We see that the new list new_ls consists only of even numbers.

The map() function gives an iterator of the results after applying a given function to each item of a given iterable. Now, instead of using map() to apply a function to the elements of an iterable, we can use a list comprehension where we directly apply the function to the elements.

Example: map() vs list comprehension

# list of ages of people in a building
ls = [21, 16, 18, 54, 12, 68]
# function to determine voting eligibility based on age
def is_eligible_to_vote(age):
    if age >= 18:
        return True
    else:
        return False

# use the map() to get the eligibility list
eligibility_ls1 = list(map(is_eligible_to_vote, ls))

# use list comprehension to get the eligibility list
eligibility_ls2 = [is_eligible_to_vote(age) for age in ls]

# print the lists
print("Age of members:", ls)
print("Eligibility list using map:", eligibility_ls1)
print("Eligibility list using list comprehension:", eligibility_ls2)

Output:

Age of members: [21, 16, 18, 54, 12, 68]
Eligibility list using map: [True, False, True, True, False, True]
Eligibility list using list comprehension: [True, False, True, True, False, True]

In the above example, we determine the eligibility of voters in a building to cast their votes based on their age. For this, the function is_eligible_to_vote() is created which returns whether a person is eligible to vote or not. Now, we create a list storing the eligibility as boolean values for each member in the list ls first, using the map() function, map(is_eligible_to_vote, ls) resulting in a map object (an iterable) which is converted to a list using the list() function. Then, we create the same list using list comprehension.

One important advantage of list comprehension here is that it is quite readable as to what is happening to each item in the iterable, this is not the case with the map function.

There are other use cases as well for list comprehensions. You can have nested loops, complex conditionals etc. But remember, you should use them to make your code clean and more readable rather than just using complex list comprehensions to save a few lines.

For more, refer to this brilliantly written guide on when to use list comprehensions and the python docs on list comprehension.


Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.


Author

  • Piyush Raj

    Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects.

Scroll to Top