Comprehensions

Comprehensions are one-liners or compact syntax to generate a new collection (like a list, set, or dictionary) from an existing one. They are often faster and more readable than traditional loops.

List Comprehensions

List comprehensions are used to create a list in a single line.

Syntax:

[expression for item in iterable if condition]
  • expression: The value you want in the new list.
  • iterable: The existing sequence to iterate over.
  • condition (optional): A filter to include only specific items.

Example:

Create a list of squares for numbers 1 to 5.

Python
Copy
squares = [x**2 for x in range(1, 6)]
print(squares)  # Output: [1, 4, 9, 16, 25]

Filter only even numbers from 1 to 10:

Python
Copy
evens = [x for x in range(1, 11) if x % 2 == 0]
print(evens)  # Output: [2, 4, 6, 8, 10]

Dictionary Comprehensions

Dictionary comprehensions are used to create dictionaries in a single line.

Syntax:

{key_expression: value_expression for item in iterable if condition}

Example:

Create a dictionary mapping numbers to their squares:

Python
Copy
squares_dict = {x: x**2 for x in range(1, 6)}
print(squares_dict)  # Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

Filter and include only odd numbers:

Python
Copy
odds_dict = {x: x**2 for x in range(1, 11) if x % 2 != 0}
print(odds_dict)  # Output: {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}

Set Comprehensions

Set comprehensions are used to create a set in one line.

Syntax:

{expression for item in iterable if condition}

Example:

Create a set of unique squares:

Python
Copy
unique_squares = {x**2 for x in [1, 2, 2, 3, 4]}
print(unique_squares)  # Output: {1, 4, 9, 16}

Filter and include only even numbers:

Python
Copy
even_set = {x for x in range(1, 11) if x % 2 == 0}
print(even_set)  # Output: {2, 4, 6, 8, 10}

Nested Comprehensions

You can nest comprehensions to handle more complex problems.

Example:

Create a matrix (list of lists):

Python
Copy
matrix = [[j for j in range(1, 4)] for i in range(1, 4)]
print(matrix)
# Output: [[1, 2, 3], [1, 2, 3], [1, 2, 3]]

Flatten a nested list:

Python
Copy
nested = [[1, 2], [3, 4], [5, 6]]
flattened = [num for sublist in nested for num in sublist]
print(flattened)  # Output: [1, 2, 3, 4, 5, 6]

Generator Expressions

Generator expressions are similar to list comprehensions but create an iterator instead of a list. They are memory-efficient for large datasets.

Syntax:

(expression for item in iterable if condition)

Example:

Generate squares for numbers 1 to 5:

Python
Copy
squares_gen = (x**2 for x in range(1, 6))
print(list(squares_gen))  # Output: [1, 4, 9, 16, 25]

Key Benefits of Comprehensions

  • Concise: Reduce the need for multiple lines of code.
  • Readable: Easier to understand when used properly.
  • Efficient: Faster than traditional loops in most cases.