Define and reference a variable:
a = 3*2 + 5
a
a = "interesting"*3
a
No type declaration needed!
(But values still have types--let's check.)
type(a)
Python variables are like pointers.
(if that word makes sense)
a = [1,2,3]
b = a
b.append(4)
b
a
You can see this pointer with id()
.
print(id(a), id(b))
The is
operator tests for object sameness.
a is b
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)
What do you think the following prints?
a = [1,2,3]
b = a
a = a + [4]
print(b)
a is b
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)
a = (1,2,3)
type(a)
Let's try to change that tuple.
a[2] = 0
Bonus question: How do you spell a single-element tuple?
a = (3,)
type(a)