How to take multiple inputs in one line in python

We take multiple inputs in one line in python using

  • split() method
  • List comprehension

Method 1: split()

This function helps in getting multiple inputs from users. It breaks the given input by the specified separator. If a separator is not provided then any white space is a separator. Generally, users use a split() method to split a Python string but one can use it in taking multiple inputs.

Syntax

input().split(separator, maxsplit)

Code

# taking two inputs in one line
x, y = input("Enter two values: ").split()
print("x: ", x)
print("y: ", y)

# taking three inputs in one line
x, y, z = input("Enter three values: ").split()
print("x: ", x)
print("y: ", y)
print("z: ", z)

Output

Enter two values: 5 10
x: 5
y: 10

Method 2: List comprehension

List comprehension is an elegant way to define and create a list in Python. We can create lists just like mathematical statements in one line only. It is also used in getting multiple inputs from a user. 

Code

# taking two input at a time
x, y = [int(x) for x in input("Enter two values: ").split()]
print("x: ", x)
print("y: ", y)

# taking three input at a time
x, y, z = [int(x) for x in input("Enter three values: ").split()]
print("x: ", x)
print("y: ", y)
print("z: ", z)

Output

Enter two values: 5 10
x: 5
y: 10

Conclusion

In this blog, we will see how to take multiple inputs in one line in python? We take multiple inputs in one line in python using split() or list comprehension.

Leave a Comment