Python tuple vs generator

前端 未结 2 1540
醉梦人生
醉梦人生 2021-02-07 11:08

I am having a problem understanding why one of the following line returns generator and another tuple.

How exactly and why a generator is created in the second line, wh

2条回答
  •  半阙折子戏
    2021-02-07 11:15

    You can imagine tuples as being created when you hardcode the values, while generators are created where you provide a way to create the objects.

    This works since there is no way (1,2,3,4) could be a generator. There is nothing to generate there, you just specified all the elements, not a rule to obtain them.

    In order for your generator to be a tuple, the expression (i for i in sample_list) would have to be a tuple comprehension. There is no way to have tuple comprehensions, since comprehensions require a mutable data type.

    Thus, the syntax for what should have been a tuple comprehension has been reused for generators.

提交回复
热议问题