0

When I apply min() on map(), I get the below result for this particular code:

a = map(int, input().split())

print(min(a))

for i in a:
    print(i)

For the input: 5 7 10 5 15

I get the result:

5

which is the minimum, but it doesn't execute the for loop.

But if I write:

a = map(int, input().split())

for i in a:
    print(i)

Then for the same input, it executes the for loop, and I get the result:

5
7
10
5
15

Why using the min() function before the for loop, is stopping the for loop from executing?

  • 1
    you can read here about generators and yield, a very good explanation https://stackoverflow.com/questions/231767/what-does-the-yield-keyword-do – mackostya May 19 '22 at 06:42
  • @mackostya probably should note, `map` objects are *iterators* not *generators* (although all generators are iterators) – juanpa.arrivillaga May 19 '22 at 06:50

4 Answers4

3

In Python 2, map() returned a list and in that environment the behaviour that you were expecting would have occurred.

However, in Python 3, map() returns a map object which is an iterator.

When you pass an iterator to a function such as min() it will be consumed - i.e. any subsequent attempts to acquire data from it will fail (not with any error but as if the iterator has been naturally exhausted).

To get the desired behaviour in the OP's code just do this:

a = list(map(int, input().split()))
DarkKnight
  • 19,739
  • 3
  • 6
  • 22
2
a = map(int, input().split())

this command returns an iterator object. Furthermore, to work on any iterator internally, next is used by many functions internally. And once there is no next output or no next object, then it exits (see __next__ implementation for more).

In case 1. the min function has used this property and traversed through this iterator and returned the minimum value, and in that next point to none, so for loop is not working there.

While in case 2. next object still points out to the first element of the map object, and thus to run iterations on this object is possible, that's why for loop work there.

sahasrara62
  • 10,069
  • 3
  • 29
  • 44
1

when you use map function in python, it returns a generator.

then when you call it with min function, it iterates over that generator and makes the generator internally point to the end of the iterable object.

then you try to reiterate on that generator, but it's already lost its initial "index" and points to the end of the iterable object

gil
  • 2,388
  • 1
  • 21
  • 29
1

What you passed into min() is the result of a map(), which is a generator. Its values are consumed by the min() function before the for loop gets the chance to consume them.

If you consume the generator and put its values into a list again, you can iterate as many times as you want.

a = list(map(int, input().split()))

print(min(a))

for i in a:
    print(i)
ljmc
  • 4,830
  • 2
  • 7
  • 26