#!/usr/bin/env python3
"""
Advanced Python List Comprehension Examples

This module demonstrates more complex list comprehension patterns.
"""

# Example 1: Flatten a nested list
nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened = [item for sublist in nested_list for item in sublist]

# Example 2: Cartesian product
colors = ['red', 'green', 'blue']
sizes = ['S', 'M', 'L']
cartesian_product = [(color, size) for color in colors for size in sizes]

# Example 3: Matrix transposition
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
transposed = [[row[i] for row in matrix] for i in range(len(matrix[0]))]

# Example 4: List comprehension with zip
names = ['Alice', 'Bob', 'Charlie']
ages = [25, 30, 35]
people = [{'name': name, 'age': age} for name, age in zip(names, ages)]

# Example 5: List comprehension with file operations
# Read lines from a file (assuming file exists)
# lines = [line.strip() for line in open('example.txt') if line.strip()]

# Example 6: List comprehension with exception handling
numbers = ['1', '2', 'three', '4', 'five']
valid_numbers = [int(x) for x in numbers if x.isdigit()]

# Example 7: List comprehension with method calls
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    def is_adult(self):
        return self.age >= 18

people_objects = [Person('Alice', 25), Person('Bob', 17), Person('Charlie', 30)]
adults = [person.name for person in people_objects if person.is_adult()]

# Example 8: List comprehension with lambda
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers))

# Example 9: List comprehension with multiple inputs
numbers1 = [1, 2, 3]
numbers2 = [4, 5, 6]
sums = [x + y for x, y in zip(numbers1, numbers2)]

# Example 10: List comprehension with generator expression
# Process large data efficiently
def generate_large_data(n):
    for i in range(n):
        yield i

large_data = list(generate_large_data(1000))
even_large_numbers = [x for x in large_data if x % 2 == 0]

if __name__ == '__main__':
    print('Flattened List:', flattened)
    print('Cartesian Product:', cartesian_product)
    print('Transposed Matrix:', transposed)
    print('People:', people)
    print('Valid Numbers:', valid_numbers)
    print('Adults:', adults)
    print('Squared Numbers:', squared)
    print('Sums:', sums)
    print('Even Large Numbers (first 10):', even_large_numbers[:10])