how to append to a list twice?

Alex Martelli aleaxit at yahoo.com
Fri Apr 21 11:14:46 EDT 2006


John Salerno <johnjsal at NOSPAMgmail.com> 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?
> 
> Right now I have this:
> 
> series = [100]
> for x in range(10):   # just for testing
>      series.append(series[-1] - 1)
> 
> But of course that only does it once, and I don't want to have to copy
> and paste the append line. Perhaps there's a better way than this.

def makeseries(N):
  series = [N]
  append = series.append
  for tailer in xrange(N-1, -1, -1):
    append(tailer)
    append(tailer)
  return series

series = makeseries(100)

assuming that by "most efficiently" you mean "fastest", this might come
close; you'll want to also time an alternative where makeseries is a
generator which just yields the values, and the last assignment becomes
series=list(makeseries(100)).


Alex



More information about the Python-list mailing list