List comprehensions

Computer Science · Python

Question 1 of 10

0

    What does this Python code print? nums = [x * 5 for x in range(6)] print(nums[-1])

    Decimals (0.75 or 0,75), fractions (3/4) and mixed numbers (1 1/2) are accepted. Do not use thousands separators.

    How to type your answer
    • Fractions: 3/4. Mixed numbers: 1 1/2.
    • Decimals with a point or a comma: 0.75 or 0,75.
    • Negative numbers start with a minus: -3/4.
    • Percentages need the % sign: 75%.

    Stuck? Read the explanation

    Unlocks at a streak of 5 correct answers in a row.

    Print a free worksheet (PDF)

    Embed this practice on your site or class page

    Paste this HTML into your page. Students practise right there; it is free and needs no account.

    List comprehensions explained

    A list comprehension builds a new list from an existing iterable in a single expression, with an optional condition to filter items. It is a concise alternative to a loop that appends to a list.

    The general form is [expression for item in iterable if condition]. Python evaluates the expression for each item that passes the condition and collects the results in a new list. The if part is optional.

    For example, [x * x for x in range(1, 4)] gives [1, 4, 9]. A loop version would create an empty list, loop over the range, compute x * x and call append each time. The comprehension expresses the same steps more compactly.

    Comprehensions can be nested, but deeply nested ones become hard to read. A reasonable rule is to use a comprehension when it fits on one line and a normal loop otherwise.

    The same pattern works with curly braces to build sets and dictionaries, giving forms such as a set comprehension or a dictionary comprehension.

    Worked example

    squares_of_odds = [x * x for x in range(1, 6) if x % 2 == 1]
    print(squares_of_odds)
    
    1. range(1, 6) gives 1, 2, 3, 4 and 5.
    2. The condition keeps only the odd numbers, 1, 3 and 5, because each leaves a remainder of 1 when divided by 2.
    3. Their squares are 1, 9 and 25, so the list is [1, 9, 25].

    Check: 1+9+25=351 + 9 + 25 = 35, which is the sum of the squares of the odd numbers from 1 to 5.

    What you will practise

    New numbers every time you practise. Levels: Easy, Medium, Hard. Each answer is followed by a worked explanation.

    Example questions

    • Easy

      What does this Python code print? nums = [x * 4 for x in range(8)] print(nums[-1])

    • Medium

      What does this Python code print? vals = [x for x in range(4, 16) if x % 3 == 1] print(sum(vals))

    • Hard

      What does this Python code print? pairs = [x * y for x in range(5) for y in range(5) if x != y] print(pairs[-1])