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

Carl Groth
  • 97
  • 1
  • 7

4 Answers4

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.

Community
  • 1
  • 1
timgeb
  • 76,762
  • 20
  • 123
  • 145
  • 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 '16 at 11:46
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.
Taylan
  • 736
  • 1
  • 5
  • 14
  • Please consider explaining the rationale behind your code to make it easier for those who are trying to learn from it. – Reti43 Apr 16 '16 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 '16 at 11:20
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)
Eli Korvigo
  • 10,265
  • 6
  • 47
  • 73
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)
Jonathan
  • 86
  • 7