I was wondering what would happen if I passed the generator to Python's built-in function enumerate (), so I experimented.

Mainly personal notes:

I was wondering if Python's built-in function ʻenumerate` also supports generators, so I experimented.

Question

If I pass a generator to enumerate (), will it be listed and expanded on the fly? (Including confirmation that you can hand it in the first place)

Experiment

Prepare the following generator

>>> def test(value):
...   for i in range(value):
...     print(i)
...     yield i
...

Confirmed to work as a generator

>>> for v in test(10):
...   print(v)
...
0  # test()Output from print in
0  #Output from print for statement
1
1
2
2
3
3
4
4
5
5
6
6
7
7
8
8
9
9

Try passing the prepared generator to ʻenumerate`

>>> for i, v in enumerate(test(10)):
...   print(i, v)
...
0      # test()Output from print in
0 0    #Output from print for statement
1
1 1
2
2 2
3
3 3
4
4 4
5
5 5
6
6 6
7
7 7
8
8 8
9
9 9
>>>

result

--You can pass a generator to ʻenumerate. --If you pass a generator to ʻenumerate, it will add an index to each element returned by the generator and return it.

Recommended Posts

I was wondering what would happen if I passed the generator to Python's built-in function enumerate (), so I experimented.
I tried to get the index of the list using the enumerate function
In IPython, when I tried to see the value, it was a generator, so I came up with it when I was frustrated.