[Tutor] lists

Jeff Shannon jeff@ccvcorp.com
Fri Jun 6 19:22:02 2003


Lloyd Kvam wrote:

> Do you really need to save list2's (potential) contents?
> Yes:
>     list2.append(list1[:])    # copy from list1 to list2


Actually, this isn't going to do what you probably think it does.

list2.append() will add a single item to list2.  That item will be a 
copy of list1.

 >>> list1 = [1, 2, 3]
 >>> list2 = []
 >>> list2.append(list1[:])
 >>> list2
[[1, 2, 3]]
 >>> list2[0]
[1, 2, 3]
 >>>

What you're thinking should happen would actually be done by extend() 
rather than append() --

 >>> list2.extend(list1[:])
 >>> list2
[[1, 2, 3], 1, 2, 3]
 >>>

And actually, there's no benefit to using a full-slice of list1 -- 
you're creating a temporary list that's identical to list1, and then 
appending/extending list2 using that temporary list.  You'll have the 
same effect using list1 instead of list1[:].

Jeff Shannon
Technician/Programmer
Credit International