Idiomatic way of repeating items in a sequence.

Bob Gailer bgailer at alum.rpi.edu
Mon Jun 30 19:16:42 CEST 2003


At 10:47 AM 6/30/2003 -0600, Bob Gailer wrote:
>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']

Then I noticed John Hunter's IMHO more elegant solution
 >>> newlist = [x for x in sequence for i in range(len(sequence))]
but would adjust it to
 >>> newlist = [x for x in sequence for i in range(repetitions)]
to meet the requirements.

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