PYTHON
Mastering Advanced List Comprehensions
Unleash the power of Python list comprehensions with nested loops and conditional filtering to create complex lists concisely and efficiently, enhancing code readability.
# Example 1: Nested loops to flatten a list of lists
matrix = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]
flattened_list = [num for row in matrix for num in row]
print(f"Flattened list: {flattened_list}")
# Example 2: Nested loops with a conditional filter
# Get all combinations of (x, y) where x is even and y is odd from two ranges
evens_and_odds = [(x, y) for x in range(1, 5) if x % 2 == 0 for y in range(1, 5) if y % 2 != 0]
print(f"Even-Odd combinations: {evens_and_odds}")
# Example 3: Conditional expression (if-else) within a comprehension
numbers = [1, 2, 3, 4, 5, 6]
transformed_numbers = [f"{num} (even)" if num % 2 == 0 else f"{num} (odd)" for num in numbers]
print(f"Transformed numbers: {transformed_numbers}")
# Example 4: Dictionary comprehension
squares_dict = {num: num*num for num in range(1, 6) if num % 2 != 0}
print(f"Squares of odd numbers (dict): {squares_dict}")
How it works: List comprehensions offer a concise way to create lists. This snippet showcases advanced usage, including nested loops for flattening structures or generating combinations, and conditional filtering to include only specific elements. It also demonstrates how to use conditional expressions (ternary operators) within comprehensions for mapping values, and briefly touches on dictionary comprehensions for creating dictionaries in a similar concise manner.