List Comprehension in Python

Introduction

List comprehension is a concise and powerful tool for creating lists in Python. It allows you to generate lists using a single line of code, making your code more efficient and readable. In this article, we will cover the basics of list comprehension, including its syntax and some use cases.

The basic syntax of list comprehension is as follows:

β€˜[expression for item in iterable if condition]β€˜

Here, β€˜expressionβ€˜ is the value that is appended to the list, β€˜itemβ€˜ is the variable that takes each value from the iterable, and β€˜iterableβ€˜ is the source of values. The optional β€˜conditionβ€˜ is used to filter the items based on some condition.

Examples of List Comprehension

Let’s take a look at some examples to see how list comprehension works:

1. Creating a list of squares


squares = [x**2 for x in range(10)]
print(squares)

Output

[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

In this example, we use the β€˜range()β€˜ function to generate a sequence of numbers from 0 to 9. We then use list comprehension to create a new list that contains the squares of these numbers.

2. Creating a list of even numbers


numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = [x for x in numbers if x % 2 == 0]
print(even_numbers)

Output

[2, 4, 6, 8, 10]

In this example, we use list comprehension to create a new list that contains only the even numbers from an existing list of numbers.

3. Creating a list of tuples


colors = ['red', 'green', 'blue']
color_codes = [(color, code) for code, color in enumerate(colors, start=1)]
print(color_codes)

Output

[(β€˜red’, 1), (β€˜green’, 2), (β€˜blue’, 3)]

In this example, we use list comprehension to create a new list of tuples. Each tuple contains a color from an existing list of colors and its corresponding index, which is generated using the β€˜enumerate()β€˜ function.

Nested List Comprehension

Nested list comprehension is a technique used to create a list of lists in Python. It allows you to generate a list that contains other lists as its elements. The basic syntax of nested list comprehension is as follows:

β€˜[[expression for item in iterable] for item in iterable]β€˜

Here, β€˜expressionβ€˜ is the value that is appended to the inner list, β€˜itemβ€˜ is the variable that takes each value from the inner iterable, and β€˜iterableβ€˜ is the source of values for the inner list. The outer β€˜forβ€˜ loop is used to iterate over the source of values for the outer list.

Examples of Nested List Comprehension

Let’s take a look at some examples to see how nested list comprehension works:

1. Creating a matrix


matrix = [[i + j for j in range(3)] for i in range(3)]
print(matrix)

Output

[[0, 1, 2], [1, 2, 3], [2, 3, 4]]

In this example, we use nested list comprehension to create a 3Γ—3 matrix. The iteration process involves two loops: The outer loop iterates through the rows of the matrix, while the inner loop iterates through the columns. We use the expression β€˜i + jβ€˜ to generate the values for each element of the matrix.

2. Flattening a matrix


matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat_matrix = [item for sublist in matrix for item in sublist]
print(flat_matrix)

Output

[1, 2, 3, 4, 5, 6, 7, 8, 9]

In this example, we use nested list comprehension to flatten a matrix into a single list. The outer loop iterates over each sublist in the matrix, while the inner loop iterates over each item in the sublist. We use the expression β€˜itemβ€˜ to add each item to the flat list.

3. Creating a list of coordinates


coordinates = [(x, y) for x in range(3) for y in range(3) if x != y]
print(coordinates)

Output

[(0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1)]

In this example, we use nested list comprehension to create a list of coordinates. The outer loop iterates over the x-coordinates, while the inner loop iterates over the y-coordinates. We use the expression β€˜(x, y)β€˜ to create a tuple for each coordinate, and we use the β€˜ifβ€˜ statement to exclude the coordinates where β€˜xβ€˜ is equal to β€˜yβ€˜.

Advantages of List Comprehension

There are several advantages of using list comprehension in Python:

  1. Concise and Readable: List comprehension allows you to create lists with a concise and readable syntax, making your code more efficient and easier to understand.
  2. Faster Execution: List comprehension is faster than traditional for loops because it uses optimized C code in the background.
  3. Easy to Maintain: List comprehension is easier to maintain because it requires fewer lines of code, making it less prone to errors.

Exercises

Try some exercises for practicing Python list comprehension.

  1. Write a list comprehension that returns a list of all the even numbers from 1 to 50.
  2. Write a list comprehension that returns a list of all the squares of numbers from 1 to 10.
  3. Write a list comprehension that returns a list of all the prime numbers from 1 to 100.
  4. Write a list comprehension that returns a list of all the elements in a given list that are divisible by 3.
  5. Write a list comprehension that returns a list of all the words in a given sentence that have more than 5 letters.
  6. Write a list comprehension that returns a list of all the uppercase letters in a given string.
  7. Write a list comprehension that returns a list of all the unique elements in a given list.
  8. Write a list comprehension that returns a list of the first letter of each word in a given sentence.
  9. Write a list comprehension that returns a list of all the strings in a given list that start with a vowel.
  10. Write a list comprehension that returns a list of all the tuples in a given list where the sum of their elements is greater than 10.

These exercises should help you become more familiar with list comprehension in Python and improve your programming skills.

Share your love
Subhankar Rakshit
Subhankar Rakshit

Hey there! I’m Subhankar Rakshit, the brains behind PySeek. I’m a Post Graduate in Computer Science. PySeek is where I channel my love for Python programming and share it with the world through engaging and informative blogs.

Articles:Β 194