-3

When I use brackets to item in the second example, the list can be changed.

list1 = [[1, 2]]

for item in list1:
    item = [88, 88]

print(list1)

-----------------

list2 = [[[1, 2]]]

for item in list2:
    item[0] = [88, 88]

print(list2)

output:

[[1, 2]]   
[[[88, 88]]]  

I did a search to find that item is just a temporary name for the element. Not the item itself. So why when adding [] to "item" the list itself can be changed?

Helmi
  • 83
  • 9
  • What is the expected output? – mad_ Apr 22 '20 at 17:55
  • I'm not expecting anything, I'm just wondering why this happens. – Helmi Apr 22 '20 at 17:58
  • 1
    Does this answer your question? [Python list doesn't reflect variable change](https://stackoverflow.com/questions/12080552/python-list-doesnt-reflect-variable-change) – Marcin Orlowski Apr 22 '20 at 17:58
  • Also check this, different situation but same reason https://stackoverflow.com/questions/5234126/python-variable-scope-passing-by-reference-or-copy – AndD Apr 22 '20 at 18:02
  • 2
    `item[0]` is syntactic sugar for a (mutating) method call: `item[0] = [88,88]` is equivalent to `item.__setitem__(0, [88, 88])`. – chepner Apr 22 '20 at 18:36

2 Answers2

1

First of all, I think you should read about Iteration in python.

Just to clear things up:

  • list1 = [[1, 2]] means you have list1 containing a list, which contains the list [1,2] at list1[0].
  • list2 = [[[1, 2]]] means you have list2 containing the list [[1, 2]].

Secondly, in order to change the value of the first item in the list, from [1,2] to [88,88], you can write:

list1 = [[1, 2]]

for item in list1:
    item[0] = 88
    item[1] = 88

print(list1)

output:

[[88, 88]]

Now, let's explain:

For each iteration of the for loop the variable item is assigned with just a copy of the value of an item in the list, so changes made to item won't be reflected in the list.

That is why in your first attempt, (with list1) when you iterated over the list - item = [88, 88] only changed the copy and not the actual list (the copy here was of the list [1,2]).

In your second attempt, i.e:

for item in list2:
    item[0] = [88, 88]

For each iteration of the for loop, you are accessing item[0] which is a copy of the reference to the first element in item. Therefore when you assign value to it, the value is changed in the list.

0

To my understanding, In the first example, when your program goes through the for loop, it gets the value of item (being [1, 2]), inside the for loop you change the variable item to [88, 88], not actually updating the list itself, but rather updating the variable containing [1, 2].

In the second example, the for loop returns the variable item as the second list inside list2. When you use the square brackets it gets the index of 0 in that list, meaning it looks for the 0th element in the list and then updates that to your value of [88, 88].

Hope this helps.

Ben
  • 89
  • 8