Idiomatic way of repeating items in a sequence.

Max M maxm at mxm.dk
Mon Jun 30 13:44:02 CEST 2003


alr wrote:
> 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


I would make just a minor change:

def repeatitems(sequence, repetitions):
     newlist = []
     for item in sequence:
         newlist += repetitions*[item]
     return newlist


regards Max M





More information about the Python-list mailing list