Python Objects: A Mass Information Drop

Introduction

ID and Type

int n = 0;
n = 0
>>> a = 0
>>> type(a)
<type 'int'>
>>> a = 'c'
>>> type(a)
<type 'str'>
>>> a = 'c'
>>> type(a)
<type 'str'>
>>> id(a)
34091456L
>>> a = 0
>>> id(a)
33777472L
>>> a = 'c'
>>> id(a)
34091456L
>>> b = 'c'
>>> id(b)
34091456L
>>> b is a
True
>>> b == a
True

Immutable Objects

Mutable Objects

Mutable vs Immutable

>>> a = 0
>>> id(a)
33777472L
>>> a += 1
>>> id(a)
33777448L
>>> a = a + 1
>>> id(a)
33777424L
>>> a -= 2
>>> id(a)
33777472L
>>> b = 2
>>> c = a + b
>>> id(c)
33777424L
>>> a = [1, 2, 3]
>>> id(a)
40974600L
>>> a.append(4)
>>> id(a)
40974600L
>>> a
[1, 2, 3, 4]
>>> a += [4]
>>> a
[1, 2, 3, 4, 4]
>>> id(a)
40974600L
>>> s1 = "HNBN"
>>> s2 = "HNBN"
>>> id(s1)
40467712L
>>> id(s2)
40467712L
>>> la = [1, 2, 3]
>>> lb = [1, 2, 3]
>>> id(la)
41045320L
>>> id(lb)
41061000L
>>> la = [1, 2, 3]
>>> id(la)
41045320L
>>> lb = la
>>> id(lb)
41045320L
>>> la += [4]
>>> lb
[1, 2, 3, 4]
>>> la = la + [4]
>>> lb
[1, 2, 3, 4]
>>> la
[1, 2, 3, 4, 4]
>>> id(lb)
41045320L
>>> id(la)
41121928L

What this means for functions

>>> a = 0
>>> def adder(n):
... n+=1
...
>>> a
0
>>> adder(a)
>>> a
0
>>>la = [0]
>>> def adder (n):
... n[0]+=1
...
>>> la
[0]
>>> adder(la)
>>> la
[1]