Python change element in array [duplicate]

How I can change element in array? I have this code, but I expected that it would print [[5,5],[1,4]]. But it wouldn't. It still prints [[1,2],[1,4]].

x = [[1,2], [1,4]]
for element in x: if element[1] == 2: element = [5,5]
print x
1

1 Answer

Change a list element requires an index.

list_object[index] = new_value

Using enumerate, you can iterate the list and get a indexes.

>>> x = [[1,2], [1,4]]
>>> for i, element in enumerate(x):
... if element[1] == 2:
... x[i] = [5,5]
...
>>> x
[[5, 5], [1, 4]]

You Might Also Like