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 (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

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.