Question

I want to add a value to an element of a two dimensional list. Instead the value is added to all the elements of the column. Could anyone help?

ROWS=3
COLUMNS=5  
a=[[0] * (ROWS)] * (COLUMNS)    
for i in range(ROWS):
    print (a[i])    
print("")
x=5
a[2][1]=a[2][1]+x

for i in range(ROWS):
    print (a[i])
Was it helpful?

Solution

Create you list like this:

In [6]: a = [[0 for _ in range(rows)] for _ in range(cols)]

In [7]: a[2][1] = a[2][1] + 5

In [8]: a
Out[8]: [[0, 0, 0], [0, 0, 0], [0, 5, 0], [0, 0, 0], [0, 0, 0]]

Because the way you are currently doing it, it actually just repeats the same list object, so changing one actually changes each of them.

In [11]: a = [[0] * (rows)] * (cols) 

In [12]: [id(x) for x in a]
Out[12]: [172862444, 172862444, 172862444, 172862444, 172862444] #same id(), i.e same object

OTHER TIPS

The line

a=[[0] * (ROWS)] * (COLUMNS)

creates copies of the lists, not new lists for each column or row.

Use a list comprehension instead:

a = [[0 for _ in range(ROWS)] for _ in range(COLUMNS)]

Quick demonstration of the difference:

>>> demo = [[0]] * 2
>>> demo
[[0], [0]]
>>> demo[0][0] = 1
>>> demo
[[1], [1]]
>>> demo = [[0] for _ in range(2)]
>>> demo
[[0], [0]]
>>> demo[0][0] = 1
>>> demo
[[1], [0]]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top