We wrote 34 short Python programs covering the everyday language and ran each one unchanged on Python 3.11, 3.12, 3.13, 3.14 and 3.15 in the official Docker images, and on Windows with 3.14.3. Each block below shows the code and what it printed, and a label marks anything that needs a version newer than 3.11. We also timed loops against comprehensions and map, and how long Python takes to start.
The short answer: the newest Python is 3.15 (3.15.2, released 25 October 2026). Versions 3.14 and 3.15 get bug fixes, 3.11 to 3.13 get security fixes only, and 3.10 reached end of life on 1 October 2026. The everyday core is the same on all of them: f-strings such as f"{x:,.2f}", comprehensions, match (3.10+), dataclasses, pathlib and exception groups (3.11+). Of our 34 examples, 21 ran on 3.11, 25 on 3.12, 27 on 3.13, 31 on 3.14 and all 34 on 3.15. Newer syntax such as def first[T] (3.12+), t-strings (3.14+) and lazy import (3.15+) is a SyntaxError on older versions. Checked 3 December 2026.
Fastero
Connect your database. Ask questions. Get dashboards.
Postgres, BigQuery, Snowflake, and 10+ sources — live-connected, AI-powered, no dashboard builder learning curve.
Try free →Python versions: release dates and end of life
From the Python Developer's Guide status page and python.org's downloads page, read 3 December 2026:
| Version | Released | End of life | Status | Headline feature |
|---|---|---|---|---|
| 3.16 | October 2027 (planned) | October 2032 | In development | Not fixed yet |
| 3.15 | 9 October 2026 | October 2031 | Bug fixes | lazy import, frozendict, UTF-8 by default |
| 3.14 | 7 October 2025 | October 2030 | Bug fixes | Template strings (t-strings), deferred annotations |
| 3.13 | 7 October 2024 | October 2029 | Security only | New interactive shell, experimental free-threading and JIT |
| 3.12 | 2 October 2023 | October 2028 | Security only | def f[T] generics, f-strings without old limits |
| 3.11 | 24 October 2022 | October 2027 | Security only | Exception groups, tomllib, 10% to 60% faster than 3.10 |
| 3.10 | 4 October 2021 | 1 October 2026 | Ended | match, X | Y types |
Python's what's new page for 3.11 says "Python 3.11 is between 10-60% faster than Python 3.10." A version gets bug fixes and new installers for its first two years (18 months before 3.13), then source-only security fixes until five years after release.

