List, Dict, and Set Comprehensions

Comprehensions in Python provide a concise way to create lists, dictionaries, and sets using a single readable expression. They make code more elegant and efficient, especially when working with iterables.

List Comprehensions

Example 1: Basic list comprehension

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

Example 2: Using an if condition

evens = [x for x in range(20) if x % 2 == 0]
print(evens)

Example 3: Nested loops in comprehension

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

Example 4: Conditional expression inside comprehension

results = [x if x > 5 else 0 for x in range(10)]
print(results)

Example 5: Flattening a list of lists

matrix = [[1, 2], [3, 4], [5, 6]]
flat = [num for row in matrix for num in row]
print(flat)

Dictionary Comprehensions

Example 6: Creating a dict from a list

nums = [1, 2, 3]
squares = {n: n**2 for n in nums}
print(squares)

Example 7: Filtering items in dict comprehension

nums = range(10)
even_squares = {n: n**2 for n in nums if n % 2 == 0}
print(even_squares)

Example 8: Swapping keys and values

d = {'a': 1, 'b': 2}
swapped = {v: k for k, v in d.items()}
print(swapped)

Set Comprehensions

Example 9: Basic set comprehension

unique_squares = {x**2 for x in [-2, -1, 0, 1, 2]}
print(unique_squares)

Example 10: Using conditionals in set comprehension

filtered = {x for x in range(10) if x % 3 != 0}
print(filtered)

Comprehensions are powerful tools for writing clear, concise, and performant Python code when working with iterables.