How to input multiple values from user in one line in Python?

PythonServer Side ProgrammingProgramming

To read multiple variables in language C, we write something like −

//Read three variable in one line
scanf(“%d %d %d”, &x, &y, &z)

Currently python does not have an equivalent to scanf(). However, python provides regular expressions which are more powerful and verbose than scanf() format strings. In Python, to provide multiple values from user, we can use −

input() method: where the user can enter multiple values in one line, like −

>>> x, y, z = input(), input(), input()
>>> x
>>> y
>>> z

From above output, you can see, we are able to give values to three variables in one line.

To avoid using multiple input() methods(depends on how many values we are passing), we can use the list comprehension or map() function.

Passing multiple values using list comprehension

>>> x,y,z = [int(x) for x in input().split()]
9 12 15
>>> x
>>> y
>>> z

In above line of code, i have typecast the input values to integers. In case you don’t want that & your inputs are of mixed type, you can simply type −

>>> x,y,z = [x for x in input().split()]
40 10 "hello"

Using map function

Another way to pass multiple values from user is to use map function.

>>> x,y,z = map(int, input().split())
40 54 90
>>> x
>>> y
>>> z
Published on 02-May-2019 11:18:18