if __name__ == '__main__':
n = int(input())
arr = map(int, input().split())

In the above code, map function taking two parameters, I got the understanding of the second parameter what it does but I am not getting 'int' parameter.

2 Answers

2
Zev On Best Solutions

Let's say I type 5 and then enter at the first prompt:

n = int(input())

Would take the input "5" and make it into the integer 5. So we are going from a string to an int

Then we will get another input prompt because we have input() again in the next line: This time I'll type 123 324 541 123 134 and then enter.

the .split() will split this into "123", "324", "541", "123", "134" which is a list (well a map) of strings. Then we'll map int onto them to give ourselves a map of ints rather than strings. int converts the strings to integers.

When checking out code it is often helpful to try things in a REPL (read execute print, looper). In your command promt just type python or python3 if you have it installed or use replt.it. Type a = "123" + "321" then try `a = int("123") + int("321")

Wrap this with list(map(int, input().split())) to get a list rather than a map.

2
Ectras On
  • map(function, iterable) takes a function which to apply to all elements of the list that is passed as second argument.
  • int(x) is a function that returns an integer object constructed from a number or string x.

Therefore, it will just make a iterable where it applied the int() function to each string from .split(), meaning it casts every entry to int.

Example:

arr = map(int, "12 34 56".split())
print(list(arr)) # prints: [12, 34, 56]