Reputation: 55
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
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
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