0

I try to use list-comprehensions see link here: https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions

but it create generator instead of return list

And when I try to convert it to list- it work only once, and then the list disappear

 values=[3,"fasdf",99]

 vv=(str(x) for x in values)

 vv

<generator object <genexpr> at 0x047D2F08>
 list(vv)

['3', 'fasdf', '99']

 list(vv)

[]

values


[3, 'fasdf', 99]
yonilobo
  • 137
  • 2
  • 7
  • 1
    Yes, generators can only be used once. Make a list to store the values so they can be used multiple times – mousetail Apr 27 '21 at 11:54
  • Following up on @mousetail, the comprehension in the `()` will return a `generator`. If you just want the list in the end and don't need a generator, use square brackets: `[str(x) for x in values]`. I would advise you to read more about generators [here](https://stackoverflow.com/questions/1756096/understanding-generators-in-python)! – gmdev Apr 27 '21 at 11:56
  • Thanks on your advice. I didn't know that () is a generator. – yonilobo Apr 28 '21 at 13:55

1 Answers1

4

(str(x) for x in values) is not a list comprehension, it's a generator expression.

[str(x) for x in values], on the other hand, is a list comprehension.

The first expression makes a one-time generator that gets exhausted the moment you iterate through it. The second expression places the result of that iteration into a list, so you can access the elements again.

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264