0

I encountered a weird phenomena while playing around with python. The following two different codes give different outputs whereas, in my opinion, they (the codes) should be equivalent.

Snippet 1:

store1 = [10.00, 11.00, 12.34, 2.34]
store2 = [9.00, 11.10, 12.34, 2.01]
cheapest = list(map(min, store1, store2))
print(list(cheapest))
list(cheapest)

Snippet 2:

store1 = [10.00, 11.00, 12.34, 2.34]
store2 = [9.00, 11.10, 12.34, 2.01]
cheapest = (map(min, store1, store2))
print(list(cheapest))
list(cheapest)  #shows empty list

Looking at the outputs from these two snippets (the only difference in declaration of cheapest from line 3), I conclude that using list(x), where x is a map, at any other point other than declaration of the variable, actually deletes/clears the contents of the map.

I can't figure out why this is happening (or if my inference is even correct), any help would be appreciated :)

Sids2k
  • 11
  • 5
  • Map returns an iterator in Python 3. On the second “read” it has already been used up, and returns 0 elements making for an empty list - see https://portingguide.readthedocs.io/en/latest/iterators.html, which explains the behavior (and difference from Python 2) – user2864740 May 02 '20 at 03:05
  • @user2864740 what do you mean by 'used up'? I have a stronger background in c++, and in that language an iterator points to the same location and the data being pointed to remains till overwritten. So an equivalent code in c++ will have same output for both the snippets. – Sids2k May 02 '20 at 03:07
  • https://stackoverflow.com/q/36486950/2864740 – user2864740 May 02 '20 at 03:07
  • in C++ terms, using the result of map a second time is akin to using an iterator already at my_map.end(). Python iterators effectively maintain their own position. – user2864740 May 02 '20 at 03:09
  • @user2864740 ah that makes more sense. So the iterator remains at map.end() or can we move it back to the front? P.S. reading up on the resources you tagged – Sids2k May 02 '20 at 03:10
  • No, so I guess that wasn’t the best example :) Some options include 1) materializing in list; 2) using a wrapping object like itertools “tee”; or 3) using a function/closure that re-evaluates to a new iterator from the same data. – user2864740 May 02 '20 at 03:13
  • You're giving me ways to work around this? Thats alright, there will be scores of ways to work around it, I'm just trying to understand how python works and what all I _can_ do in the language Thanks for all your help and the sources you tagged. I'm getting my doubts cleared :) – Sids2k May 02 '20 at 03:20

0 Answers0