DEV Community

Cover image for List Comprehensions in Python
Ashish Panchal
Ashish Panchal

Posted on

4

List Comprehensions in Python

List comprehensions provide a way to create lists, where each element will be derived from an operation applied to each member of another sequence or iterable or to create another a subsequence with elements that satisfy particular condition.

Use-case 1: Lets calculate squares of all numbers from 1 to 10

Without List Comprehension:

squares = []

for x in range(10):
    squares.append(x**2)

print squares

With List Comprehension:

List comprehension consists of square brackets containing an expression followed by a one or multiple for loops or if clauses. Now, lets calculate squares using list comprehension

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

Use-case 2: If the resulting data is a tuple, the expression must be parenthesised.

Example: Lets fetch indices of matching elements from two lists. For example:
first_list = [2, 5, 6]
second_list = [5, 6, 1]
Output : [(1, 0), (2, 1)]

Without List Comprehension:

first_list = [2, 5, 6]
second_list = [5, 6, 1]

result = []

for i in range(len(first_list)):
    for j in range(len(second_list)):
        if first_list[i] == second_list[j]:
            result.append((i, j))

print result

With List Comprehension:

first_list = [2, 5, 6]
second_list = [5, 6, 1]

result = [(i, j) for i in range(len(first_list)) for j in range(len(second_list)) if first_list[i] == second_list[j]]

print result

Use-case 3: Nested list comprehension

Nested list comprehension is a list comprehension within another list comprehension just like nested for loops.

Lets take a popular example of flattening a 2D matrix:

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

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

Without List Comprehension:

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

for row in matrix:
    for val in row:
        result.append(val)

print result

With List Comprehension:

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

result = [val for row in matrix for val in row]

print result

We can use multiple for loops or if clauses to achieve any result but list comprehensions make it very concise and readable.

Happy Coding! 👨‍💻

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay