Code & computing / QUICK REFERENCE

Python essentials

Built-in types, comprehensions, iteration, functions and common standard-library patterns.

36 entries

Values and strings

Length
len('atlas')

Returns 5; counts code points, not displayed grapheme clusters. [1][6]

Integer conversion
int('42')

Invalid numeric text raises ValueError. [1][6]

Floating-point division
7 / 2

Returns 3.5. [1]

Floor division
7 // 2

Returns 3; negative results round downward. [1]

Remainder
7 % 2

Returns 1. [1]

Formatted string
name = 'Atlas'; message = f'Hello, {name}'

Substitutes the variable into a new string. [1]

Strip surrounding whitespace
' atlas '.strip()

Does not change the original immutable string. [1]

Split words
'one two'.split()

Splits on runs of whitespace. [1]

Join strings
', '.join(['one', 'two'])

Every joined element must be a string. [1]

Slice a string
'abcdef'[1:4]

Returns bcd; the stop index is excluded. [1]

Lists, dictionaries and sets

Create a list
items = [1, 2, 3]

Lists preserve order and allow duplicates. [2]

Last element
items[-1]

Raises IndexError for an empty list. [2]

Append one element
items.append(4)

Mutates the list and returns None. [2]

Sorted copy
sorted([3, 1, 2])

Returns a new list without changing the input. [2][6]

Comprehension
[x * x for x in range(5)]

Produces squares for 0 through 4. [2][6]

Create a dictionary
record = {'name': 'Atlas', 'count': 3}

Keys map to values. [2]

Lookup with fallback
record.get('missing', 0)

Uses the fallback only when the key is absent. [2]

Dictionary entries
list(record.items())

Returns key-value pairs in insertion order. [2]

Unique values
set([1, 1, 2])

A set removes duplicates; do not rely on display order. [2]

Membership
'name' in record

Tests dictionary keys, not values. [2]

Iteration and functions

Index while iterating
for i, value in enumerate(['a', 'b']): print(i, value)

Indexes start at zero unless a start value is given. [3][6]

Pair two iterables
list(zip([1, 2], ['a', 'b']))

Default zip stops at the shorter iterable. [3][6]

Half-open range
list(range(2, 8, 2))

Produces 2, 4 and 6. [3][6]

Small function
def square(x): return x * x

Indentation defines the function body. [3]

Conditional expression
label = 'even' if 4 % 2 == 0 else 'odd'

Selects one expression's value. [3]

Truth test
bool([])

Empty containers are false. [3][6]

Identity check for None
value is None

Prefer identity rather than == for this singleton. [3]

Generator expression
sum(x * x for x in range(5))

Accumulates without creating a list of squares. [3][6]

Useful standard-library patterns

Open text explicitly
with open('notes.txt', encoding='utf-8') as f: text = f.read()

The context manager closes the file. [4]

Parse JSON
import json; record = json.loads('{"count": 3}')

Parses data; do not use eval for JSON. [7]

Serialize JSON
json.dumps({'count': 3})

Import json first; custom objects need handling. [7]

Build a filesystem path
from pathlib import Path; path = Path('data') / 'notes.txt'

Avoids manual separator concatenation. [8]

Count values
from collections import Counter; counts = Counter('banana')

Produces frequencies by distinct element. [9]

Current UTC time
from datetime import datetime, timezone; now = datetime.now(timezone.utc)

Creates an aware datetime rather than a naive one. [10]

Catch a conversion error
try: number = int('bad') except ValueError: number = None

Handles the expected exception, not every error indiscriminately. [5][6]

Enumerate from one
list(enumerate(['a', 'b'], start=1))

Useful for human-readable row numbering. [5][6]

Reserved placement, separate from reference controls. No ad network is active.

Updated Python 3 · portable core syntax

Sources

  1. Built-in types ↗
  2. Data structures ↗
  3. Control flow ↗
  4. Input and output ↗
  5. Standard library tour ↗
  6. Built-in functions ↗
  7. JSON encoding and decoding ↗
  8. Object-oriented filesystem paths ↗
  9. Container datatypes ↗
  10. Date and time types ↗