Home > database >  Applying min() on map() in Python
Applying min() on map() in Python

Time:05-19

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 input: 5 7 10 5 15

I get the result as:

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 'min()' before the 'for' loop is stopping 'for' loop to execute?

CodePudding user response:

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()))

CodePudding user response:

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

this command return a iterator object. and to work on any iterator internally next is used by many function internally. and once there is no next output or no next object then it exit (see __next__ implementation for more) .

now in case 1. min function has use this property and traverse through this iterator and return 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 first element of map object and thus to run iteratation on this object is possible, that's why for loop work there

CodePudding user response:

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

CodePudding user response:

Wahat you passed into min, is the result of a map, which is a generator, it's values are cosumed by the min function before the for loop get's the chance to consume them.

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

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

print(min(a))

for i in a:
    print(i)
  • Related