Define and reference a variable:
a = 3*2 + 5
a
11
a = "interesting"*3
a
'interestinginterestinginteresting'
No type declaration needed!
(But values still have types--let's check.)
type(a)
str
Python variables are like pointers.
(if that word makes sense)
a = [1,2,3]
b = a
b.append(4)
b
[1, 2, 3, 4]
a
[1, 2, 3, 4]
You can see this pointer with id()
.
print(id(a), id(b))
140441837907336 140441837907336
The is
operator tests for object sameness.
a is b
True
This is a stronger condition than being equal!
a = [1,2,3]
b = [1,2,3]
print("IS ", a is b)
print("EQUAL", a == b)
IS False EQUAL True
What do you think the following prints?
a = [1,2,3]
b = a
a = a + [4]
print(b)
[1, 2, 3]
a is b
False
Why is that?
How could this lead to bugs?
To help manage this risk, Python provides immutable types.
Immutable types cannot be changed in-place, only by creating a new object.
A tuple
is an immutable list
.
a = [1,2,3]
type(a)
list
a = (1,2,3)
type(a)
tuple
Let's try to change that tuple.
a[2] = 0
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-42-ec18b7a325e0> in <module>() ----> 1 a[2] = 0 TypeError: 'tuple' object does not support item assignment
Bonus question: How do you spell a single-element tuple?
a = (3,)
type(a)
tuple
Can you represent that graphically?
# (This cell contains a bunch of voodoo that
# helps with the graphics below. You don't need to
# know what this does.)
%load_ext gvmagic
from objgraph_helper import dot_refs
The gvmagic extension is already loaded. To reload it, use: %reload_ext gvmagic
a = [1,2,3]
b = [a,[1,2], a]
%dotstr dot_refs([b])