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?
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:
input()
function gets executed, and let's say that the user enters 123 456
"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"]
.map(int, ["123", "456"])
, which might be a bit easier to reason about.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"
).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]
a, b = [123, 456]