Skip to the content

Generator expressions

Python · Unit 15: Comprehensions and generators

Swap the square brackets of a comprehension for parentheses and you have a generator expression: the values come out one by one, without building the list.

Inside a call like sum() you don't even need the extra parentheses.

nums = [1, 2, 3, 4]
print(sum(n * n for n in nums))

Prints

30

The rest of the explanation is in the lesson, which is part of the full plan.

Exercises in this lesson

You do them in the app, which checks them on the spot and explains why.

  1. 1. Predict the output

    These are the prices of three things. What does it print?

  2. 2. Complete the code

    Fill in the blank to find out whether somebody in the group is already of age.

  3. 3. Predict the output

    What does this code print?

  4. 4. Multiple choice

    You have g = (n * 2 for n in nums). What do you see if you run print(g)?

  5. 5. Find the bug

    It should print the total of the doubled prices and the largest of them. Which line has the error?

  6. 6. Multiple choice

    You have a million prices in pr and you only want the total with tax. Which one is better?

  7. 7. Write the code

    Write more_than(ns, t), which returns how many numbers in ns are greater than t. Use sum with a generator expression.

  8. 8. Predict the output

    This dictionary holds the price of each product. What does it print?

  9. 9. Put the lines in order

    Put the lines in order to print how many marks are over 7 and how many marks there are in total.

  10. 10. Predict the output

    How many vowels does the text have?

Do this lesson

It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.

See all lessons →