Idiomatic way of repeating items in a sequence.

Mike C. Fletcher mcfletch at rogers.com
Mon Jun 30 18:10:54 CEST 2003

```John Hunter wrote:

>This doesn't look too bad to me, but perhaps list comprehensions are
>clearer?
>
>  seq = ['a', 'b', 'c']
>  print [x for x in seq for x in seq]
>
>>> def repeat3( sequence, count=1 ):
...     return [x for x in sequence for i in range(count) ]
...
>>> repeat3( [2,3,4], 3 )
[2, 2, 2, 3, 3, 3, 4, 4, 4]

I *think* is what you were suggesting, and is indeed very clear.  For
those into generators, this is fun (but has no huge advantage if you
wind up using repeat instead of irepeat, or if you're using small
sequences):

>>> from __future__ import generators
>>> def irepeat( sequence, count=1 ):
...     countSet = range(count)
...     for item in sequence:
...         for i in countSet:
...             yield item
...
>>> def repeat( sequence, count = 1 ):
...     return list(irepeat(sequence, count))
...
>>> repeat( [2,3,4], 3 )
[2, 2, 2, 3, 3, 3, 4, 4, 4]

Enjoy,
Mike

_______________________________________
Mike C. Fletcher
Designer, VR Plumber, Coder
http://members.rogers.com/mcfletch/

```