All categories
    PythonIntermediate

    Comprehensions

    Python comprehensions: list, dictionary, set, and generator expressions for concise and readable data transformation.

    01List comprehension with filter

    main.py
    nums = [1, 2, 3, 4, 5, 6]
    evens = [n for n in nums if n % 2 == 0]
    print(evens)
    Output
    [2, 4, 6]

    02Nested comprehension

    main.py
    matrix = [[1, 2, 3], [4, 5, 6]]
    flat = [x for row in matrix for x in row]
    print(flat)
    Output
    [1, 2, 3, 4, 5, 6]

    03Dictionary comprehension

    main.py
    words = ["hi", "bye", "yes"]
    lengths = {w: len(w) for w in words}
    print(lengths)
    Output
    {'hi': 2, 'bye': 3, 'yes': 3}

    04Set comprehension

    main.py
    nums = [1, 2, 2, 3, 3, 3]
    squares = {n * n for n in nums}
    print(sorted(squares))
    Output
    [1, 4, 9]

    05Generator expression

    main.py
    total = sum(x * x for x in range(1, 6))
    print(total)
    Output
    55