Skip to content Skip to sidebar Skip to footer

How Does Python Max(list) Function Work?

I have the following code that doesn't work the way it should. n = int(input()) arr = map(int, input().split()) num=max(arr) x=list(set(arr)) print (x) This returns and empty lis

Solution 1:

n = int(input())  # unused - why put it in your example?
arr = map(int, input().split())  # returns an iterator

num=max(arr)      # consumes the iterator
x=list(set(arr))  # nothing in the iterator anymore
print (x)         # prints nothing

Fix:

n = int(input())  # unused - why put it in your example?
arr = set(map(int, input().split()))  # returns an set named arr

num=max(arr)      # get num as max from set 
print (arr)       # prints the set named arr

In python 2 map behaved differently - for 3 its an iterator. Once consumed, iterators are "empty". You can see for yourself if you print(type(arr)) for the result of your map operation.

Read: map()


Solution 2:

I'm not sure why you need to use map in this case. Another thing is that you will throw errors on your input if the user does not provide a single int since you are trying to convert it. You can take your input, like a string of '1 4 6 23 5', convert it to a list of ints, and then find the max.

n = '1 4 6 23 5'
arr = [int(x) for x in n.split()]
max(arr)

Post a Comment for "How Does Python Max(list) Function Work?"