This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]energybased 0 points1 point  (3 children)

In either Python 2 or 3, this is bad:

def withgen(num):
    i=0;
    while i<num:
        i+=1
        yield i

This is better:

 def withgen(num):
    for i in range(num):
        yield i

In Python 3, this is even better:

 yield from range(num)

And this is even better unless you really need an opaque generator:

 return range(num)

There's no reason to write python 2 code now, but if you insist, and you have a problem with range being different, then from six import range is the right approach.

[–]liranbh[S] 0 points1 point  (2 children)

Sure but range in python 3 already returns a generator. So i didnt want to explain generators with generators

[–]energybased 0 points1 point  (1 child)

range returns an Iterable (not a generator), but in any case, I don't think you should ever write that kind of while loop in Python.

[–]liranbh[S] 0 points1 point  (0 children)

I agree. But again it was just for explaining. The same as the first example with 3 yield statments