A
alr
I need to repeat each item in a list n times, like this function does:
def repeatitems(sequence, repetitions):
newlist = []
for item in sequence:
for i in range(repetitions):
newlist.append(item)
return newlist
Output:
Clear and simple. But i wonder if there is a more idiomatic way. Surely not this:
def repeatitems(sequence, repetitions):
return reduce(lambda l, i: l + i, [[item] * repetitions for item in sequence])
?
def repeatitems(sequence, repetitions):
newlist = []
for item in sequence:
for i in range(repetitions):
newlist.append(item)
return newlist
Output:
['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c']>>> repeatitems(['a', 'b', 'c'], 3)
Clear and simple. But i wonder if there is a more idiomatic way. Surely not this:
def repeatitems(sequence, repetitions):
return reduce(lambda l, i: l + i, [[item] * repetitions for item in sequence])
?