Search code examples
pythonpython-3.xdictionaryintmap-function

What does `int` parameter in `map` function of Python 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.


Solution

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