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

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]]
Chloe Bennett

Chloe Bennett

Culture, Media & Entertainment Columnist

Chloe Bennett explores the intersection of pop culture, streaming entertainment, digital trends, and contemporary lifestyle. Her weekly commentary reaches thousands of culture enthusiasts.

Share this article
Twitter Facebook Pinterest