14

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
  • you need to add element to x and remove the one you dont want Commented Dec 15, 2015 at 12:39

1 Answer 1

14

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]]
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.