Some python basics

Wencao Yang
1 min readJun 7, 2020

See the following example.


def assign_value(n, v):
print(“address of n {}”.format(id(n))) n = v print(“address of n {}”.format(id(n)))
list1 = [1, 2, 3]list2 = [4, 5, 6]list3 = list1[:] list4 = list1 assign_value(list1, list2)print(list1)print(“address of list1 {}”.format(id(list1)))print(“address of list3 {}”.format(id(list3)))print(“address of list4 {}”.format(id(list4)))

when pass reference as function parameters, the reference is actually a copy of the reference (the value of address pointed by reference), rebinding inside the function will not affect the outside variables

some other notes

list = list + [“a”] # not in-placelist += [“a”] # in-place

In python, int, float, bool, str, tuple are immutable, and list, dict, set are mutable. How does that affect the reference? In short, when try to change an immutable object, you create a new one. You can reference the same object and change the value inside if it’s mutable.

# inta = 1
b = 1
print(id(a))
print(id(b))
a = a + 1
print(id(a))
a = 2
print(id(a))
# list a = [1]
b = [1]
print(id(a))
print(id(b))
a = [2]
print(id(a))

See reference for mutable and immutable object:

Mutable vs Immutable Objects in Python

--

--