Get a list of numbers as input from the user


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

numbers = raw_input()
print len(numbers)

the input [1,2,3] gives a result of 7, so I guess it interprets 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.

6/8/2016 3:29:26 PM

Accepted Answer

In Python 3.x, use this.

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


>>> a = [int(x) for x in input().split()]
3 4 5
>>> a
[3, 4, 5]
4/9/2015 7:25:25 AM

It is much easier to parse a list of numbers separated by spaces rather than trying to parse Python syntax:

Python 3:

s = input()
numbers = list(map(int, s.split()))

Python 2:

s = raw_input()
numbers = map(int, s.split())

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow