how to append to a list twice?

Tim Chase python.list at tim.thechases.com
Fri Apr 21 11:16:14 EDT 2006


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

Well, you can do something like

def foo(start):
     count = 0
     while 1:
         yield start - ((count + 1) / 2)
         count += 1

which is pretty efficient in the matter.  If you just need 
the results, you can do something like

series = [100]
for _ in range(10):
     series.extend([x[-1]-1]*2)

Both should get you what you want, and one or the other may 
be better depending on the scenario in which you want to use it.

-tkc







More information about the Python-list mailing list