'How do I read multiple integers from a line of input in python 2?

I am new to python. I searched and found out how to do it in python 3:

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

but in python 2 I get the syntax error. I need it for foobar because I can't code in c++ nor python 3 there which is incredibly annoying.



Solution 1:[1]

In python3 there is no raw_input. The python3 input is the renamed python2 raw_input. So in python2 you should use raw_input instead. Like this:

v = [int(x) for x in raw_input("Enter numbers here").split(" ")]

The argument in split is the separator. In the first example the separator is a space. But if you want to get the numbers separated with -, you can use it like this:

v = [int(x) for x in raw_input("Enter numbers here").split("-")]

Solution 2:[2]

In Python 2 you have 2 input functions:

  • raw_input : this does what you expect; it reads the input as a string.
  • input : this actually evaluates the user input; this is why you get a syntax error; you cannot evaluate a string like "1 2 3 4 5".

So you want to use raw_input():

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

In Python 3 input instead does what you want.

Solution 3:[3]

Try this:

v = [int(x) for x in raw_input("Enter your numbers separated by space: ").split()]

In Python 2.X

  • raw_input() takes exactly what the user typed and passes it back as a string
  • input() first takes the raw_input() and then performs an eval() on as well.

In Python 3.X

  • raw_input() was renamed to input() so now input() returns exactly what the user typed and passes it back as a string
  • Old input() was removed.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mark7888
Solution 2
Solution 3