Release and end-of-life dates from devguide.python.org/versions, read 3 December 2026.
The latest patch releases on 3 December 2026 were 3.15.2, 3.14.10, 3.13.18, 3.12.16 and 3.11.18, and those are the exact versions our Docker runs used. To see yours, run python --version, or py -0 on Windows to list every install.
Which Python version does a feature need?
Every example here runs on 3.11 and later unless its first line says 3.12+, 3.13+, 3.14+ or 3.15+. Those need more, and this is what 3.11.18 printed when we ran them:
| Feature | Example | Needs | What 3.11 says |
|---|---|---|---|
| Same quotes inside an f-string | f"{d["a"]}" |
3.12 | SyntaxError: f-string: unmatched '[' |
Generic functions and type aliases |
def first[T](x: T) |
3.12 | SyntaxError: expected '(' |
itertools.batched, Path.walk() |
batched(range(7), 3) |
3.12 | ImportError, AttributeError |
copy.replace() |
copy.replace(row, n=1) |
3.13 | AttributeError |
| Defaults for type parameters | class Box[T = int] |
3.13 | SyntaxError (3.12 too) |
| Template strings | t"Hello {name}" |
3.14 | SyntaxError: invalid syntax |
except without brackets |
except ValueError, TypeError: |
3.14 | SyntaxError: multiple exception types must be parenthesized |
| Unquoted forward references | next: Node inside class Node |
3.14 | NameError: name 'Node' is not defined |
Path.copy(), Path.move() |
src.copy(dst) |
3.14 | AttributeError |
| Unpacking in comprehensions | [*row for row in rows] |
3.15 | SyntaxError: iterable unpacking cannot be used in comprehension |
| Lazy imports | lazy import json |
3.15 | SyntaxError: invalid syntax |
frozendict |
frozendict(a=1) |
3.15 | NameError: name 'frozendict' is not defined |
Syntax errors stop the whole file before its first line runs, so one 3.12 f-string breaks a script on 3.11 even if that line is never reached.
Python basics: types, numbers and literals
n = 42 # int: no size limit
x = 3.14 # float: 64-bit
z = 2 + 3j # complex
big = 1_000_000 # underscores are ignored
s, b = "text", b"raw" # str (Unicode) and bytes
ok, nothing = True, None
print(type(n).__name__, type(x).__name__, type(s).__name__, type(nothing).__name__)
print(2**100)
print(7 / 2, 7 // 2, -7 // 2, 7 % 3, divmod(17, 5))
print(0.1 + 0.2, round(2.5), round(3.5), int("42") + int(3.9))
print(0b1010, 0o17, 0xFF, 1e3, f"{big:,}")
print(True + True, bool(""), bool([0]), None is None)
print(int("ff", 16), float("1.5e2"), str(42), list("abc"), tuple([1, 2]))int float str NoneType
1267650600228229401496703205376
3.5 3 -4 1 (3, 2)
0.30000000000000004 2 4 45
10 15 255 1000.0 1,000,000
2 False True True
255 150.0 42 ['a', 'b', 'c'] (1, 2)Three results surprise people. // rounds down toward minus infinity, so -7 // 2 is -4. round() rounds halves to the even number, so round(2.5) is 2. And 0.1 + 0.2 isn't exactly 0.3, because floats are binary; use decimal.Decimal for money.
Strings and f-strings
Strings are immutable: every method returns a new string.
s = " Hello, World "
print(s.strip(), "|", s.lower().strip(), "|", s.split(","))
print("-".join(["a", "b", "c"]), "a,b,,c".split(","), "x y z".split())
print("Python"[0], "Python"[-1], "Python"[1:4], "Python"[::-1])
print("report.csv".removesuffix(".csv"), "v1.2".removeprefix("v")) # 3.9+
print("data".upper(), "Data Team".title(), "ab".replace("a", "A"))
print("42".isdigit(), "abc".isalpha(), "web".startswith("we"), "py" in "python")
print("na" * 3, len("hello"), "hello".find("l"), "hello".count("l"))
print("7".zfill(3), "id".ljust(5, "."), "total".center(11, "*"))
print("""triple quotes
span lines""", r"C:\raw\no\escapes")Hello, World | hello, world | [' Hello', ' World ']
a-b-c ['a', 'b', '', 'c'] ['x', 'y', 'z']
P n yth nohtyP
report 1.2
DATA Data Team Ab
True True True True
nanana 5 2 2
007 id... ***total***
triple quotes
span lines C:\raw\no\escapesAn f-string puts any expression in braces, followed by a format spec after the colon: , adds thousands separators, .2f two decimals, % a percentage, >10 right-aligns in 10 characters. {x=} prints the expression and its value, which is handy for debugging (3.8+).
from datetime import date
name, price, ratio, n = "Widget", 1234.5, 0.4567, 42
print(f"{name:>10}|{name:<10}|{name:^10}|")
print(f"{price:,.2f} {ratio:.1%} {n:08b} {n:x} {n:e} {1/3:.3f}")
print(f"{price=} {name!r} {3 * 7 = }") # = shows the expression
print(f"{date(2026, 12, 3):%d %b %Y} {date(2026, 12, 3):%A}")
width = 8
print(f"[{n:>{width}}] [{'left':<{width}}]") # nested format spec
print(f"{{braces}} {'quoted'}") Widget|Widget | Widget |
1,234.50 45.7% 00101010 2a 4.200000e+01 0.333
price=1234.5 'Widget' 3 * 7 = 21
03 Dec 2026 Thursday
[ 42] [left ]
{braces} quotedf-strings in Python 3.12+: quotes, backslashes and comments
PEP 701 made f-strings part of Python's grammar in 3.12, so the expression inside the braces can reuse the outer quotes, contain a backslash, span lines and hold a comment. All three lines are errors on 3.11.
# Python 3.12+: PEP 701 lets f-strings reuse quotes, backslashes and comments
prices = {"apple": 1.25, "pear": 0.8}
print(f"apple costs {prices["apple"]}") # same quote type inside
print(f"{"\n".join(["line 1", "line 2"])}") # backslash inside the braces
print(f"total: {
sum(prices.values()) # a comment inside the braces
}")apple costs 1.25
line 1
line 2
total: 2.05t-strings in Python 3.14+
A t-string looks like an f-string but doesn't produce a string. The docs: "Template strings are a mechanism for custom string processing." You get a Template with the text and the values kept apart, so a library can escape values for SQL, HTML or shell before joining them. The quoting function below is a toy to show the idea; use your database driver's parameters for real queries.
# Python 3.14+: template strings (PEP 750) keep the values apart from the text
from string.templatelib import Interpolation, Template
name = "O'Brien"
t = t"Hello {name}!"
print(type(t).__name__, t.strings, t.values)
def sql_literal(template: Template) -> str:
out = []
for part in template: # str pieces and Interpolations
if isinstance(part, Interpolation):
out.append("'" + str(part.value).replace("'", "''") + "'")
else:
out.append(part)
return "".join(out)
print(sql_literal(t"SELECT * FROM users WHERE name = {name}"))Template ('Hello ', '!') ("O'Brien",)
SELECT * FROM users WHERE name = 'O''Brien'Lists, tuples, dicts and sets
| Type | Literal | Ordered | Changeable | Duplicates |
|---|---|---|---|---|
| list | [1, 2, 2] |
Yes | Yes | Yes |
| tuple | (1, 2, 2) |
Yes | No | Yes |
| dict | {"a": 1} |
Insertion order (3.7+) | Yes | Keys unique |
| set | {1, 2} |
No | Yes | No |
| frozendict | frozendict(a=1) |
Insertion order | No | Keys unique (3.15+) |
nums = [3, 1, 4, 1, 5]
nums.append(9) # add one item
nums.extend([2, 6]) # add many
nums.insert(0, 0) # at an index
print(nums, len(nums))
print(nums.pop(), nums.pop(0), nums) # remove last, remove first
print(nums.index(4), nums.count(1), 5 in nums)
nums.remove(1) # first 1 only
print(nums, nums[-1], nums[1:3], nums[::2])
print(sorted(nums), sorted(nums, reverse=True), nums) # sorted() copies
nums.sort(key=lambda v: -v) # .sort() changes the list, returns None
print(nums, min(nums), max(nums), sum(nums))
copy = nums.copy(); copy[0] = 99
print(nums[0], copy[0], [0] * 3, list(range(2, 11, 3)))[0, 3, 1, 4, 1, 5, 9, 2, 6] 9
6 0 [3, 1, 4, 1, 5, 9, 2]
2 2 True
[3, 4, 1, 5, 9, 2] 2 [4, 1] [3, 1, 9]
[1, 2, 3, 4, 5, 9] [9, 5, 4, 3, 2, 1] [3, 4, 1, 5, 9, 2]
[9, 5, 4, 3, 2, 1] 1 9 24
9 99 [0, 0, 0] [2, 5, 8]sorted() returns a new list and works on any iterable; .sort() changes the list in place and returns None, so nums = nums.sort() leaves you with None.
point = (3, 4) # tuple: fixed, hashable
x, y = point
single = (5,) # the comma makes the tuple
print(point[0], len(point), single, point + (5,))
stock = {"apple": 3, "pear": 5}
stock["fig"] = 1 # add or overwrite
print(stock.get("kiwi", 0), stock.pop("pear"), stock)
print(list(stock.keys()), list(stock.values()), list(stock.items()))
print(stock | {"kiwi": 2}) # merge into a new dict, 3.9+
stock.update(plum=4)
stock.setdefault("fig", 99) # only sets a missing key
print(stock, "fig" in stock, len(stock))
for key, value in stock.items():
print(key, value, end="; ")
print()
by_value = dict(sorted(stock.items(), key=lambda kv: kv[1]))
print(by_value, dict(zip(["a", "b"], [1, 2])))
a, b = {1, 2, 3}, {3, 4}
a.add(5); a.discard(9) # discard: no error if missing
print(a | b, a & b, a - b, a ^ b, {1, 2} <= a, set("hello")) # str order varies
print(frozenset({1, 2}) in {frozenset({1, 2})})3 2 (5,) (3, 4, 5)
0 5 {'apple': 3, 'fig': 1}
['apple', 'fig'] [3, 1] [('apple', 3), ('fig', 1)]
{'apple': 3, 'fig': 1, 'kiwi': 2}
{'apple': 3, 'fig': 1, 'plum': 4} True 3
apple 3; fig 1; plum 4;
{'fig': 1, 'apple': 3, 'plum': 4} {'a': 1, 'b': 2}
{1, 2, 3, 4, 5} {3} {1, 2, 5} {1, 2, 4, 5} True {'l', 'o', 'h', 'e'}
TrueDicts keep insertion order. Sets don't: string hashing is randomized per process, so set("hello") prints its letters in a different order from run to run. Use | to merge dicts (3.9+) and .get(key, default) when a key may be missing.
frozendict (3.15+)
Python 3.15 adds an immutable dict, hashable when its contents are. "A frozendict is not a subclass of dict", so isinstance(x, dict) is False for one.
# Python 3.15+: the frozendict built-in (PEP 814)
config = frozendict(region="West", year=2026)
print(config, hash(config) == hash(frozendict(year=2026, region="West")))
try:
config["year"] = 2027
except TypeError as e:
print("TypeError:", e)Output on Python 3.15.2:
frozendict({'region': 'West', 'year': 2026}) True
TypeError: 'frozendict' object does not support item assignmentList comprehensions
A comprehension builds a list, dict or set in one expression: [expr for x in items if cond]. With nested loops, the for clauses read in the same order as the loops would.
squares = [n * n for n in range(10) if n % 2 == 0]
lengths = {w: len(w) for w in ["pandas", "sql", "duckdb"]}
letters = {c.lower() for c in "AbBa"}
total = sum(n * n for n in range(10)) # generator: no list built
matrix = [[1, 2, 3], [4, 5, 6]]
flat = [x for row in matrix for x in row] # loops read left to right
transposed = [list(col) for col in zip(*matrix)]
labels = ["big" if n > 2 else "small" for n in [1, 3]]
print(squares, lengths, sorted(letters), total)
print(flat, transposed, labels)[0, 4, 16, 36, 64] {'pandas': 6, 'sql': 3, 'duckdb': 6} ['a', 'b'] 285
[1, 2, 3, 4, 5, 6] [[1, 4], [2, 5], [3, 6]] ['small', 'big']Unpacking in comprehensions (3.15+)
Python 3.15 lets * and ** flatten inside a comprehension, replacing the double for above and itertools.chain.
# Python 3.15+: * and ** unpacking inside comprehensions (PEP 798)
matrix = [[1, 2, 3], [4, 5, 6]]
dicts = [{"a": 1}, {"b": 2}, {"a": 3}]
print([*row for row in matrix])
print({**d for d in dicts})Output on Python 3.15.2:
[1, 2, 3, 4, 5, 6]
{'a': 3, 'b': 2}Is a list comprehension faster than a for loop?
Slightly. We timed three ways to build a 10,000-item list, of squares and then of strings, with timeit in the 3.11 and 3.15 Docker images, alternating them over eight rounds: 480 samples per case.

Median of 480 timeit samples per bar, Docker images python:3.11-slim (3.11.18) and python:3.15-slim (3.15.2) on one laptop, measured 3 December 2026.
- A comprehension beat the loop every time, by 1% to 7%. On 3.11, squaring was a tie in practice: 319 µs against 322. Python 3.12's what's new page says inlining "speeds up execution of a comprehension by up to two times"; we saw nothing like that here.
mapwith a lambda was slowest, 68% to 75% slower than the loop, because it calls a Python function for every item.map(str, nums)depends on the version: 24% slower than the comprehension on 3.11, 3% faster on 3.15.- Every case was slower on 3.15 than on 3.11 in these images, by 11% to 53%, though both were built with the same configure options (profile-guided optimization and LTO); 3.15 also turns on frame pointers. One laptop and a tiny workload are no verdict on 3.15, so time your own code before an upgrade.
Choose the comprehension because it reads best, not for speed. When a list is only fed to sum(), max() or any(), pass a generator expression instead and no list is built at all.
Unpacking, zip and enumerate
* collects the rest of a sequence, and * and ** spread a list or dict into a call or a literal.
first, *rest = [1, 2, 3, 4]
*init, last = "abc"
a, b = 1, 2
a, b = b, a # swap
(x, y), z = (1, 2), 3 # nested
print(first, rest, init, last, a, b, x, y, z)
print([*rest, *"xy"], {**{"a": 1}, "b": 2}, (*range(3),))
def area(w, h):
return w * h
print(area(*[3, 4]), area(**{"w": 2, "h": 5}))
for i, (name, score) in enumerate([("ann", 9), ("bo", 7)], start=1):
print(i, name, score)
print(*zip("abc", [1, 2, 3]))
print(list(zip("ab", [1, 2, 3]))) # stops at the shortest
try:
list(zip("ab", [1, 2, 3], strict=True)) # 3.10+
except ValueError as e:
print("ValueError:", e)1 [2, 3, 4] ['a', 'b'] c 2 1 1 2 3
[2, 3, 4, 'x', 'y'] {'a': 1, 'b': 2} (0, 1, 2)
12 10
1 ann 9
2 bo 7
('a', 1) ('b', 2) ('c', 3)
[('a', 1), ('b', 2)]
ValueError: zip() argument 2 is longer than argument 1zip stops at the shortest input without a word. Pass strict=True (3.10+) when the lengths must match.
Control flow: if, for, while and match
temp = 23
if temp > 30:
label = "hot"
elif temp > 15:
label = "mild"
else:
label = "cold"
print(label, "even" if temp % 2 == 0 else "odd") # one-line if/else
for n in range(2, 12):
for d in range(2, n):
if n % d == 0:
break # leave the inner loop
else: # runs only if the loop did not break
print(n, end=" ")
print()
count = 0
while count < 10:
count += 1
if count % 3:
continue # skip to the next round
print(count, end=" ")
print()
data = [5, 0, 12, 7]
if (k := len(data)) > 3: # walrus: assign inside an expression, 3.8+
print(f"{k} items, any zero: {any(v == 0 for v in data)}, "
f"all positive: {all(v > 0 for v in data)}")mild odd
2 3 5 7 11
3 6 9
4 items, any zero: True, all positive: FalseA loop's else runs only when the loop ends without break. The walrus operator := assigns inside an expression (3.8+).
match (3.10+) compares a value against patterns and pulls parts out of it: dict keys, list items, class attributes, alternatives with | and conditions with if. The first matching case wins and case _ catches the rest. It isn't a plain switch: a bare name such as case x: matches anything and binds it.
# Python 3.10+: structural pattern matching
from dataclasses import dataclass
@dataclass
class Point:
x: int
y: int
def describe(cmd):
match cmd:
case {"action": "move", "x": int(x), "y": int(y)}:
return f"move to {x},{y}"
case ["load", *files] if files:
return f"load {len(files)} files"
case "quit" | "exit":
return "bye"
case Point(x=0, y=0):
return "origin"
case Point(x=x, y=0):
return f"on the x axis at {x}"
case int() | float() as n if n < 0:
return f"negative {n}"
case _:
return "unknown"
for c in [{"action": "move", "x": 1, "y": 2}, ["load", "a.csv", "b.csv"],
"exit", Point(0, 0), Point(5, 0), -3.5, None]:
print(describe(c))move to 1,2
load 2 files
bye
origin
on the x axis at 5
negative -3.5
unknownFunctions: default arguments, *args, **kwargs and lambda
Parameters after a bare * must be passed by name; parameters before / must be passed by position. *args collects extra positional arguments into a tuple, **kwargs extra keyword arguments into a dict.
def greet(name, greeting="Hello", *, punct="!"): # after *: keyword-only
return f"{greeting}, {name}{punct}"
def total(*args, **kwargs): # extra positional -> tuple, keyword -> dict
return sum(args), kwargs
def clamp(x, /, lo=0, hi=1): # before /: positional-only, 3.8+
return max(lo, min(hi, x))
print(greet("Ann"), greet("Bo", "Hi", punct="?"))
print(total(1, 2, 3, unit="kg", note="net"))
print(clamp(1.7), clamp(-2, lo=-1))
try:
greet("Ann", "Hi", "?")
except TypeError as e:
print("TypeError:", e)
def append_bad(item, bucket=[]): # the default list is made once
bucket.append(item)
return bucket
def append_ok(item, bucket=None):
bucket = [] if bucket is None else bucket
bucket.append(item)
return bucket
print(append_bad(1), append_bad(2), append_ok(1), append_ok(2))
square = lambda n: n * n # a one-expression function
print(square(7), sorted(["bb", "a", "ccc"], key=len),
max(["pear", "fig"], key=lambda w: w[-1]))
def counter():
count = 0
def step():
nonlocal count # rebind the enclosing variable
count += 1
return count
return step
tick = counter()
print(tick(), tick(), tick())Hello, Ann! Hi, Bo?
(6, {'unit': 'kg', 'note': 'net'})
1 -1
TypeError: greet() takes from 1 to 2 positional arguments but 3 were given
[1, 2] [1, 2] [1] [2]
49 ['a', 'bb', 'ccc'] pear
1 2 3The append_bad line is the classic trap: a default value is created once, when the function is defined, so every call that omits bucket shares one list. Use None as the default and make the list inside. nonlocal lets an inner function change a variable of the function around it; global does the same for a module variable.
Classes and dataclasses
class Account:
bank = "Demo Bank" # class attribute, shared
def __init__(self, owner, balance=0):
self.owner = owner # instance attributes
self._balance = balance # _ means "internal" by convention
def deposit(self, amount):
if amount <= 0:
raise ValueError("amount must be positive")
self._balance += amount
return self
@property
def balance(self): # read like an attribute
return self._balance
@classmethod
def from_csv_row(cls, row): # alternative constructor
owner, balance = row.split(",")
return cls(owner, int(balance))
@staticmethod
def fee(amount):
return round(amount * 0.01, 2)
def __repr__(self):
return f"Account({self.owner!r}, {self._balance})"
def __eq__(self, other):
return isinstance(other, Account) and self.owner == other.owner
class Savings(Account): # inheritance
def __init__(self, owner, balance=0, rate=0.02):
super().__init__(owner, balance)
self.rate = rate
def __repr__(self):
return f"Savings({self.owner!r}, {self.balance}, rate={self.rate})"
a = Account("ann").deposit(50).deposit(25)
print(a, a.balance, Account.fee(250), Account.from_csv_row("bo,10"))
print(Savings("cy", 100), isinstance(Savings("cy"), Account), a == Account("ann"))Account('ann', 75) 75 2.5 Account('bo', 10)
Savings('cy', 100, rate=0.02) True TrueA dataclass writes __init__, __repr__ and __eq__ from the annotated fields. order=True adds comparisons, frozen=True makes instances read-only and hashable, slots=True (3.10+) saves memory, and kw_only=True (3.10+) forces named arguments. Use field(default_factory=list) for a mutable default, for the same reason as the function trap above.
from dataclasses import asdict, dataclass, field, replace
@dataclass(order=True, frozen=True, slots=True) # slots: 3.10+
class Version:
major: int
minor: int = 0
@dataclass(kw_only=True) # kw_only: 3.10+
class Order:
id: int
items: list[str] = field(default_factory=list) # never items=[]
total: float = 0.0
def __post_init__(self):
if self.total < 0:
raise ValueError("total must be >= 0")
v = Version(3, 14)
print(v, v < Version(3, 15))
print(sorted([Version(3, 9), v, Version(3, 11)]))
print(replace(v, minor=15), hash(v) == hash(Version(3, 14)))
try:
v.minor = 0
except AttributeError as e: # FrozenInstanceError subclasses it
print(type(e).__name__)
o = Order(id=1, items=["pen"], total=2.5)
print(o, asdict(o))Version(major=3, minor=14) True
[Version(major=3, minor=9), Version(major=3, minor=11), Version(major=3, minor=14)]
Version(major=3, minor=15) True
FrozenInstanceError
Order(id=1, items=['pen'], total=2.5) {'id': 1, 'items': ['pen'], 'total': 2.5}dataclasses.replace() makes a changed copy of a dataclass. Python 3.13 added copy.replace(), which does the same for named tuples, dates and other types:
# Python 3.13+: copy.replace() works on dataclasses, namedtuples, dates and more
import copy
from collections import namedtuple
from datetime import date
Row = namedtuple("Row", "region revenue")
print(copy.replace(Row("West", 10), revenue=12))
print(copy.replace(date(2026, 12, 3), day=25))Row(region='West', revenue=12)
2026-12-25Connect any database. Ask in plain English.
Start free →Exceptions and exception groups
try runs the code, except handles a matching error, else runs only if nothing was raised, and finally always runs. raise ... from e keeps the original error as __cause__, so the traceback shows both, and add_note() (3.11+) attaches context.
import contextlib
class DataError(Exception): # your own exception type
pass
def parse(text):
try:
value = int(text)
except ValueError as e:
raise DataError(f"not a number: {text!r}") from e # keep the cause
else:
return value # runs only if no exception
finally:
print(f"parsed {text!r}", end=" -> ") # always runs
print(parse("42"))
try:
parse("4x2")
except DataError as e:
e.add_note("row 7 of sales.csv") # 3.11+
print(type(e).__name__, e)
print("cause:", type(e.__cause__).__name__, "| notes:", e.__notes__)
with contextlib.suppress(FileNotFoundError): # ignore one error type
open("missing.txt")
try:
{"a": 1}["b"]
except (KeyError, IndexError) as e: # several types at once
print("lookup failed:", repr(e))parsed '42' -> 42
parsed '4x2' -> DataError not a number: '4x2'
cause: ValueError | notes: ['row 7 of sales.csv']
lookup failed: KeyError('b')An ExceptionGroup (3.11+) carries several errors at once, as when you validate a whole row or run tasks side by side. except* handles each type in the group, and more than one except* clause can run:
# Python 3.11+: ExceptionGroup and except*
def validate(row):
errors = []
if not row.get("id"):
errors.append(ValueError("id is missing"))
if row.get("qty", 0) < 0:
errors.append(ValueError("qty is negative"))
if not isinstance(row.get("price"), float):
errors.append(TypeError("price is not a float"))
if errors:
raise ExceptionGroup(f"row {row}", errors)
try:
validate({"id": "", "qty": -1, "price": "9"})
except* ValueError as group: # handles every ValueError in the group
print("values:", [str(e) for e in group.exceptions])
except* TypeError as group: # and, separately, every TypeError
print("types:", [str(e) for e in group.exceptions])values: ['id is missing', 'qty is negative']
types: ['price is not a float']Python 3.14 lets you drop the brackets when you catch several types without as. With as, the brackets are still required.
# Python 3.14+: except and except* without brackets (PEP 758)
try:
int("x")
except ValueError, TypeError:
print("caught without brackets")caught without bracketsFiles and pathlib
pathlib.Path joins paths with / and reads or writes a whole file in one call. Use with open(...) to stream a large file line by line, and pass encoding="utf-8" every time.
from pathlib import Path
base = Path("demo")
(base / "raw").mkdir(parents=True, exist_ok=True) # / joins paths
notes = base / "raw" / "notes.txt"
notes.write_text("first line\nsecond line\n", encoding="utf-8")
print(notes.read_text(encoding="utf-8").splitlines())
with open(notes, "a", encoding="utf-8") as f: # "a" appends, "w" overwrites
f.write("third line\n")
with open(notes, encoding="utf-8") as f: # "r" is the default
for number, line in enumerate(f, start=1): # one line at a time
print(number, line.rstrip())
print(notes.name, notes.stem, notes.suffix, notes.parent.as_posix())
print(notes.exists(), notes.is_file(), notes.stat().st_size, "bytes")
print(notes.with_suffix(".md").name, Path("a/b/c.tar.gz").suffixes)
(base / "raw" / "data.csv").write_text("a,b\n1,2\n", encoding="utf-8")
print(sorted(p.name for p in base.rglob("*.txt")),
sorted(p.name for p in (base / "raw").glob("*")))
print(Path.cwd().is_absolute(), Path("~").expanduser() != Path("~"))
notes.write_text("a\nb\n", encoding="utf-8", newline="\n") # keep \n on Windows
print(notes.stat().st_size, "bytes")['first line', 'second line']
1 first line
2 second line
3 third line
notes.txt notes .txt demo/raw
True True 37 bytes
notes.md ['.tar', '.gz']
['notes.txt'] ['data.csv', 'notes.txt']
True True
4 bytesThat run was on Windows, where text mode writes each \n as \r\n: the same file was 37 bytes there and 34 bytes on Linux. Pass newline="\n" to write_text() or open() to keep Unix line endings. Python 3.15 makes UTF-8 the default encoding everywhere, but its what's new page still advises passing an explicit encoding when code must run on several versions.
Path.walk() (3.12+) is the pathlib version of os.walk():
# Python 3.12+: Path.walk(), the pathlib version of os.walk()
from pathlib import Path
root = Path("tree")
(root / "a" / "b").mkdir(parents=True, exist_ok=True)
(root / "a" / "one.txt").write_text("1", encoding="utf-8")
(root / "a" / "b" / "two.txt").write_text("2", encoding="utf-8")
for folder, subfolders, files in root.walk():
print(folder.as_posix(), sorted(subfolders), sorted(files))tree ['a'] []
tree/a ['b'] ['one.txt']
tree/a/b [] ['two.txt']And 3.14 adds copy(), move() and a cached info attribute, so you no longer need shutil for a single file:
# Python 3.14+: Path.copy() and Path.move()
from pathlib import Path
src = Path("copy-demo/in.txt")
src.parent.mkdir(exist_ok=True)
src.write_text("hello", encoding="utf-8")
out = src.copy(Path("copy-demo/out.txt")) # returns the new path
moved = out.move(Path("copy-demo/moved.txt")) # out.txt is gone now
print(src.exists(), out.exists(), moved.read_text(encoding="utf-8"),
moved.info.is_file())True False hello Trueitertools, collections and functools
Counter counts, defaultdict creates missing keys for you, deque is a list that's fast at both ends, and namedtuple gives tuple fields names.
from collections import Counter, defaultdict, deque, namedtuple
words = "the cat and the hat and a bat".split()
counts = Counter(words)
print(counts.most_common(2), counts["the"], counts["dog"])
by_letter = defaultdict(list) # missing keys start as []
for w in words:
by_letter[w[0]].append(w)
print(dict(by_letter))
recent = deque(maxlen=3) # keeps the last 3 items
for n in range(6):
recent.append(n)
first = recent.popleft() # fast at both ends
print(first, recent)
Sale = namedtuple("Sale", ["region", "revenue"])
s = Sale("West", 1200)
print(s, s.revenue, s._asdict())[('the', 2), ('and', 2)] 2 0
{'t': ['the', 'the'], 'c': ['cat'], 'a': ['and', 'and', 'a'], 'h': ['hat'], 'b': ['bat']}
3 deque([4, 5], maxlen=3)
Sale(region='West', revenue=1200) 1200 {'region': 'West', 'revenue': 1200}from itertools import accumulate, chain, combinations, count, groupby
from itertools import islice, pairwise, product
print(list(chain([1, 2], (3,), "ab")))
print(list(islice(count(10, 5), 4))) # first 4 of an endless counter
print(list(accumulate([3, 1, 4, 1]))) # running total
print(list(pairwise([1, 4, 9, 16]))) # 3.10+
print(list(product("ab", [0, 1])), len(list(combinations(range(5), 2))))
rows = [("East", 3), ("East", 5), ("West", 2), ("East", 1)]
for region, group in groupby(sorted(rows), key=lambda r: r[0]): # sort first!
print(region, sum(qty for _, qty in group))[1, 2, 3, 'a', 'b']
[10, 15, 20, 25]
[3, 4, 8, 9]
[(1, 4), (4, 9), (9, 16)]
[('a', 0), ('a', 1), ('b', 0), ('b', 1)] 10
East 9
West 2groupby only groups neighbors, so sort by the same key first or you'll get East twice. To split a list into chunks, 3.12 added batched:
# Python 3.12+: itertools.batched (its strict= option needs 3.13+)
from itertools import batched
print(list(batched(range(7), 3)))[(0, 1, 2), (3, 4, 5), (6,)]From functools: @cache stores results by argument (@lru_cache(maxsize=128) caps the memory), @wraps keeps a decorated function's name and docstring, and partial fixes some arguments.
from functools import cache, partial, reduce, wraps
@cache # memoize: same args, stored result
def fib(n):
return n if n < 2 else fib(n - 1) + fib(n - 2)
print(fib(90), fib.cache_info().hits)
def logged(func): # a decorator
@wraps(func) # keeps the name and docstring
def wrapper(*args, **kwargs):
print(f"calling {func.__name__} with {args}")
return func(*args, **kwargs)
return wrapper
@logged
def slow_sum(n):
"""Add 0 to n - 1."""
return sum(range(n))
print(slow_sum(10**6), slow_sum.__name__, slow_sum.__doc__)
base2 = partial(int, base=2) # fix some arguments
print(base2("1011"), reduce(lambda a, b: a * b, [1, 2, 3, 4]))2880067194370816120 88
calling slow_sum with (1000000,)
499999500000 slow_sum Add 0 to n - 1.
11 24Type hints and the new generic syntax
Type hints document what a function takes and returns, and checkers such as mypy or Pyright read them. Python itself doesn't enforce them: the last line passes ints where floats are declared, and it runs.
from typing import Literal, Protocol, TypedDict, TypeVar
def mean(values: list[float]) -> float: # list[float]: 3.9+
return sum(values) / len(values)
def find(name: str, ids: dict[str, int]) -> int | None: # X | None: 3.10+
return ids.get(name)
class Row(TypedDict):
region: str
revenue: float
class HasLen(Protocol): # structural: any object with __len__
def __len__(self) -> int: ...
def size(x: HasLen) -> int:
return len(x)
T = TypeVar("T") # generics before 3.12
def first(items: list[T]) -> T:
return items[0]
Mode = Literal["r", "w"]
row: Row = {"region": "West", "revenue": 10.5}
print(mean([1.0, 2.0]), find("b", {"a": 1}), size("abc"), first(["x", "y"]), row)
print(mean.__annotations__) # hints are not enforced:
print(mean([1, 2])) # ints run fine1.5 None 3 x {'region': 'West', 'revenue': 10.5}
{'values': list[float], 'return': <class 'float'>}
1.5Python 3.12 replaced TypeVar boilerplate with square brackets after the name, and added the type statement for aliases:
# Python 3.12+: type parameter syntax and the type statement (PEP 695)
def first[T](items: list[T]) -> T:
return items[0]
class Box[T]:
def __init__(self, item: T) -> None:
self.item = item
type Pair[T] = tuple[T, T]
type Rows = list[dict[str, float]]
print(first([3, 4]), Box("x").item, Pair, Pair.__value__, Rows.__value__)3 x Pair tuple[T, T] list[dict[str, float]]Python 3.13 allows a default for a type parameter:
# Python 3.13+: defaults for type parameters (PEP 696)
class Box[T = int]:
def __init__(self, item: T) -> None:
self.item = item
print(Box.__type_params__[0].__default__)<class 'int'>Since 3.14, annotations are evaluated only when something reads them, so a class can name itself in a method's hints without quotes. On 3.11 to 3.13 this is a NameError; there, write "Node" or put from __future__ import annotations at the top of the file.
# Python 3.14+: annotations are evaluated only when read (PEP 649)
class Node:
def __init__(self, value: int, next: Node | None = None) -> None:
self.value, self.next = value, next
print(Node(1, Node(2)).next.value)
print(Node.__init__.__annotations__["next"])2
__main__.Node | Noneasync and await basics
async def defines a coroutine, await pauses it until the result is ready, and asyncio.run() starts the event loop. While one coroutine waits on the network or a timer, others run, so two waits of 0.2 and 0.3 seconds finish in 0.3 seconds, not 0.5.
import asyncio
import time
async def fetch(name, seconds):
await asyncio.sleep(seconds) # stands in for a network call
return f"{name} after {seconds}s"
async def main():
start = time.perf_counter()
results = await asyncio.gather(fetch("a", 0.2), fetch("b", 0.3))
print(results, f"{time.perf_counter() - start:.1f}s total") # not 0.5
async with asyncio.TaskGroup() as tg: # 3.11+: cancels the rest on error
t1 = tg.create_task(fetch("c", 0.1))
t2 = tg.create_task(fetch("d", 0.1))
print(t1.result(), t2.result())
try:
async with asyncio.timeout(0.1): # 3.11+
await fetch("slow", 1)
except TimeoutError:
print("timed out")
asyncio.run(main())['a after 0.2s', 'b after 0.3s'] 0.3s total
c after 0.1s d after 0.1s
timed outTaskGroup and asyncio.timeout arrived in 3.11. Async helps with many slow network calls; for CPU-heavy work use processes (concurrent.futures.ProcessPoolExecutor) instead.
Modules, venv, pip and uv
Any .py file is a module: import sales runs sales.py once and caches it. Code under if __name__ == "__main__": runs only when the file is executed directly, not when it's imported.
A virtual environment keeps each project's packages apart. On Linux or macOS (we ran this in the python:3.11-slim image):
python3 -m venv .venv
source .venv/bin/activate # the prompt changes; python now means .venv's
pip install requests
pip freeze > requirements.txt # pin what you installed
cat requirements.txt
deactivatecertifi==2026.11.20
charset-normalizer==3.5.3
idna==3.20
requests==2.34.2
urllib3==2.8.0On Windows, in PowerShell, .venv\Scripts\Activate.ps1 activates, but the venv docs note "You don’t specifically need to activate a virtual environment": calling its Python by path works anywhere, including in scheduled tasks. We ran this with Python 3.14.3, and creating the venv took a median 8.4 seconds over three runs on our busy laptop:
python -m venv .venv
.venv\Scripts\python -m pip install six
.venv\Scripts\python -m pip freezesix==1.17.0uv is Astral's Rust-based tool, which its docs describe as "10-100x faster than pip"; the latest release was 0.13.12 on 1 December 2026. It creates the environment, installs Python versions and keeps a lock file. Not run here (we kept downloads small for this post); these commands are from uv's docs:
uv init sales-report # a project with pyproject.toml
cd sales-report
uv add pandas # install and record the dependency
uv run main.py # run inside the project's environment
uv python install 3.15 # fetch another Python version
uvx ruff check # run a tool without installing itUse plain venv and pip when you need nothing extra installed; reach for uv when you juggle several Python versions or want a lock file.
Lazy imports (3.15+)
Python 3.15's lazy keyword defers loading a module until its name is first used:
# Python 3.15+: explicit lazy imports (PEP 810)
lazy import json
import sys
print("json loaded:", "json" in sys.modules)
print(json.dumps({"lazy": True})) # first use loads it
print("json loaded:", "json" in sys.modules)Output on Python 3.15.2:
json loaded: False
{"lazy": true}
json loaded: TrueWe timed each command 64 times. A bare start took 12.0 ms on 3.11 and 14.4 ms on 3.15, and import asyncio 66.3 and 80.2 ms. On 3.15, lazy import asyncio took 14.3 ms, the same as no import, because the name was never used. That matters for command-line tools that import a lot and use a little.

Median of 64 runs each, python:3.11-slim (3.11.18) and python:3.15-slim (3.15.2) on one laptop, measured 3 December 2026.
Python for data work: csv, json and pandas
The standard library reads and writes CSV and JSON with no installs. csv.DictReader returns every value as a string, so convert numbers yourself, and open CSV files with newline="".
import csv
import json
from pathlib import Path
rows = [{"region": "West", "revenue": 1200.5}, {"region": "East", "revenue": 950}]
with open("out.csv", "w", newline="", encoding="utf-8") as f: # newline="" for csv
writer = csv.DictWriter(f, fieldnames=["region", "revenue"])
writer.writeheader()
writer.writerows(rows)
with open("out.csv", newline="", encoding="utf-8") as f:
for row in csv.DictReader(f): # every value comes back as a str
print(row)
text = json.dumps(rows, indent=2)
Path("out.json").write_text(text, encoding="utf-8")
back = json.loads(Path("out.json").read_text(encoding="utf-8"))
print(back[0]["revenue"] + 1, json.dumps({"ok": True, "n": None})){'region': 'West', 'revenue': '1200.5'}
{'region': 'East', 'revenue': '950'}
1201.5 {"ok": true, "n": null}The same pattern totals revenue by region in the invented orders file behind the sample sales table every new Fastero account has, 4,734 rows:
import csv
from collections import defaultdict
totals = defaultdict(float)
with open("sample-sales.csv", newline="", encoding="utf-8") as f:
for row in csv.DictReader(f):
totals[row["region"]] += float(row["revenue"]) # values arrive as str
for region, revenue in sorted(totals.items(), key=lambda kv: -kv[1]):
print(f"{region:<8}{revenue:>12,.0f}")North 417,482
West 413,523
East 336,184
South 306,511pandas does it in two lines, read and group, and parses the dates on the way in. We ran it with pandas 3.0.3 on Python 3.14.3. The latest pandas, 3.1.2 (30 November 2026), needs Python 3.11 or newer, per PyPI.
import pandas as pd
df = pd.read_csv("sample-sales.csv", parse_dates=["order_date"])
print(df.shape, df["order_date"].min().date(), df["order_date"].max().date())
print(df.groupby("region")["revenue"].sum().round().sort_values(ascending=False))
print(pd.__version__)(4734, 10) 2024-11-01 2026-10-31
region
North 417482.0
West 413523.0
East 336184.0
South 306511.0
Name: revenue, dtype: float64
3.0.3For the rest of pandas, see our pandas cheat sheet and what changed in pandas 3; for the SQL side, the SQL cheat sheet.
Where Fastero fits
Fastero is an AI and data platform where people and AI agents work together on a team's data, in the browser. Its notebooks run Python 3.11, so 21 of the examples on this page run there as written, and the 13 labelled 3.12+ to 3.15+ don't: they fail with the errors in the table near the top.
Notebooks come with pandas, seaborn (and so matplotlib), plotly and DuckDB preinstalled, along with SQLAlchemy, psycopg2, openpyxl and the BigQuery client. scikit-learn isn't preinstalled, and a package you add with %pip install lasts for that session only. Python projects run now or on a five-field cron schedule on Fastero's servers, with secrets passed as environment variables, so os.environ["DB_URL"] works unchanged, and each run keeps its log. Colleagues who only view are free.

A Python project in Fastero's demo workspace, which holds invented data, on Python 3.11.
The Free plan has no end date and needs no card: notebooks and Python get 6 hours of compute a day, a notebook server has 1 CPU and 2 GB, and a Python run ¼ CPU and 0.5 GB. Fastero has no GPU. For newer syntax, run Python 3.14 or 3.15 on your own machine or in one of the online Python IDEs we compared; to try a snippet with no install, see online Python compilers. More: running a Python script online, Python cron jobs, Jupyter notebooks online and pricing.
FAQ
What is the latest version of Python?
Python 3.15, first released on 9 October 2026; the latest patch is 3.15.2, from 25 October 2026. It gets bug fixes until about October 2028 and security fixes until October 2031.
Which Python version should I use in 2026?
For new projects, 3.14 or 3.15 if your libraries support them; the latest pandas needs 3.11 or newer. Versions 3.11 to 3.13 get security fixes until October 2027, 2028 and 2029. Move off 3.10 and older, which no longer get fixes.
Is a list comprehension faster than a for loop?
A little. In our timing a comprehension beat a for loop with append by 1% to 7% on Python 3.11 and 3.15, and map with a lambda took 68% to 75% longer than the loop. Pick whichever reads best.
What is the difference between a list, a tuple and a set?
A list is ordered and changeable; a tuple is ordered and fixed, so it can be a dict key; a set has no order and no duplicates, and tests membership fast. A dict maps unique keys to values in insertion order.
What are *args and **kwargs in Python?
In a definition, *args collects extra positional arguments into a tuple and **kwargs extra keyword arguments into a dict. In a call, * and ** spread a list or dict into arguments. Only the stars matter; the names are a convention.
What is the difference between an f-string and a t-string?
An f-string (3.6+) evaluates straight to a str. A t-string (3.14+) evaluates to a Template object that keeps the literal text and the values apart, so a library can escape or check each value before building the final string.
Should I use pip, venv or uv?
venv makes an isolated environment and pip installs into it; both ship with Python. uv does both, installs Python versions and keeps a lock file, and its docs claim 10 to 100 times pip's speed. It's a separate install.
Sources
Read on 3 December 2026:
- Python Software Foundation: Status of Python versions, Python downloads, What's new in Python 3.15, 3.14, 3.13, 3.12, 3.11 and 3.10, venv, string.templatelib
- Astral: uv documentation, uv features, uv releases
- PyPI: pandas
- Our runs: Windows 11 with Python 3.14.3, pandas 3.0.3 and NumPy 2.4.4; Docker images python:3.11-slim (3.11.18), python:3.12-slim (3.12.16), python:3.13-slim (3.13.18), python:3.14-slim (3.14.10) and python:3.15-slim (3.15.2), on an Intel Core i7-11800H laptop
Try Fastero free: run the 3.11-compatible examples from this cheat sheet in a notebook with pandas, plotly and DuckDB already installed. No credit card required.
Fastero Dev Team