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.
You just need to type
raw_input().split()
and the default split() is that values are split by a whitespace.Try this:
You can use
.split()
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:
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
try this one ,
If the element of the list is just a number the statement 1 will get executed and if it is a string then statement 2 will be executed. In the end you will have an list l1 as you needed.
You can still use your code but you will need to tweak it a bit. You can use the code for python 2.9 or less:
If you use python 3 or higher you can use the code:
You can use this function (with int type only) ;)
This function return your list (with int type) !
Example :
If you enter
then