1

I am trying to use raw_input in the python code to get user input of lists as below.

input_array.append(list(raw_input()));

User input as:

1 2 3 5 100

But the code is interpreting input as

[['1', ' ', '2', ' ', '3', ' ', '5', ' ', '1', '0', '0']]

Try: If I use plain input() instead of raw_input(), I am facing the issue in console.

"SyntaxError: ('invalid syntax', ('<string>', 1, 3, '1 2 3 4 100'))"

Note: I am not allowed to give the input in list format like

[1,2,3,5,100]

Could somebody please tell me how to proceed further.

1
  • 1
    That data looks to you like numbers separated by spaces, but to the computer it's just a string of characters (which happen to be decimal digits and spaces). When you cast it to a list, Python thinks you want a list composing of every individual character in the string. What you want is to separate the string into shorter substrings, using the spaces as the word delimiter; then, turn each substring into an integer and put it in a list. That's what the answer below does. Commented Dec 5, 2014 at 3:52

1 Answer 1

6
>>> [int(x) for x in raw_input().split()]
1 2 3 5 100
[1, 2, 3, 5, 100]

>>> raw_input().split()
1 2 3 5 100
['1', '2', '3', '5', '100']

Creates a new list split by whitespace and then

[int(x) for x in raw_input().split()]

Converts each string in this new list into an integer.


list()

is a function that constructs a list from an iterable such as

>>> list({1, 2, 3}) # constructs list from a set {1, 2, 3}
[1, 2, 3]
>>> list('123') # constructs list from a string
['1', '2', '3']
>>> list((1, 2, 3))
[1, 2, 3] # constructs list from a tuple

so

>>> list('1 2 3 5 100')
['1', ' ', '2', ' ', '3', ' ', '5', ' ', '1', '0', '0']

also works, the list function iterates through the string and appends each character to a new list. However you need to separate by spaces so the list function is not suitable.

input takes a string and converts it into an object

'1 2 3 5 100'

is not a valid python object, it is 5 numbers separated by spaces. To make this clear, consider typing

>>> 1 2 3 5 100
SyntaxError: invalid syntax

into a Python Shell. It is just invalid syntax. So input raises this error as well.

On an important side note: input is not a safe function to use so even if your string was '[1,2,3,5,100]' as you mentioned you should not use input because harmful python code can be executed through input. If this case ever arises, use ast.literal_eval:

>>> import ast
>>> ast.literal_eval('[1,2,3,5,100]')
[1, 2, 3, 5, 100]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.