I have built a zip object and by accident I noticed that if I apply list() to this object twice, second time it will yield []. My code is shown below:
coordinate = ['x', 'y', 'z']
values = [5, 7, 9]
my_map = zip(coordinate, values)
my_map_list_first = list(my_map)
my_map_list_second = list(my_map)
print(my_map_list_first)
print(my_map_list_second)
Output of the code is:
[('x', 5), ('y', 7), ('z', 9)]
[]
I am new to Python so my terminology may not be 100% accurate. I have tried finding the explanation online, but problem here is what is the actual question. (Good question makes half he answer). Since I am still learning Python, I probably don't know what to ask.
I also tried using that Python simulator which I saw in another topic: http://www.pythontutor.com/visualize.html#mode=display But I only saw what I knew - that my_map_list_second is [], not what exactly is going on under the hood. Can someone explain what happened here? And also point me in a right direction regarding "similar" issues, although I am sure those will become clear in time, as I progress with Python.
This is also my first port on these forums. Thanks in advance.
You are looking for awnser about generator.
In fact, zip
will create a generator
, that is not process until you iterate
trought it, using list
in your exemple. An other important property is that generator
can only be iterate once
.
The last property explain why you get en empty list the second time.