Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple inputs from one input

I'm writing a function to append an input to a list. I want it so that when you input 280 2 the list becomes ['280', '280'] instead of ['280 2'].

like image 474
Carl groth Avatar asked Apr 16 '16 11:04

Carl groth


People also ask

How do you take multiple inputs from 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. Using split() method : This function helps in getting multiple inputs from users. It breaks the given input by the specified separator.


2 Answers

>>> number, factor = input().split()
280 2
>>> [number]*int(factor)
['280', '280']

Remember that concatenating a list with itself with the * operator can have unexpected results if your list contains mutable elements - but in your case it's fine.

edit:

Solution that can handle inputs without a factor:

>>> def multiply_input():
...     *head, tail = input().split()
...     return head*int(tail) if head else [tail]
... 
>>> multiply_input()
280 3
['280', '280', '280']
>>> multiply_input()
280
['280']

Add error checking as needed (for example for empty inputs) depending on your use case.

like image 114
timgeb Avatar answered Oct 23 '22 12:10

timgeb


You can handle the case with unspecified number of repetitions by extending the parsed input with a list containing 1. You can then slice the list to leave the first 2 items (in case the number of repetitions was provided, that [1] will be discarded)

number, rep = (input().split() + [1])[:2]
[number] * int(rep)
like image 27
Eli Korvigo Avatar answered Oct 23 '22 11:10

Eli Korvigo