how to append to a list twice?

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


> Interesting. I tried the *2 method twice, but I kept
> getting weird results, I guess because I was using append
> and not extend. I thought extend added lists to lists,
> but obviously that's not the case here.


In the above example, it *is* "add[ing] lists to lists". 
Note the set of brackets:

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

You have a one-element series:

	[series[-1] - 1]

that gets duplicated using the overloading of the 
multiplication ("duplication") operator:

	[...] * 2

This yields a two-element list.  This list then gets passed 
to extend(), to add those two elements to the original list.

If you used append() instead of extend(), it would be 
something like

	[100, [99, 99], [98, 98],...]

-tkc







More information about the Python-list mailing list