Python dict function for enumeration object

If I have an enumeration object x, why does the following:

dict(x) 

delete all elements in an enumeration sequence?

+4
source share
1 answer

enumerate creates an iterator . An iterator is a python object that knows only about the current element of the sequence and how to get the next, but there is no way to restart it. Therefore, once you used an iterator in a loop, it cannot give you more elements and seems empty.

If you want to create a real sequence from an iterator, you can call list on it.

 stuff = range(5,0,-1) it = enumerate(stuff) print dict(it), dict(it) # first consumes all items, so there are none left for the 2nd call seq = list(enumerate(stuff)) # creates a list of all the items print dict(seq), dict(seq) # you can use it as often as you want 
+18
source

Source: https://habr.com/ru/post/1308026/


All Articles