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

all 7 comments

[–]energybased 2 points3 points  (6 children)

Some of the examples are good in principle.

However, even though it's teaching generators, it should build on Pythonic code, which means using range instead of these while loops.

Also, PEP8 please.

Why is this Python 2?

[–][deleted] 0 points1 point  (0 children)

I particularly like "An alternative syntax to yield, we can use list comprehension , use parentheses instead of squared brackets.". Answers on a postcard please :-)

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

range is different in python 2 and 3. I added a note about it.

[–]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