0

Can someone please explain why the for loop acts differently in these 2 situations? (if it operates on a copy of the variable, why the values change in scenario 1? if not, why the values don’t change in scenario 2?

Scenario 1:

class Person:
  height = 100

people = []

for i in range(2):
  people.append(Person())

for i in people:
  print(i.height)

for i in people:
  i.height += 20

for i in people:
  print(i.height)

Results:

100
100
120
120

Scenario 2:

b = [1, 2, 3]

for i in b:
  i += 5

print(b)

Results:

[1, 2, 3]

Shouldn't it act the same way? I am confused!

Unmitigated
  • 76,500
  • 11
  • 62
  • 80
  • Does this answer your question? [How do I pass a variable by reference?](https://stackoverflow.com/questions/986006/how-do-i-pass-a-variable-by-reference) – InSync Mar 19 '23 at 00:18
  • In your second scenario, the `i` variable is the value of the (immutable) integer item, not a reference to an object in the list. So modifying `i` has no effect on the item at the corresponding position in the list. It is not that for-loop behaves differently but the mutability of the item that causes this apparent difference. – Alain T. Mar 19 '23 at 00:47

1 Answers1

0

The problem with scenario 2 is that the print(b) is not located inside of the for loop. Also, you should be trying to print i not b.

The fixed code looks like this:

b = [1, 2, 3]

for i in b:
  i += 5
  print(i)

Output:

6
7
8
TVXD
  • 33
  • 9
  • If you print ```b```, you will not get the ```i``` values that you just added 5 to. – TVXD Mar 18 '23 at 23:28
  • That’s not the problem, the problem is that after running both loops, the actual value of people[0].height is 120 (not 100) but the value of b[0] is still 1 (not 6) the results are inconsistent. (Don’t focus on print, my problem is with the final values) – amir alamir Mar 18 '23 at 23:32
  • That's because you're editing the values of a class in scenario 1, not the values of a list like you are in scenario 2. – TVXD Mar 18 '23 at 23:39
  • That’s exactly my question, so it means only in dealing with objects, the loop works on the reference and other than that it will be just a copy of the variable? – amir alamir Mar 18 '23 at 23:45
  • That's a good way to see it. – TVXD Mar 18 '23 at 23:47