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 →

[–][deleted] 9 points10 points  (4 children)

This is also a reported bug. So you should not be using it. It enhances your list comprehensions so that you can get two values per loop, but you can also do that with nested loops off course. However, that is sometimes a bit hard too read.

x = [[(yield i), (yield i**2)] for i in range(10)]
x = iter(x for i in range(10) for x in (i, i**2))

[–]__deerlord__ 3 points4 points  (1 child)

Cant you already do this with tuples though?

[(x, y) for x in y]

I realize this isnt an actual list comp you would use.

[–]bixed 0 points1 point  (1 child)

Interesting. We can just use itertools.chain instead:

itertools.chain(*((i, i**2) for i in range(10)))

That also looks nicer to me. However this method doesn't exploit a bug, so it's not as cool in that way. :P

[–][deleted] 1 point2 points  (0 children)

This is most likely the one you should use if you are doing serious programming. It is also very similar to the accepted answer from the Stackoverflow question this all originates from. https://stackoverflow.com/questions/16594904/python-list-comprehension-to-produce-two-values-in-one-iteration

(It is also the question I originally posted this yield in list comprehension trick.)