Get a list of numbers as input from the user Get a list of numbers as input from the user python python

Get a list of numbers as input from the user


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]>>> 


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())


eval(a_string) evaluates a string as Python code. Obviously this is not particularly safe. You can get safer (more restricted) evaluation by using the literal_eval function from the ast module.

raw_input() is called that in Python 2.x because it gets raw, not "interpreted" input. input() interprets the input, i.e. is equivalent to eval(raw_input()).

In Python 3.x, input() does what raw_input() used to do, and you must evaluate the contents manually if that's what you want (i.e. eval(input())).