1

I wanted to change the value of the argument(list), so I wrote the code as follows, but it didn't work properly.

def add1(s): # s is a list
    for i in s:
        i += 1

So I changed the code as shown below, and it worked. However, I want to know why the first code didn't work properly.

def add1(s):
    for i in range(len(s)):
        s[i] += 1

If you know the reason and explain it, I would really appreciate it.

Sooyeon
  • 71
  • 1
  • 5
  • Read this for a full explanation - https://robertheaton.com/2014/02/09/pythons-pass-by-object-reference-as-explained-by-philip-k-dick/ – Tom Ron Oct 26 '19 at 15:30
  • If you reassign `i` it will become a new reference to the new value. The old value still remains in memory and the reference in the list is still pointing to it. – Klaus D. Oct 26 '19 at 15:30
  • Thank you all!! Now I understand. – Sooyeon Oct 26 '19 at 15:47

2 Answers2

0

i is a local variable in the loop that's holding the number that s holds. Reassigning a variable doesn't effect the data that it held originally.

It's similar to how this doesn't change a:

a = 1
b = a  # This is somewhat what's happening with `for i`
b += 1  # And this is comparable to i += 1

print(a, b)  # Will print 1 2, not 2 2
Carcigenicate
  • 43,494
  • 9
  • 68
  • 117
0

int values are immutable. You can't change the value of an existing int; you can only replace it with a different int. But that means you only change what the name i refers to, not the element of s used to initialize i in the first place.

In your first code, you make i reference a new int.

In your second code, you make a particular slot of s refer to a new instance of int.

chepner
  • 497,756
  • 71
  • 530
  • 681