Python Introduction: Names and Values

Define and reference a variable:

In [1]:
a = 3*2 + 5
In [2]:
a
Out[2]:
11
In [3]:
a = "interesting"*3
In [4]:
a
Out[4]:
'interestinginterestinginteresting'

No type declaration needed!

(But values still have types--let's check.)

In [26]:
type(a)
Out[26]:
str

Python variables are like pointers.

(if that word makes sense)

In [27]:
a = [1,2,3]
In [28]:
b = a
In [29]:
b.append(4)
In [30]:
b
Out[30]:
[1, 2, 3, 4]
In [31]:
a
Out[31]:
[1, 2, 3, 4]

You can see this pointer with id().

In [33]:
print(id(a), id(b))
140441837907336 140441837907336

The is operator tests for object sameness.

In [34]:
a is b
Out[34]:
True

This is a stronger condition than being equal!

In [36]:
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?

In [38]:
a = [1,2,3]
b = a
a = a + [4]
print(b)
[1, 2, 3]
In [39]:
a is b
Out[39]:
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.

In [40]:
a = [1,2,3]
type(a)
Out[40]:
list
In [41]:
a = (1,2,3)

type(a)
Out[41]:
tuple

Let's try to change that tuple.

In [42]:
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?

In [43]:
a = (3,)

type(a)
Out[43]:
tuple

Can you represent that graphically?

In [12]:
# (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
In [13]:
a = [1,2,3]
b = [a,[1,2], a]
In [14]:
%dotstr dot_refs([b])
ObjectGraph o140352440694024 list 3 items o140352442844424 list 3 items o140352440694024->o140352442844424 o140352440694024->o140352442844424 o140352437032136 list 2 items o140352440694024->o140352437032136 o10923616 int 3 o140352442844424->o10923616 o10923584 int 2 o140352442844424->o10923584 o10923552 int 1 o140352442844424->o10923552 o140352437032136->o10923584 o140352437032136->o10923552
In [ ]: