Reputation: 115
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 list "[]". However, if I remove the num=max[arr] line from the code, it works as expected.
n = int(input())
arr = map(int, input().split())
x=list(set(arr))
print (x)
And the output is a list of all elements without duplicates. I wanted to use the max() value somewhere else in the program, but it seems to break the list formation. Why does this happen? Is there a basic property of the max function that I'm missing?
Edit: Why are people downvoting this without any answers? I'm fairly new to python and any help would be appreciated. If I made a silly mistake please point that out.
Upvotes: 0
Views: 187
Reputation: 8324
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)
Upvotes: 0
Reputation: 51653
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()
Upvotes: 3