5

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'].

0

4 Answers 4

8
>>> 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.

1
  • I like it, but it appears it runs into an error when you only enter 280, I could use ugly code like I usually do to fix this but do you know of any sleek solution?
    – Carl Groth
    Apr 16, 2016 at 11:46
2

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)
1
  • A bit of text would help the reader understand quicker your solution.
    – Laur Ivan
    Apr 16, 2016 at 14:22
2
from itertools import repeat

mes=input("please write your number and repetitions:").split()
listt= []
listt.extend(repeat(int(mes[0]), int(mes[1]))   

#repeat(object [,times]) -> create an iterator which returns the object
#for the specified number of times.  If not specified, returns the object
#endlessly.
2
  • Please consider explaining the rationale behind your code to make it easier for those who are trying to learn from it.
    – Reti43
    Apr 16, 2016 at 19:59
  • 1
    Thank you! I was going insane trying to .append my inputs when I (unbeknownst to me) actually wanted to .extend them.
    – Carl Groth
    Apr 17, 2016 at 11:20
0

This code provides exception handling against no second number being provided with in put.

def addtolist():
    number = input("Enter number: ")
    try:
        factor = input("Enter factor: ")
    except SyntaxError:
        factor = 1
    for i in range(factor):
        listname.append(number)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.