← Back to Blog
    TutorialFebruary 01, 20246 min read

    Master Python List Comprehension: From Basics to Advanced

    Learn Python list comprehension with practical examples. Transform your code from verbose loops to elegant one-liners.

    Master Python List Comprehension

    What is List Comprehension?

    List comprehension is a concise way to create lists by filtering and transforming elements.

    Syntax:

    ```python

    [expression for item in iterable if condition]

    ```

    Basic Examples

    Square Numbers

    ```python

    squares = [x**2 for x in range(5)]

    [0, 1, 4, 9, 16]

    ```

    Filter Even Numbers

    ```python

    evens = [x for x in range(10) if x % 2 == 0]

    [0, 2, 4, 6, 8]

    ```

    Convert to Uppercase

    ```python

    words = ["python", "java", "rust"]

    upper = [w.upper() for w in words]

    [''PYTHON'', ''JAVA'', ''RUST'']

    ```

    Nested List Comprehension

    Flatten a 2D List

    ```python

    matrix = [[1, 2], [3, 4], [5, 6]]

    flat = [x for row in matrix for x in row]

    [1, 2, 3, 4, 5, 6]

    ```

    Create Cartesian Product

    ```python

    pairs = [(x, y) for x in [1, 2] for y in [''a'', ''b'']]

    [(1, ''a''), (1, ''b''), (2, ''a''), (2, ''b'')]

    ```

    Performance Benefits

    List comprehension is faster than loops:

    ```python

    Slow (loop)

    result = []

    for x in range(1000):

    if x % 2 == 0:

    result.append(x * 2)

    Fast (list comprehension)

    result = [x * 2 for x in range(1000) if x % 2 == 0]

    ```

    Dictionary & Set Comprehension

    Dict Comprehension

    ```python

    squares_dict = {x: x**2 for x in range(5)}

    {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

    ```

    Set Comprehension

    ```python

    unique = {x % 3 for x in range(10)}

    {0, 1, 2}

    ```

    Best Practices

    1. Keep it simple: One condition max, consider readability
    2. Use meaningful names: `[s.strip() for s in lines]` not `[x for x in y]`
    3. For complex logic: Use regular loops, don''t force comprehension

    By PythonExecutor Team

    Related Articles