Python List Comprehensions

This is a detailed tutorial on List Comprehension in Python. Learn to create lists in a concise way with examples using Python List Comprehension.

Python List Comprehension

It is a great way of creating lists in Python without the need for individually specifying every element of the list. This helps you to create logical and very large lists in just a single line of code, concisely.

List Comprehension is basically a syntax in Python that lets you define the logic to create lists dynamically. You basically define how each of the elements has to be created. So, when you define to the computer how to generate the elements of the list, you eliminate the need of defining each and every element of the list yourself. The computer will do the work for you.

List Comprehension Syntax

There are several different syntaxes that you can actually follow to generate a list using comprehension. In the syntax given below, everything has to be written within square brackets as defined below.

generated_list = [expression(x) for x in existing_list if condition(x)]

The above syntax will return a list that you might have otherwise generated using the following code.

generated_list = []
for x in existing_list:
    if condition(x):
        generated_list.append(expression(x))

It might be a bit confusing for beginners to understand this kind of syntax. Let’s try to figure out everything.

Firstly, we’ve created an empty list, generated_list. Next, we’re iterating over the existing_list. Next, we’re checking if the iterating element of the existing_list satisfies the condition. If yes, then we’re simply calculating a new value by evaluating an expression that takes into account the value of the iterating existing_list elements. We’re simply appending this value to the initially empty list generated_list.

This way the generated_list variable will hold a new list with evaluated list elements from the elements of the existing_list list variable. The single line of list comprehension also does the same thing.

[expression(x) for x in existing_list if condition(x)]

Let’s make this line of code making use of list comprehension more readable.

It is basically evaluating a list for which every element x of existing_list satisfied the condition then it will evaluate a new value by feeding x into an expression and consequently will add the so evaluated value to the returning list.

Examples

Let’s understand some examples to understand the concept of List Comprehension in Python better. We’ll begin with the simplest example.

Generating a Simple List of Integers

The following list comprehension will generate a list of integers from 1 to 25.

integers_list = [x for x in range(1,26)]
print(integers_list)

The screenshot of the output shows the list so generated.

Python List Comprehension Simple Example

You could also have used simple Python For Loop for doing the same, but List comprehension is simply better.

integers_list = []
for x in range(1,26):
    integers_list.append(x)
print(integers_list)

And it also gives the same output as shown in the following screenshot.

Generating Lists In Python Example Simply Using For Loop

Creating a List of Integer Squares

The first example was quite simple but this example will make you realize the importance of List Comprehension in Python. Let’s evaluate the square of the first 10 positive integers using it. The code remains a single line.

squares = [x*x for x in range(1,11)]
print(squares)

Generating List Of Squares Using List Comprehension Example

Till now, we’ve been generating lists without conditions. Let’s add a condition for the same example. Now, we’ll generate a list containing the square of only odd integers. All we need to do is to add a simple condition to check whether the number is odd or not in the last of the list comprehension.

oddSquares = [x*x for x in range(1,11) if x % 2 != 0]
print(oddSquares)

The output shows that it generates a list of odd integer squares.

List Comprehension Example With Condition

Similarly, you can create as many lists as you want with numerous conditions and possibilities.

Using Functions With List Comprehension

You can make use of your own defined functions to evaluate expressions for the list to be generated or even to check a condition. Examples illustrating both of these are given below.

We’ve defined a function fahrenheit in the following code snippet that converts temperature in Celsius to Fahrenheit. Then we used this function to generate a list of temperature values in Fahrenheit for integer values 0 to 9 that is in celsius. So, the list so obtained using this comprehension contains values of temperature in Fahrenheit for the corresponding celsius integer values from 0 to 9.

def fahrenheit(celsius):
    return (celsius * 1.8) + 32
values = [fahrenheit(x) for x in range(10)]
print(values)

Python List Comprehension With Functions Example

The first element of the generated list is 32.0 ºF which is 0 ºC and the last element is 48.2 ºF and which corresponds to 9 ºC. Now, let’s just extend this example by creating a condition function and then making use of that function for checking the condition in a list comprehension.

def fahrenheit(celsius):
    return (celsius * 1.8) + 32
def isMultipleOf5(x):
    if x % 5 == 0:
        return True
    else:
        return False
values = [fahrenheit(x) for x in range(50) if isMultipleOf5(x)]
print(values)

The screenshot of the output shows that it creates a list of temperatures in Fahrenheit from integers that are multiples of 5 from 0 to 49 and we assume them to be in Celsius. The first list element corresponds to 32.0 ºF which is 0 ºC and the last element corresponds to 113.0 ºF which is basically 45 ºC. Both of these are the multiple of 5 as our condition function checks.

Python List Comprehension Example With Condition & Expression Functions

Parsing a File Using List Comprehension

You can also use list comprehension to parse file data and it’s very simple as illustrated in this example. We have got a file with 10 lines of text.

The screenshot for the file contents is given below.

Example Text File

As you can see there are five lines, third, fifth, sixth, eighth, and tenth that contain the word, “hello”. We’ll generate a list that will contain those lines as elements that contain the word, “hello”.

file = open("hello.txt", "r")
lines = [x for x in file if "hello" in x]
print(lines)

Python List Comprehension With Files Example

This way you can read files line by line and can make use of list comprehension to generate lists with some logic and conditions.

If you find this article useful, do share it with others who might be willing to learn Python. If you have any questions related to this article, feel free to ask in the comments section.

Leave a Reply

Your email address will not be published. Required fields are marked *