0
a = [[1,2,3],[4,5,6],[7,8,9]]

for x in a:
   x[0] = 0

print(a)

gives:

[[0, 2, 3], [0, 5, 6], [0, 8, 9]]

but:

for x in a:
   for y in x:
       y = 0

gives:

[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

I expected:

[[0,0,0],[0,0,0],[0,0,0]]

Why couldn't I modify 'a' in the second example?

Tim M
  • 479
  • 1
  • 8
  • 21
  • Not exactly, why does it work in the first case? – Tim M Dec 21 '21 at 18:49
  • 2
    Because `y` is an `int`, which is immutable. `list` is a mutable object. You can change its contents – dumbPotato21 Dec 21 '21 at 18:50
  • Ah, OK. I can change x but not y. Annoying. How can I (cleanly) modify all the values of a 2D list? – Tim M Dec 21 '21 at 18:51
  • @MichaelSzczesny I'd argue that that distinction doesn't really exist in python. – dumbPotato21 Dec 21 '21 at 18:51
  • 1
    `y = 0` You're rebinding the name `y` to a new value; it does not remember its previous life as the loop variable. – John Gordon Dec 21 '21 at 18:53
  • 1
    @dumbPotato21 While correct, this isn't the reason why `y` doesn't change. The reason is that `y` is a label pointing to each element in `x`, and `y = 0` just makes the label to point to `0` instead. – Ted Klein Bergman Dec 21 '21 at 18:53
  • True. Doing `x = [0,0,0]` wouldn't work either. Just wanted to mention that you can change a list. Changing ints is not possible – dumbPotato21 Dec 21 '21 at 18:54
  • OK, so x is a label for the sub list on a, and if I change the first element of that label=, I change the actual list? I think I get that. – Tim M Dec 21 '21 at 18:55
  • 1
    @TimMottram You do `for x in a: for i in range(len(x)): x[i] = 0` to modify all elements. – Ted Klein Bergman Dec 21 '21 at 18:55
  • You simply set a variable ```y``` to a value of ```0``` instead of referencing to the index of the inner list. You are iterating in a manner that results with the actual elements inside a list. However, if your aim is to change the values of the list, iterating over the indexes (as you are doing in your first example: ```for x in a: x[0] = 0```), would do the trick (at least for the last iteration). – Matthias Dec 21 '21 at 18:55
  • @TimMottram yes. whenever you do `x = something` in python, you're binding `x` to a new object. It doesn't change the original value. – dumbPotato21 Dec 21 '21 at 18:58
  • Just a note: ```for x in a: for i in range(len(x)): x[i] = 0``` Gave me a syntax error... – Tim M Dec 21 '21 at 19:24

0 Answers0