Skip to content

script_2.py - List Comprehensions

Code

See script_2.py for full code.

Explanation

Line 10: numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] - List literal containing integers - numbers is list type

Line 13: squares = [x**2 for x in numbers] - List comprehension (creates new list in one line) - Syntax: [expression for variable in iterable] - x is loop variable - x**2 is expression applied to each element - ** is exponentiation operator - Returns new list: [1, 4, 9, 16, 25...] - Original list unchanged

Line 16: evens = [x for x in numbers if x % 2 == 0] - List comprehension with filter condition - if clause filters elements - Only elements where condition is True are included - % modulo operator checks remainder - Returns [2, 4, 6, 8, 10]

Line 20: odd_squares = [x**2 for x in numbers if x % 2 != 0] - Combines transformation and filtering - First filters (if x % 2 != 0), then transforms (x**2) - Returns squares of odd numbers only

Line 24: labels = ["Even" if x % 2 == 0 else "Odd" for x in numbers] - Conditional expression (ternary operator) in comprehension - Syntax: value_if_true if condition else value_if_false - Different from filter - includes all elements, chooses which value

Line 28-32: Dictionary list with .items() - users is list of dictionaries - Each dict has keys: "name", "email", "active"

Line 34: active_emails = [u["email"] for u in users if u["active"]] - u is loop variable (each dict) - u["email"] accesses dict value by key (string type) - u["active"] is boolean, used directly as condition - Filters to active users, extracts emails