Python Variables and Data Types

Chapter 1 of 18

Many tutorials describe a variable as “a box that holds data”. In Python that picture misleads. A Python variable is a name bound to an object: the object exists first, and the name just points at it.

Names, not boxes

a = [1, 2, 3]
b = a
b.append(4)
print(a)  # [1, 2, 3, 4]

b = a does not copy the list. Both names point at the same list object, so a change made through b is visible through a. Once this clicks, the rest of Python’s data model stops being surprising.

a = [1, 2, 3]
b = a
print(a is b)   # True — same object
print(a == b)   # True — equal value

Use == for value equality and is only when you mean “the same object”.

Built-in types you use every day

Type Example Mutable
int 42 no
float 3.14 no
str "hello" no
bool True no
list [1, 2] yes
tuple (1, 2) no
dict {"a": 1} yes
set {1, 2} yes
NoneType None no

Types are never declared, but you can always ask:

print(type(42))       # <class 'int'>
print(type("hello"))  # <class 'str'>

Mutable vs immutable

“Modifying” an immutable object really creates a new one:

s = "hello"
s = s + " world"   # a new string; the old one is untouched

Mutable objects change in place:

nums = [1, 2]
nums.append(3)     # same object, new contents

The practical consequence: changes to a mutable object inside a function are visible to the caller; changes to an immutable one are not.

Three common traps

  1. Float precision. 0.1 + 0.2 == 0.3 is False. Use decimal.Decimal when exact decimal arithmetic matters.
  2. is on strings or numbers. Small integers and short strings are cached, so is sometimes “works” by accident. Never use it for equality.
  3. Booleans are ints. True + True is 2. Test truthiness with if x:, not if x == True:.

Naming

Use snake_case for variables, UPPER_CASE for constants, and avoid l, O, I as single letters. Never shadow built-ins like list, dict or str.

Summary

  • A variable is a name bound to an object.
  • == compares values, is compares identity.
  • Whether a change is visible outside a function depends on whether the object is mutable.

Next up: the list and dict operations you will reach for constantly.