9

How can I accept multiple user inputs separated by a space? I don't know the number of inputs, but I do know they are all ints.

Here's some example inputs:

13213 412 8143
12 312
1321 142 9421 9 29 319 

I know can do this if I know the number of inputs beforehand, but I'm having trouble making this generic. I could just ask the user to input how many groups of ints he will input:

inputs = int(raw_input("Enter number of raw inputs "))
num = []
for i in xrange(1, inputs):
    num.append(raw_input('Enter the %s number: '))

But I am looking for a more elegant solution that doesn't require asking the user 2 questions.

4 Answers 4

25
s = raw_input("Please enter your numbers: ")

mynums = [int(i) for i in s.split()]
# OR
mynums = map(int, s.split())
Sign up to request clarification or add additional context in comments.

2 Comments

@inspectorG4dget thanks! i uped both of you, i have to be fair although the oneliner is much more elegant
+1 to both of you -- @inspectorG4dget special recognition for "argv!"
12

Try this:

nums = [int(i) for i in raw_input("Enter space separated inputs: ").split()]

Comments

0

for python 2.x

x,y = map(int,raw_input().split())

it take two variable x and y of int type separated by space and you can replace int with your desired type

for python 3.x

x,y = input().split()

it takes two variables x and y of string type separated by space and you have to convert explicitly

Comments

0

x,y=map(int,input().split()) #this will take input separated by space and map #into int

1 Comment

I don't see any tag or comment for what language this is. Can you clarify the question?

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.