Python 3 syntax and data structures for everyday scripting. Examples use Python 3.10 or later; match requires 3.10. For a function-by-function index, see the built-in functions and methods reference.
General rules and help
Names are case-sensitive, sequence indices start at zero, and indentation defines blocks. Use four spaces per indentation level. help(str.replace) shows documentation and dir(str) lists available attributes.
Modules
import math
from datetime import datetime, timedelta
print(math.sqrt(9)) # 3.0
moment = datetime.strptime('2026-10-21', '%Y-%m-%d')
print((moment + timedelta(days=1)).strftime('%Y-%m-%d')) # 2026-10-22
import module binds the module name. from module import name binds a selected name. Prefer explicit imports to from module import *.
Scalar types
| Type | Purpose | Example |
|---|---|---|
int |
Arbitrary-precision integers; Python 3 has no separate long type |
10 ** 30 |
float |
Floating-point values; decimal fractions may be approximate | 0.1 + 0.2 |
bool |
Boolean values | True, False |
str |
Unicode text | 'hello' |
bytes |
Binary data | b'hello' |
NoneType |
Type of the singleton None |
type(None) |
None is a reserved keyword. Compare with is None, rather than treating it as an empty string or zero.
value = None
if value is None:
print('No value')
print(int('42')) # 42
print('hello'.encode()) # b'hello'
print(b'hello'.decode()) # hello
Tuples and lists
Tuples are immutable sequences; lists are mutable sequences. A tuple's members can themselves refer to mutable objects. Methods such as append, extend and sort modify a list and return None.
point = (3, 4)
x, y = point
x, y = y, x
items = [3, 1, 2]
items.append(4)
items.extend([5, 6])
items.insert(0, 0)
last = items.pop()
items.remove(1) # remove the first matching value
print(sorted(items)) # [0, 2, 3, 4, 5]; items is unchanged
items.sort()
print(items) # [0, 2, 3, 4, 5]
Indexing and slicing
The start is inclusive and the stop is exclusive. Omitting the start or stop uses the corresponding end of the sequence. A zero step raises ValueError.
values = [0, 1, 2, 3, 4]
print(values[0], values[-1]) # 0 4
print(values[1:4]) # [1, 2, 3]
print(values[::2]) # [0, 2, 4]
print(values[::-1]) # [4, 3, 2, 1, 0]
Dictionaries
Dictionaries map hashable keys to values and preserve insertion order. keys(), values() and items() return dynamic views, not lists. update() modifies the dictionary in place.
settings = {'theme': 'light', 'size': 12}
settings['theme'] = 'dark'
print(settings.get('language', 'en')) # en
settings.update({'size': 14})
print(list(settings.keys())) # ['theme', 'size']
print('theme' in settings) # True
del settings['size']
Sets
Sets hold distinct hashable elements. They do not provide positional indexing. {} creates an empty dictionary; set() creates an empty set.
a, b = {1, 2, 3}, {3, 4}
print(sorted(a | b)) # [1, 2, 3, 4], union
print(sorted(a & b)) # [3], intersection
print(sorted(a - b)) # [1, 2], difference
print(sorted(a ^ b)) # [1, 2, 4], symmetric difference
print({1, 2}.issubset(a)) # True
Functions and defaults
A function without an explicit return value returns None. Multiple return values are packed into a tuple. Use None instead of a mutable default when each call needs a fresh list.
def add_item(value, items=None):
if items is None:
items = []
items.append(value)
return items
double = lambda number: number * 2
print(add_item('a')) # ['a']
print(add_item('b')) # ['b']
print(double(3)) # 6
Iteration
enumerate yields index/value pairs. In Python 3, zip, map, filter and reversed return iterators. Materialize an iterator with list() when a list is required; consuming it does not reset it.
for index, name in enumerate(['Ada', 'Lin'], start=1):
print(index, name)
print(list(zip(['a', 'b'], [1, 2]))) # [('a', 1), ('b', 2)]
print(list(map(str, [1, 2]))) # ['1', '2']
print(list(reversed([1, 2, 3]))) # [3, 2, 1]
Conditions and control flow
Use == for equality and is for identity. pass does nothing. Use if/elif/else for conditions; Python 3.10+ also supports structural pattern matching, which is more than a C-style switch.
score = 8
result = 'pass' if score >= 6 else 'retry'
print(result) # pass
command = 'open'
match command:
case 'open':
print('Opening')
case _:
print('Unknown command')
Classes
class Person:
def __init__(self, name):
self.name = name
def greet(self):
return f'Hello, {self.name}'
@staticmethod
def category():
return 'person'
person = Person('Ada')
print(person.greet()) # Hello, Ada
print(Person.category()) # person
Strings
print(', '.join(['a', 'b'])) # a, b
print('a-b-c'.split('-')) # ['a', 'b', 'c']
print('5'.zfill(2)) # 05
print(f'{4.88:.2f}') # 4.88
print('Hello, {name}'.format(name='Ada')) # Hello, Ada
print(r'C:\Users\Ada') # backslashes are literal
Exceptions
Catch the exception types a caller can handle. finally runs whether the operation succeeds or raises. Use raise to report an error.
try:
number = int('invalid')
except ValueError as error:
print(type(error).__name__) # ValueError
finally:
print('Finished')
Comprehensions
numbers = [1, 2, 3, 4]
print([n * 2 for n in numbers if n % 2 == 0]) # [4, 8]
print({n: n * n for n in numbers}) # {1: 1, 2: 4, 3: 9, 4: 16}
print(sorted({n % 2 for n in numbers})) # [0, 1]
matrix = [[1, 2], [3, 4]]
print([value for row in matrix for value in row]) # [1, 2, 3, 4]