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']
.
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.
>>> 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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With