A variable in Python is a name pointing at an object. That is a slightly different model from “a box holding a value”, and the difference explains several behaviours that surprise beginners — why two variables can change together, why is and == disagree, and why a default argument can remember things between calls.
Assignment#
age = 34
name = "Ana"
price = 12.99
No type declaration, and no fixed type. A name can point at anything, and can be repointed at any time:
value = 42
value = "forty-two"
value = [1, 2, 3]
Python still knows the type — it belongs to the object, not to the name:
print(type(42)) # <class 'int'>
print(type("Ana")) # <class 'str'>
print(isinstance(42, int)) # True - the preferred check
The built-in types#
| Type | Example | Holds |
|---|---|---|
int |
42 |
whole numbers, any size |
float |
12.99 |
decimals |
str |
"Ana" |
text |
bool |
True |
true or false |
list |
[1, 2, 3] |
ordered, changeable |
tuple |
(1, 2) |
ordered, fixed |
dict |
{"a": 1} |
key to value |
set |
{1, 2} |
unique, unordered |
NoneType |
None |
deliberately nothing |
Two Python-specific details. Integers have no size limit — 2 ** 1000 is an ordinary int. And bool is a subclass of int, so True + True is 2, which is occasionally useful for counting.
Numbers#
a = 7
b = 2
print(a + b, a - b, a * b) # 9 5 14
print(a / b) # 3.5 - always a float
print(a // b) # 3 - floor division
print(a % b) # 1 - remainder
print(a ** b) # 49
print(0.1 + 0.2) # 0.30000000000000004
That last line is not a Python flaw — binary floating point cannot represent 0.1 exactly, and the same happens in every language. For money, use decimal:
from decimal import Decimal
print(Decimal("0.1") + Decimal("0.2")) # exactly 0.3
Pass strings to Decimal, not floats. Decimal(0.1) inherits the float’s imprecision before it starts.
Strings#
name = "Ana"
print(len(name)) # 3
print(name.upper()) # ANA
print(name[0], name[-1]) # A a
print(name * 3) # AnaAnaAna
print("na" in name) # True
age = 34
print(f"{name} is {age}") # f-string - the modern way
print(f"{price:.2f}") # formatting inside the braces
Strings cannot be changed in place. Every operation returns a new one:
name = "Ana"
name[0] = "B" # TypeError
name = "B" + name[1:] # this works - a new string
Conversion#
int("42") # 42
int(3.9) # 3 - truncates, does not round
float("3.14") # 3.14
str(42) # "42"
bool(0) # False
list("abc") # ['a', 'b', 'c']
int("3.9") # ValueError - not a valid integer literal
int("abc") # ValueError
Convert safely when the input comes from a person or a file:
def to_int(text, default=0):
try:
return int(text)
except (ValueError, TypeError):
return default
print(to_int("42")) # 42
print(to_int("abc")) # 0
Mutable and immutable#
This is the distinction that explains a whole family of bugs.
| Immutable | Mutable |
|---|---|
int, float, bool |
list |
str |
dict |
tuple |
set |
frozenset, None |
most custom classes |
a = [1, 2, 3]
b = a # both names point at the SAME list
b.append(4)
print(a) # [1, 2, 3, 4] - a changed too
a = 5
b = a
b = b + 1
print(a) # 5 - unchanged, because ints are immutable
To copy rather than share:
b = a.copy() # or list(a), or a[:]
import copy
b = copy.deepcopy(a) # for nested structures
A shallow copy only copies one level. Nested lists are still shared, which is what deepcopy is for.
The mutable default argument#
def add_item(item, items=[]): # the list is created ONCE
items.append(item)
return items
print(add_item("a")) # ['a']
print(add_item("b")) # ['a', 'b'] - the same list again
The default is evaluated when the function is defined, not when it is called, so every call without an argument shares one list. The fix is always the same:
def add_item(item, items=None):
if items is None:
items = []
items.append(item)
return items
is and ==#
a = [1, 2, 3]
b = [1, 2, 3]
print(a == b) # True - same contents
print(a is b) # False - different objects
== asks whether the values are equal; is asks whether they are the same object. Use is only with None, True and False. On numbers and strings it appears to work for small values, because Python reuses those objects, and then fails unpredictably for larger ones.
if value is None: # correct
if value == None: # works, but not idiomatic
Naming#
user_count = 10 # snake_case for variables
MAX_RETRIES = 3 # upper case for constants
class ShoppingCart: # capitalised words for classes
pass
_internal = "private by convention"
Rules: letters, digits and underscores only; cannot start with a digit; case-sensitive; cannot be a keyword such as class, for or lambda.
Multiple assignment#
a, b, c = 1, 2, 3
x = y = z = 0
a, b = b, a # swap, no temporary needed
first, *rest = [1, 2, 3, 4] # first=1, rest=[2, 3, 4]
Type hints#
name: str = "Ana"
age: int = 34
scores: list[float] = []
def average(numbers: list[float]) -> float:
return sum(numbers) / len(numbers) if numbers else 0.0
Python ignores these at run time, so they cost nothing. What they buy is editor autocomplete and a checker such as mypy catching mistakes before you run anything.
Questions people ask#
Do I need to declare types?
No. Python infers them. Type hints are optional and useful in anything larger than a script.
What is the difference between a list and a tuple?
A list can be changed; a tuple cannot. That makes tuples usable as dictionary keys and set members, and it signals “this is a fixed record” to whoever reads the code.
Why is 0.1 + 0.2 not 0.3?
Binary floating point cannot represent those decimals exactly. Compare with math.isclose, or use decimal when exactness matters.
How much memory does a variable use?
sys.getsizeof(obj) tells you, though it does not include what a container’s contents use. Python objects carry more overhead than you might expect — a small integer is around 28 bytes.
Where to go next#
- Python basics — the rest of the language in one page.
- Number and type conversion — conversion in more depth.
- Python lists explained — the most-used mutable type.