techmore.in

Python - Comprehensions

Comprehensions in Python are a concise way to create lists, sets, and dictionaries. They are often more readable and faster than using traditional loops.

1. List Comprehensions

List comprehensions provide a concise way to create lists from iterable objects.

python
# Create a list of squares from 0 to 9
squares = [x ** 2 for x in range(10)]
print(squares)

2. Set Comprehensions

Set comprehensions are similar to list comprehensions but return a set.

python
# Create a set of unique squares
unique_squares = {x ** 2 for x in range(10)}
print(unique_squares)

3. Dictionary Comprehensions

Dictionary comprehensions allow creating dictionaries from iterables in a single line.

python
# Create a dictionary of numbers and their squares
square_dict = {x: x ** 2 for x in range(10)}
print(square_dict)

Pros of Comprehensions

  • Shorter and more readable code
  • Faster execution than equivalent for-loops
  • Can be used inline

Cons of Comprehensions

  • Can be less readable if overused or complex
  • Not always suitable for complex logic