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.
Python zip() Function The zip() function returns a zip object, which is an iterator of tuples where the first item in each passed iterator is paired together, and then the second item in each passed iterator are paired together etc.
Python's zip() function is defined as zip(*iterables) . The function takes in iterables as arguments and returns an iterator. This iterator generates a series of tuples containing elements from each iterable. zip() can accept any type of iterable, such as files, lists, tuples, dictionaries, sets, and so on.
zip
returns a generator
, not list
. generator
only runs once, so you will need to recall zip
again for my_map_list_second
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With