Idiomatic way of repeating items in a sequence.

alr anlri at
Mon Jun 30 13:26:17 CEST 2003

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):
      return newlist


  >>> 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])


More information about the Python-list mailing list