how to append to a list twice?

Gerard Flanagan grflanagan at yahoo.co.uk
Fri Apr 21 12:17:49 EDT 2006


Gerard Flanagan wrote:
> John Salerno wrote:
> > If I want to create a list of the form [100, 99, 99, 98, 98, 97, 97...]
> > (where each item is repeated twice after the first one), how might I do
> > that most efficiently?
>
> series = [100]
>
> for i in range(1,10):
>     series.extend([100-i]*2)
>
> print series
>
> [100, 99, 99, 98, 98, 97, 97, 96, 96, 95, 95, 94, 94, 93, 93, 92, 92,
> 91, 91]

Alternative:

---------------------------------------------------------
series = [100]

r = xrange(99,90,-1)

for L in ( [a1,a2] for a1,a2 in zip( r, r ) ):
    series.extend(L)

print series

out: [100, 99, 99, 98, 98, 97, 97, 96, 96, 95, 95, 94, 94, 93, 93, 92,
92, 91, 91]

---------------------------------------------------------
series = ['a']

r = 'bcdefgh'

for L in ( [a1,a2] for a1,a2 in zip( r, r ) ):
    series.extend(L)

print series

out:  ['a', 'b', 'b', 'c', 'c', 'd', 'd', 'e', 'e', 'f', 'f', 'g', 'g',
'h', 'h']
---------------------------------------------------------

Gerard




More information about the Python-list mailing list