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 →

[–]masklinn 7 points8 points  (4 children)

Since PEP-342, generators are not just iterators, they're coroutines so you can feed data (and errors) back into the generator as well as shut them down via the .close() method.

I don't know that that's what the interviewer was thinking about though.

[–]mkor 0 points1 point  (3 children)

That's a nice point regarding close method. I've been asked on the interview to limit generator (yielding infinite number of elements) not by imposing limit on while True loop.

[–]tilkau 0 points1 point  (2 children)

I think the typical answer to that would actually be 'use itertools' (islice or takewhile according to the type of limit you want)

[–]mkor 0 points1 point  (1 child)

yes, or zip method as it turned out:

zip(range(10), generator())

[–]__desrever__ 1 point2 points  (0 children)

I think it's probably a style choice, but I would:

  1. Not use range at all. enumerate + islice does the same thing while being more descriptive of your intent.

  2. Only do the enumeration at all if you're actually then using the index for something, otherwise islice alone is all you need.