Idiomatic way of repeating items in a sequence.

Bob Gailer bgailer at alum.rpi.edu
Mon Jun 30 18:47:28 CEST 2003


At 04:26 AM 6/30/2003 -0700, 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
>
>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])

 >>> sequence = ['a', 'b', 'c']
 >>> repetitions = 3
 >>> newlist = []
 >>> map(newlist.extend,apply(zip,[sequence]*repetitions))
 >>> newlist
['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c']

Bob Gailer
bgailer at alum.rpi.edu
303 442 2625
-------------- next part --------------

---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.492 / Virus Database: 291 - Release Date: 6/24/2003


More information about the Python-list mailing list