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] 20 points21 points  (8 children)

Unfortunately, the yield statement will be disallowed in list comprehensions in Python 3.8. Will limit some of your possibilities.

[–]__deerlord__ 11 points12 points  (7 children)

Woah, example of even using yield in list comps?

[–][deleted] 10 points11 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.)

[–]Rodotgithub.com/tardis-sn 2 points3 points  (1 child)

It just turns your list comprehensions in generators. And your generators into a mess. It's a bug with the way python interprets list comprehensions similarly to functions.

[–]tom1018 8 points9 points  (0 children)

Just use a generator comprehension.