Ayush Goyal
Ayush Goyal

Reputation: 233

What is the way to get variable number of inputs from user in one line in python?

I'm new to python. We have to accept two lines of inputs according to one problem. The first line will tell how many numbers will be entered in the next line. Then the next line will have that many numbers and we need to perform some operations on those numbers. So, I know that accepting multiple inputs from a single line is fairly easy when you know how many numbers you are going to get. For example, if you know the user will enter 3 numbers, one can do this:

a,b,c=map(int,input().split())

But what should one do when the number of inputs to be accepted is not known?

Please excuse me if this question is a duplicate, but I couldn't find any solution for the same. Any help is appreciated.

Many thanks.

Upvotes: 1

Views: 321

Answers (3)

FatihAkici
FatihAkici

Reputation: 5109

Why don't you just do:

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

Say your input is "1 2 3 4 5", a will be [1, 2, 3, 4, 5], and you can use its elements however you want.

Upvotes: 1

Darkonaut
Darkonaut

Reputation: 21694

A simple list comprehension is all you need here:

a = [int(i) for i in input().split()]
1 2 3 4 5
a
# Out: [1, 2, 3, 4, 5]

Upvotes: 1

vishes_shell
vishes_shell

Reputation: 23554

You can assign your map to one variable, and then it will become map object, which you can iterate easily.

If you want list you can use star(*) expression

*a, = map(int, input().split())
  ^
not this comma, it is important in unpacking

Simple example:

In [1]: *a, = map(int, input().split())
1 2 3 4 5

In [2]: a
Out[2]: [1, 2, 3, 4, 5]

Upvotes: 0

Related Questions