Problem with lists.

desas2 at gmail.com desas2 at gmail.com
Sun Feb 22 16:03:03 EST 2009


On Feb 20, 10: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,

This is what I did and gives your expected results. I am sure, there
may be better way of doing it.
a = []
b =[]
for i in range(0,5):
    for j in range(0,5):
        a.append(i)
        a.append(j)
        b.append(a)
        a =[]
print b

output:
[[0, 0], [0, 1], [0, 2], [0, 3], [0, 4], [1, 0], [1, 1], [1, 2], [1,
3], [1, 4],
 [2, 0], [2, 1], [2, 2], [2, 3], [2, 4], [3, 0], [3, 1], [3, 2], [3,
3], [3, 4],
 [4, 0], [4, 1], [4, 2], [4, 3], [4, 4]]

HTH
Dinakar



More information about the Python-list mailing list