Grigoriy Volkov
Grigoriy Volkov

Reputation: 55

Does list comprehension always create a list in Python?

For example, if I have something like:

sum([i for i in range(very_big_number)])

Will this construction be optimized for reducing memory cost?

Upvotes: 2

Views: 259

Answers (2)

declension
declension

Reputation: 4185

Yes - so what you probably want is a generator expression.

sum(i for i in range(very_big_number))

As others have noted, you'll need xrange in Python 2.

As an additional benefit, you omit any additional syntax tokens, so it looks slightly neater :)

Upvotes: 1

John Zwinck
John Zwinck

Reputation: 249133

This will indeed always create a large list, assuming you are using a typical implementation of Python such as the standard CPython:

sum([i for i in range(very_big_number)])

These will avoid creating the list (in Python 2 you'll need xrange() instead):

sum(i for i in range(very_big_number))
sum(range(very_big_number))

Upvotes: 1

Related Questions