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

For instance, in C we can do something like this:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Reads two values in one line
scanf("%d %d", &x, &y) 

chevron_right


One solution is to use raw_input() two times.

filter_none

edit
close

play_arrow

link
brightness_4
code

x, y = raw_input(),  raw_input()

chevron_right


Another solution is to use split()



filter_none

edit
close

play_arrow

link
brightness_4
code

x, y = raw_input().split()

chevron_right


Note that we don’t have to explicitly specify split(‘ ‘) because split() uses any whitespace characters as delimiter as default.

One thing to note in above Python code is, both x and y would be of string. We can convert them to int using another line

x, y = [int(x), int(y)]

# We can also use  list comprehension
x, y = [int(x) for x in [x, y]]

Below is complete one line code to read two integer variables from standard input using split and list comprehension

filter_none

edit
close

play_arrow

link
brightness_4
code

# Reads two numbers from input and typecasts them to int using 
# list comprehension
x, y = [int(x) for x in raw_input().split()]  

chevron_right


filter_none

edit
close

play_arrow

link
brightness_4
code

# Reads two numbers from input and typecasts them to int using 
# map function
x, y = map(int, raw_input().split())

chevron_right


Note that in Python 3, we use input() in place of raw_input().

This article is contributed by Abhishek Shukla. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above



My Personal Notes arrow_drop_up

Improved By : dev_aditya



Article Tags :

12


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.