On Fri, Feb 20, 2009 at 8:12 AM, ssd <c...@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
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to