Issue
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?
Solution
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()))
Answered By - Stuart
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.