Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

accepting multiple user inputs separated by a space in python and append them to a list

Tags:

python

list

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.

like image 205
pyCthon Avatar asked Jul 10 '12 00:07

pyCthon


People also ask

How to take multiple inputs from user in Python?

Taking multiple inputs from user in Python. Developer often wants a user to enter multiple values or inputs in one line. In C++/C user can take multiple inputs in one line using scanf but in Python user can take multiple values or inputs in one line by two methods. This function helps in getting a multiple inputs from user .

How to take space-separated input in Python?

The Python built-in input () function is used to prompt the user for input and the split () function to split the input with whitespace. 1. Take space-separated input in Python To read a string input from the user in Python, the built-in input () function is used. The input () function always takes input as a string.

How to split a list in Python with multiple input?

Generally, user use a split () method to split a Python string but one can use it in taking multiple input. List comprehension is an elegant way to define and create list in Python.

How to split the input with whitespace in Python?

The Python built-in input () function is used to prompt the user for input and the split () function to split the input with whitespace. 1. Take space-separated input in Python


2 Answers

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

mynums = [int(i) for i in s.split()]
# OR
mynums = map(int, s.split())
like image 71
Hugh Bothwell Avatar answered Oct 14 '22 07:10

Hugh Bothwell


Try this:

nums = [int(i) for i in raw_input("Enter space separated inputs: ").split()]
like image 37
inspectorG4dget Avatar answered Oct 14 '22 07:10

inspectorG4dget