Sometimes, we want to get a list of numbers as input from the user with Python.
In this article, we’ll look at how to get a list of numbers as input from the user with Python.
How to get a list of numbers as input from the user with Python?
To get a list of numbers as input from the user with Python, we can use list comprehension.
For instance, we write:
a = [int(x) for x in input().split()]
print(a)
to call input
to get the input from the user.
And then we call split
to split the inputted string by the spaces.
Then we call int
to convert each entry from the split string to an int.
And finally, we assign the list to a
.
Therefore, a
is [1, 2]
.
Conclusion
To get a list of numbers as input from the user with Python, we can use list comprehension.