Python passes things around by assignment, so basically Python always passes a reference to the object, but the reference is passed by value.
An example where the value of the reference is not changed:
def foo(list_):
list_.append(0)
l = [3, 2, 1]
foo(l)
# l = [3, 2, 1, 0]
Now one where it is changed:
def foo(list_):
list_ = [1, 2, 3]
l = [3, 2, 1]
foo(l)
# l = [1, 2, 3]
You could also get a copy of the list:
def foo(list_):
list_copy = list_.copy()
list_copy.append(0)
l = [3, 2, 1]
foo(l)
# l = [3, 2, 1]
In your example you changed the value of the reference of the i
variable inside the dict d
, but not of the list l
, you used the reference and changed an item inside the list. This happened because lists are mutable, Python integers are not, you made two different operations. You won't be able to change what is inside the dict d
using the variable i
after the assignment, you would need to do d['i'] = 0
for that.