Idiomatic way of repeating items in a sequence.
Duncan Booth
duncan at NOSPAMrcp.co.uk
Mon Jun 30 07:54:46 EDT 2003
anlri at wmdata.com (alr) wrote in
news:f58803d.0306300326.705bad44 at posting.google.com:
> 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.
The most obvious one that springs to mind is just a slight simplification
of your version:
def repeatitems(sequence, repetitions):
newlist = []
for item in sequence:
newlist.extend([item] * repetitions)
return newlist
--
Duncan Booth duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?
More information about the Python-list
mailing list