Define and reference a variable:

In [22]:
a = 3*2 + 5
In [23]:
a
Out[23]:
11
In [24]:
a = "interesting"*3
In [25]:
a
Out[25]:
'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