Register

Python for Beginners

0 of 24 notes read 0%

Reading progress is saved to your INFIRALS account. Sign in to keep this note marked as read.

Comprehensions and generator expressions

More Python9 min readLesson 1 of 7

1.1 One expression instead of a loop

A list comprehension builds a list from an iterable in a single expression: square brackets, an expression for each item, then a for clause, optionally followed by an if filter. It is not faster than a well-written loop, but it says what is happening without an index variable.

Swap the square brackets for parentheses and you get a generator expression. It produces values on demand instead of building the whole list, which matters when the data is large or the first few values are all you need.

python
squares = [n * n for n in range(1, 6)]
print(squares)

evens = [n for n in squares if n % 2 == 0]
print(evens)

total = sum(n * n for n in range(1, 6))
print(total)

Output

[1, 4, 9, 16, 25]
[4, 16]
55

Use comprehensions for a single transformation or filter. If the expression needs nested loops and two conditions, a normal loop with a name is easier to read a month later.

Interview questions

2 questions from this note. Open one to see the answer; no account needed.

  • 01When should I use a generator expression?

    When you only need to iterate once, or when building the full list would use unnecessary memory.

  • 02Do comprehensions change the original list?

    No. They build a new list; the source iterable is left as it was.

Quiz

Check: comprehensions and generators

Four questions on list comprehensions, generator expressions and when a plain loop is clearer.

4 questions

Question 1 of 4

0/4 answered

A generator expression is written with:

Answer all you can, then submit.