PROGRAMMING

# REMEMBERS

Last update:   02-12-2021

### Variable

p97 Variables are storing references to the computer memory locations.

# When you assign 42 to a variable,
# you are creating 42 value in computer memory ...
# and store a reference to it
a = 42
b = a

# When later you change the value of a,
# you are creating a new value and store a reference to it
a = 100

# This copy doesn't afect b
assert a == 100
assert b == 42
... 6 lines 

### Lists

! When you copy a list, you are copying the list (because lists are mutable).

# References are different with lists ...
# because lists are mutable

A = [1, 2, 3]
B = A

A[1] = 'x'

assert A == [1, 'x', 3] # pass
assert B == [1, 'x', 3] # pass

# Even the code touches only A list ...
# both A and B have changed!
#
# Values stored in A and B both refer to the same list
... 6 lines 

### Garbage

p100 Python makes automatic garbage collection.

# Python's automatic garbage collection ...
# delete any values not being referred to by any variables
#
# Manual memory management in other programming languages ...
# is a common source of bugs

import sys

a = 'm9 string'
assert sys.getrefcount(a) == 4

b = a
assert sys.getrefcount(a) == 5

c = b
assert sys.getrefcount(a) == 6

del b
assert sys.getrefcount(a) == 5

del c
assert sys.getrefcount(a) == 4
... 11 lines 

Questions     github Collections

A B C D E F
🔔
1/1