[Tutor] increment a counter inside generator

Mark Lawrence breamoreboy at yahoo.co.uk
Thu Mar 14 02:46:53 CET 2013


On 14/03/2013 01:13, David Knupp wrote:
> On Wed, 13 Mar 2013, Oscar Benjamin wrote:
>> (it's not actually a generator by the way)
>
> As Oscar points out, you're not working with a generator expression. The
> syntactical difference between a list comprehension and a generator
> expression is subtle. List comprehensions use square brackets, but
> generator expressions use parentheses.
>
>>>> foo = [n for n in xrange(10)]
>>>> foo
> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>> bar = (n for n in xrange(10))
>>>> bar
> <generator object at 0xb7eaadec>
>
> FWIW, if you're working with very large lists, but don't need to create
> the full list in memory, then a generator expression is usually
> preferred. To get the number of items a generator would return, you can
> use sum() like this:
>
>>>> gen = (n for n in xrange(some_really_huge_number))
>>>> sum(1 for n in gen) # outputs some_really_huge_number
>
> --dk.


There is little point in creating a generator from an xrange object. 
Quoting from 
http://docs.python.org/2/library/stdtypes.html#typesseq-xrange "The 
xrange type is an immutable sequence which is commonly used for looping. 
The advantage of the xrange type is that an xrange object will always 
take the same amount of memory, no matter the size of the range it 
represents. There are no consistent performance advantages."


-- 
Cheers.

Mark Lawrence



More information about the Tutor mailing list