Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to modify the elements in a list within list

Tags:

python

list

I am very new to Python, trying to learn the basics. Have a doubt about the list.

Have a list:

L = [[1,2,3],[4,5,6],[3,4,6]]

The output should be:

[[2,4,6],[8,10,12],[6,8,12]]

The code that works for me is the following

for x in range(len(L)):
    for y in range(len(L[x])):
        L[x][y] = L[x][y] + L[x][y]
print L

It gives the output [[2,4,6],[8,10,12],[6,8,12]].

Now I want the same output with a different code:

for x in L:
    a = L.index(x)
    for y in L[a]:
        b = L[a].index(y)
        L[a][b] = L[a][b] + L[a][b]
print L

With the above code the output obtained is:

[[4,2,6],[8,10,12],[12,8,6]]

I tried to debug about the above output. I put a print statement above the line "L[a][b] = L[a][b] + L[a][b]" for printing a and b. I was surprised to see the values of a and b are :

0,0
0,0
0,2
1,0
1,1
1,2
2,0
2,1
2,0

Again if I comment out the line "L[a][b] = L[a][b] + L[a][b]" then the values of a and b are as expected:

0,0
0,1
0,2
1,0
1,1
1,2
2,0
2,1
2,2

I suspect this might be happening due to the scope of variable in python and tried to study few stuffs about scoping in python. But I didn't get appropriate answer neither for scoping or the above question.

like image 366
s.patra Avatar asked Nov 09 '22 19:11

s.patra


1 Answers

You modifying your list with statement - L[a][b] = L[a][b] + L[a][b] e.g. -

L = [[1, 2, 3], [4, 5, 6], [3, 4, 6]]

L[0][0] = 1 initially Then you modify it as L[0][0] = 2

L = [[2, 2, 3], [4, 5, 6], [3, 4, 6]]

In next loop you search index for 2, which is 0,0 now, Because you modified list L. I tried to print L along with a,b in your example. Result explains the behavior -

0 0
[[1, 2, 3], [4, 5, 6], [3, 4, 6]]
0 0
[[2, 2, 3], [4, 5, 6], [3, 4, 6]]
0 2
[[4, 2, 3], [4, 5, 6], [3, 4, 6]]
1 0
[[4, 2, 6], [4, 5, 6], [3, 4, 6]]
1 1
[[4, 2, 6], [8, 5, 6], [3, 4, 6]]
1 2
[[4, 2, 6], [8, 10, 6], [3, 4, 6]]
2 0
[[4, 2, 6], [8, 10, 12], [3, 4, 6]]
2 1
[[4, 2, 6], [8, 10, 12], [6, 4, 6]]
2 0
[[4, 2, 6], [8, 10, 12], [6, 8, 6]] 
like image 52
AlokThakur Avatar answered Nov 14 '22 21:11

AlokThakur