[Tutor] increment a counter inside generator

Oscar Benjamin oscar.j.benjamin at gmail.com
Wed Mar 13 22:23:43 CET 2013


On 13 March 2013 21:12, Abhishek Pratap <abhishek.vit at gmail.com> wrote:
> On Wed, Mar 13, 2013 at 2:02 PM, Oscar Benjamin
> <oscar.j.benjamin at gmail.com> wrote:
>> On 13 March 2013 19:50, Abhishek Pratap <abhishek.vit at gmail.com> wrote:
>>> Hey Guys
>>>
>>> I might be missing something obvious here.
>>>
>>>
>>> import numpy as np
>>>
>>> count = 0
>>> [ count += 1 for num in np.random.random_integers(1,100,20) if num > 20]
>>>
>>>  File "<ipython-input-45-0ba0e51b7644>", line 2
>>>     [ count += 1 for num in np.random.random_integers(1,100,20) if num > 20]
>>>              ^
>>> SyntaxError: invalid syntax
[SNIP]
>
> I just used a very contrived example to ask if we can increment a
> counter inside a generator. The real case is more specific and
> dependent on other code and not necessarily useful for the question.

Ok, so can you be more specific about the effect that you are trying
to achieve? Do you want to know the length of the list (equivalent to
Dave's suggestion)?

len([num for num in np.random.random_integers(1,100,20) if num > 20])

Or is it that you want to use count in the expression in the list
comprehension (it's not actually a generator by the way)? You can
achieve this with enumerate and an inner generator:

data = np.random.random_integers(1, 100, 20)
[x + count for count, x in enumerate(n for n in data if n > 2)]

If your case is much more complicated than this then personally I
would write a generator function rather than use a comprehension. Then
you can increment variables or anything else just like normal.


Oscar


More information about the Tutor mailing list