Skip to content

How to take n inputs in one line in Python | Example code

  • by

You can use a list comprehension to take n inputs in one line in Python. The input string is split into n parts, then the list comp creates a new list by applying int() to each of them.

Example take n inputs in one line in Python

Simple example code

n = 2  # how many numbers to accept
numbers = [int(num) for num in input().split(" ", n-1)]

print(numbers)

Output:

How to take n inputs in one line in Python

The following snippet will map the single line input separated by white space into a list of integers

lst = list(map(int, input().split()))

print(lst)

Output:

1 2 3
[1, 2, 3]

How to take multiple inputs of different data types in one line in Python?

Answer: Example take 2 input values.

x, y = input("Enter a two value: ").split()

print(x, y)

Output:

Enter a two value: 1 X
1 X

OR

score, name = int(input('Enter Score: ')), input('Enter name:')

print(score)
print(name)

Do comment if you have any doubts and suggestions on this Python input topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading