Problem with lists.

Chris Rebert clp2 at rebertia.com
Sun Feb 22 16:11:55 EST 2009


On Fri, Feb 20, 2009 at 8:12 AM, ssd <cdsd at d.com> wrote:
>
> Hi,
>
> In the following code, (in Python 2.5)
> I was expecting to get in "b" variable the values  b: [[0, 0], [0, 1],[0,
> 2], [0, 3],[0, 4], [1, 0],[1, 1], [1, 2], .....]
> But I get only the last value [4,4], b: b: [[4, 4], [4, 4], [4, 4], ... ]
>
> My code:
>
> a = ["",""]
> b = []
>
> for i in range (0,5):
>    for j in range (0,5):
>        a[0] = i
>        a[1] = j
>        print "a: " + str(a)
>        b.append(a)

.append() does NOT copy the list `a`, it appends a /reference/ to `a`
(so to speak); thus, when you change `a` on the next iteration, you
change the same list *all* the entries in `b` point to.

Here's a corrected version:

b =[]
for i in range(0,5):
    for j in range(0,5):
        a = [i, j]
        b.append(a)
print b

Cheers,
Chris

-- 
Follow the path of the Iguana...
http://rebertia.com



More information about the Python-list mailing list