Problem with lists.

Matimus mccredie at gmail.com
Sun Feb 22 16:23:47 EST 2009


On Feb 20, 8:12 am, "ssd" <c... 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)
>
> print "b: " + str(b)
>
> what is worng in the code?
>
> Thanks,
> Bye,

The problem is that `a' is the name of a list object. When you change
the contents of that list object you are simply mutating that object.
You then append that list object to list `b'. But, you aren't creating
a new list, you are simply mutating the same list object over and over
and appending it to list `b'. So list `b' contains 5 references to the
same object.

A couple of things I would do differently. There is no reason to
declare `a' outside of the loop. This isn't C you don't have to
declare your variables before they are needed. `range(0, 5)' is
usually just written `range(5)'. Also, check out  `xrange'.


Here are a couple of examples of alternatives:

construct new lists and append them in the inner loop:

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


check out list comprehension:

b = [[i, j] for i in range(5) for j in range(5)]
print b


Matt



More information about the Python-list mailing list