3
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.

Prathamesh More
  • 1,470
  • 2
  • 18
  • 32

2 Answers2

4
  • map(function, iterable) Return an iterator that applies function to every item of iterable, yielding the results.
  • int(x) Return an integer object constructed from a number or string x.

Therefore, it will return an iterable where it applied the int() function to each substring from .split(), meaning it casts every substring to int.

Example:

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

# This is equivalent:
arr = [int("12"), int("34"), int("56")]

Other example with custom function instead of int():

def increment(x):
    return x + 1

arr = map(increment, [1, 2, 3, 4, 5])
arr = list(arr)
print(arr) # prints: [2, 3, 4, 5, 6]
Ectras
  • 166
  • 4
3

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.

Zev
  • 3,423
  • 1
  • 20
  • 41