Search code examples
python-3.xdictionarymap-function

How to input two integers in a same line?


This a simple line of code used to input 2 integers in the same line. A, B = map(int, input().split()) Please tell me how it's working using the map function?


Solution

  • In Python 3, the input() method will always return a string. Your provided code snippet tries to split that input, and the split() function defaults to splitting on a space character.

    The map() function takes a function (in this case, the int function), and applies that function to each part of the enumerable returned by the split() function.

    So, if you were to write a, b = map(int, input().split(" ")), and then the user entered 123 456, you would have a == 123 and b == 456.

    Let's take this as an example: a, b = map(int, input().split())

    This is what's going to happen:

    1. The input() function gets executed, and let's say that the user enters 123 456
    2. This gets interpreted as "123 456", and then gets passed into the split function, like this: "123 456".split() which returns a list that looks like this: ["123", "456"].
    3. Now you can sort of imagine that the code looks like this: map(int, ["123", "456"]), which might be a bit easier to reason about.
    4. What's going to happen now is that the map function will take its first argument (the int function), and apply that to each element of the ["123", 456"] list (that is, "123" and "456").
    5. The map() function returns an enumerable, which you in this case can think of as looking like the result of [int("123"), int("456")], which results in [123, 456]
    6. The unpacking of the assignment happens. You can think of that like this: a, b = [123, 456]