Idiomatic way of repeating items in a sequence.

sismex01 at hebmex.com sismex01 at hebmex.com
Mon Jun 30 17:44:02 CEST 2003


> From: anlri at wmdata.com [mailto:anlri at wmdata.com] 
> Sent: Lunes, 30 de Junio de 2003 06:26 a.m.
> 
> 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:
> 
>   >>> repeatitems(['a', 'b', 'c'], 3)
>   ['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c']
> 
> 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])
>

eek, lambdas.  Something like this comes to mind:

def repeatitems(L, n):
    out = []
    for i in L:
        out.extend([i]*n)
    return out

Sometimes a for loop is better :-)

-gustavo

pd: I haven't tested it, so caveat emptor!
Advertencia:La informacion contenida en este mensaje es confidencial y
restringida, por lo tanto esta destinada unicamente para el uso de la
persona arriba indicada, se le notifica que esta prohibida la difusion de
este mensaje. Si ha recibido este mensaje por error, o si hay problemas en
la transmision, favor de comunicarse con el remitente. Gracias.





More information about the Python-list mailing list