0

I have used this code to add up all numbers up to 1000, which are multiples of 3 or 5. Is this technically a list comprehension approach?

print(sum(i for i in range(1,1000) if i % 3 == 0 or i % 5== 0))
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Tuning
  • 53
  • 1
  • 5

1 Answers1

8

Technically, it's a generator expression. A list comprehension always has square brackets and results in a list being created. By contrast, a generator expression can be evaluated element by element without constructing an entire list in memory.

Here's the same code with a list comprehension:

print(sum([i for i in range(1,1000) if i % 3 == 0 or i % 5== 0]))

This would be a waste of memory as there's no reason to keep all the numbers in memory when computing their sum.

See also:

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • Thanks, this is very helpful and clear. So a generator expression is better since it doesn't store the numbers in memory? – Tuning Jan 04 '21 at 19:41