Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

list() applied to zip object twice in a row issue

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.

like image 264
Milos Mirosavljevic Avatar asked Nov 01 '19 10:11

Milos Mirosavljevic


People also ask

What does zip() function do in Python?

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.

What is zip(* in Python?

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.


1 Answers

zip returns a generator, not list. generator only runs once, so you will need to recall zip again for my_map_list_second

like image 97
ExplodingGayFish Avatar answered Oct 28 '22 16:10

ExplodingGayFish