0

I just wanted to know if there is any efficient way to take multiple inputs from a user and store it in a list in Python.

Based on my research so far I understand that we can make use of split method to do this however, from what I understand that, if I take this approach and if I have to get 10 value from a user I'll have to define 10 variables and it seems a little tedious to me.

I tried taking multiple inputs and defining it in a list using the following code : x = list(input('Enter 10 numbers ')) print(x) however, this will treat numbers as strings and if I try to use int() function it gives me the following error : invalid literal for int() with base 10

Hence, any suggestions or an efficient approach will be really helpful.

gis
  • 31
  • 6
  • 1
    `x = [int(i) for i in input("Enter 10 numbers: ").split()]`. Read: [List Comprehensions](https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions), [`input()`](https://docs.python.org/3/library/functions.html#input), [`str.split()`](https://docs.python.org/3/library/stdtypes.html#str.split), [`int()`](https://docs.python.org/3/library/functions.html#int). – Olvin Roght Aug 31 '21 at 07:54
  • *"I'll have to define 10 variables"* — How did you conclude *that?* `str.split` returns a list…! – deceze Aug 31 '21 at 07:55

1 Answers1

1

try this:

x = list(map(int, input('Enter 10 numbers ').split()))
print(x)

output:

Enter 10 numbers 1 2 34 56 100 22 340 344 44 5
[1, 2, 34, 56, 100, 22, 340, 344, 44, 5]
I'mahdi
  • 23,382
  • 5
  • 22
  • 30