Velocity Reviews > Idiomatic way of repeating items in a sequence.

# Idiomatic way of repeating items in a sequence.

Jeff Epler
Guest
Posts: n/a

 06-30-2003
Here's one:

def repeatitems(sequence, repetitions):
r = [None] * repetitions
return [i for i in sequence for j in r]

Here's another, using generator functions (so the return is an iterator,
not a list):

def repeatitems(sequence, repetitions):
r = [None] * repetitions
for item in sequence:
for i in r:
yield item

In both cases I've performed an "optimization" by precomputing a list
with len(repetitions) instead of computing it once for each item in
sequence. Whether this makes a difference, I don't know.

Jeff

Mike C. Fletcher
Guest
Posts: n/a

 06-30-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/

alr
Guest
Posts: n/a

 07-02-2003
Wow, tanks for alle the replies. My favourite is John Hunters/Bob
Gailers solution ([x for x in seq for i in range(repetitions)]). I had
forgotten that you could have nested for statements in list
literals... Aahz's point is taken. I happen to need to repeat lists of
strings (which are immutable), but that's not what i asked about now
is it.

--
Regards
André Risnes