Retrieve a List of Numbers from User Input in Python
In an attempt to obtain a list of numbers from user input through input() or raw_input(), a developer discovered that numbers were being treated as strings. Thus, the desired result was not achieved.
However, there is a more Pythonic approach to convert the input directly into a list of integers.
For Python 3.x, the following code accomplishes this task:
a = [int(x) for x in input().split()]
This code breaks down the user's input into individual strings, represented by x, using the split() method. Each string is then converted into an integer using the int() function. The resulting list of integers is stored in the variable a.
For illustration, consider the following example:
>>> a = [int(x) for x in input().split()] 3 4 5 >>> a [3, 4, 5] >>>
With this improved approach, the input is successfully transformed into a list of numbers, addressing the issue encountered in the initial attempt.
The above is the detailed content of How to Convert User Input into a List of Integers in Python?. For more information, please follow other related articles on the PHP Chinese website!