2

This is the code with list function commented out:

from collections import Counter

a = input().split() 
b = map(int, a) 
##c = list(b) 
d = Counter(b)

print(d)

Input: 1 2 3
Output: Counter({1: 1, 2: 1, 3: 1})

However, when i remove the hashtags, assign c to list(b) and rerun the code this occurs:

Input: 1 2 3

Output: Counter()

My question is, Why is it that the counter output values differ if b is not being assigned any new type? From what i know, b would not be affected by this operation? Please forgive me if its a dumb question, I am still quite new to coding. Thanks!

Trushit Shekhda
  • 563
  • 7
  • 18
kiblykat
  • 121
  • 5
  • 5
    `map()` returns an iterator. You can only loop through it once. When you use `list(b)` it exhausts the iterator. See also: [related post](https://stackoverflow.com/questions/36486950/python-calling-list-on-a-map-object-twice) – Mark May 11 '20 at 03:52

1 Answers1

0

Python map() function is used to apply a function on all the elements of specified iterable and return map object. Python map object is an iterator, so we can iterate over its elements.

b = map(int, a) 

This only maps 'int' function to each element in a. (Not executes).

when you call the iterator it executes and returns the value and clears.

for example

a = list(range(5))
for i in a:
 print(i)
 break

Outputs

0

for i in a:
 print(i)
 break

Outputs

1 #now it returns next element

And goes on. This is a type of on-demand execution

Wickkiey
  • 4,446
  • 2
  • 39
  • 46