pythonlistinput

Get a list of numbers as input from the user


I tried to use input (Py3) /raw_input() (Py2) to get a list of numbers, however with the code

numbers = input()
print(len(numbers))

the input [1,2,3] and 1 2 3 gives a result of 7 and 5 respectively – it seems to interpret the input as if it were a string. Is there any direct way to make a list out of it? Maybe I could use re.findall to extract the integers, but if possible, I would prefer to use a more Pythonic solution.


Solution

  • In Python 3.x, use this.

    a = [int(x) for x in input().split()]
    

    Example

    >>> a = [int(x) for x in input().split()]
    3 4 5
    >>> a
    [3, 4, 5]
    >>>