[Tutor] Append to list

Alan Gauld alan.gauld at yahoo.co.uk
Wed May 9 19:05:05 EDT 2018



On 9 May 2018, at 23:57, Rick Jaramillo <rck.learn at gmail.com> wrote:

>
>Hello,
>I’m having trouble understanding the following behavior and would greatly appreciate any insight. 
>l = [1,2,3,4]
>b=[]
>for i in range(l):
>    print l
>    b.append(l)
>    l.pop(0)
>print b
>OUTPUT 
>[1,2,3,4]
>[2,3,4]
>[3,4]
>[4]
>[[],[],[],[]]
>My confusions is the output for b. I don’t understand why it’s empty. I’m expecting for b to equal [[1,2,3,4], [2,3,4], [3,4], [4]].  

You append l each time. The same l, not a copy of its current state. You also modify l each time. But there is only one list object. It is just being referenced from several places. So all of the references reflect your changes.


Alan g


More information about the Tutor mailing list