Loading

Quipoin Menu

Learn • Practice • Grow

python / List Comprehension
tutorial

List Comprehension

Creating a new list by applying an operation to each element of an existing list often requires a loop. List comprehension provides a concise way to do this in a single line. It's a hallmark of Python's readability and expressiveness.

Basic Syntax
`[expression for item in iterable if condition]`


# Without comprehension
squares = []
for i in range(5):
squares.append(i * i)

# With list comprehension
squares = [i * i for i in range(5)]
print(squares) # [0, 1, 4, 9, 16]

Adding a condition
You can filter elements with an `if` clause.


even_numbers = [x for x in range(10) if x % 2 == 0]
print(even_numbers) # [0, 2, 4, 6, 8]

Nested loops in comprehension
You can also have nested loops.


pairs = [(x, y) for x in [1,2] for y in [3,4]]
print(pairs) # [(1,3), (1,4), (2,3), (2,4)]

Other comprehensions
The same syntax works for sets and dictionaries.


# Set comprehension
unique_squares = {x*x for x in [1,2,2,3]} # {1,4,9}

# Dictionary comprehension
square_dict = {x: x*x for x in range(5)} # {0:0, 1:1, 2:4, 3:9, 4:16}
Two Minute Drill
  • List comprehension creates lists in a concise, readable way.
  • Syntax: `[expression for item in iterable if condition]`.
  • Can include nested loops.
  • Set and dictionary comprehensions use `{}`.
  • Often replaces `for` loops when building lists.

Need more clarification?

Drop us an email at career@quipoinfotech.com