I tried to use raw_input()
to get a list of numbers, however with the code
numbers = raw_input()
print len(numbers)
the input
num = int(input('Size of elements : '))
arr = list()
for i in range(num) :
ele = int(input())
arr.append(ele)
print(arr)
You can use .split()
numbers = raw_input().split(",")
print len(numbers)
This will still give you strings, but it will be a list of strings.
If you need to map them to a type, use list comprehension:
numbers = [int(n, 10) for n in raw_input().split(",")]
print len(numbers)
If you want to be able to enter in any Python type and have it mapped automatically and you trust your users IMPLICITLY then you can use eval
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]
>>>
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())
).
I think if you do it without the split() as mentioned in the first answer. It will work for all the values without spaces. So you don't have to give spaces as in the first answer which is more convenient I guess.
a = [int(x) for x in input()]
a
Here is my ouput:
11111
[1, 1, 1, 1, 1]
you can pass a string representation of the list to json:
import json
str_list = raw_input("Enter in a list: ")
my_list = json.loads(str_list)
user enters in the list as you would in python: [2, 34, 5.6, 90]