Free lab Real Python 3. Zero installs. Your code stays in this browser. Open the playground
92 snippets · 13 categories

The Python you keep looking up.

Every snippet here shows the output it genuinely produces — they are executed and checked, not written from memory. Filter by topic, search for what you need, copy it, or open it in the playground and change it.

92 snippets

Print several values

Output & f-strings

print() joins its arguments with a space.

print("Total:", 42, "items")
Total: 42 items
Try it

Put a variable in text

Output & f-strings

An f-string drops values straight into the sentence.

name = "Ana"
print(f"Hello, {name}!")
Hello, Ana!
Try it

Round a number in text

Output & f-strings

:.2f shows exactly two decimal places.

price = 12.3456
print(f"Price: {price:.2f}")
Price: 12.35
Try it

Thousands separator

Output & f-strings

:, makes big numbers readable.

print(f"{1234567:,}")
1,234,567
Try it

Pad and align

Output & f-strings

<10 pads right, >10 pads left — how you line up columns.

for item, qty in [("apple", 3), ("banana", 12)]:
    print(f"{item:<10}{qty:>4}")
apple        3
banana      12
Try it

Show a percentage

Output & f-strings

:.1% turns 0.256 into 25.6%.

print(f"{0.256:.1%}")
25.6%
Try it

Print without a newline

Output & f-strings

end= replaces the line break.

for i in range(3):
    print(i, end=" ")
print()
0 1 2
Try it

Debug a variable

Output & f-strings

The = suffix prints the name and the value.

total = 99
print(f"{total=}")
total=99
Try it

Change case

Strings

Useful for comparing user input.

print("Python".upper(), "Python".lower())
PYTHON python
Try it

Strip whitespace

Strings

Removes spaces and newlines from both ends.

print(repr("  hi  ".strip()))
'hi'
Try it

Split into a list

Strings

Splits on the separator you give it.

print("a,b,c".split(","))
['a', 'b', 'c']
Try it

Join a list into text

Strings

The separator goes in front of .join().

print(" & ".join(["eggs", "milk", "bread"]))
eggs & milk & bread
Try it

Replace part of a string

Strings

Returns a new string — the original is unchanged.

print("2026-01-05".replace("-", "/"))
2026/01/05
Try it

Does it contain / start / end

Strings

in, startswith and endswith all return True or False.

f = "report.csv"
print("port" in f, f.startswith("re"), f.endswith(".csv"))
True True True
Try it

Slice out a piece

Strings

[start:stop] — stop is not included.

s = "abcdefgh"
print(s[:3], s[3:5], s[-2:])
abc de gh
Try it

Reverse a string

Strings

[::-1] steps backwards through it.

print("stressed"[::-1])
desserts
Try it

Check what kind of text

Strings

Handy for validating input.

print("123".isdigit(), "abc".isalpha(), "a1".isalnum())
True True True
Try it

Count occurrences

Strings

Counts non-overlapping matches.

print("banana".count("an"))
2
Try it

Divide two ways

Numbers & math

/ gives a decimal, // throws away the remainder.

print(7 / 2, 7 // 2, 7 % 2)
3.5 3 1
Try it

Powers

Numbers & math

** is 'to the power of'.

print(2 ** 10)
1024
Try it

Round a number

Numbers & math

round() to n decimals; watch banker's rounding on .5.

print(round(3.14159, 2), round(2.5), round(3.5))
3.14 2 4
Try it

Absolute value and min/max

Numbers & math

Work on any numbers you pass.

print(abs(-7), min(3, 9, 1), max([3, 9, 1]))
7 1 9
Try it

Sum a list

Numbers & math

sum() with an optional starting value.

print(sum([1, 2, 3, 4]))
10
Try it

Convert between types

Numbers & math

int() truncates, it does not round.

print(int("42") + 1, float("3.5"), str(99) + "!")
43 3.5 99!
Try it

Square root and ceiling

Numbers & math

math has the rest of school maths.

import math
print(math.sqrt(144), math.ceil(4.1), math.floor(4.9))
12.0 5 4
Try it

Average of a list

Numbers & math

statistics.mean beats writing it by hand.

import statistics
print(statistics.mean([2, 4, 4, 6]))
4
Try it

Add and remove

Lists

append adds one, extend adds many, pop removes and returns.

xs = [1, 2]
xs.append(3)
xs.extend([4, 5])
last = xs.pop()
print(xs, last)
[1, 2, 3, 4] 5
Try it

Insert and delete

Lists

insert takes a position; remove takes a value.

xs = ["a", "c"]
xs.insert(1, "b")
xs.remove("a")
print(xs)
['b', 'c']
Try it

Sort

Lists

sort() changes the list; sorted() returns a new one.

xs = [3, 1, 2]
print(sorted(xs), sorted(xs, reverse=True), xs)
[1, 2, 3] [3, 2, 1] [3, 1, 2]
Try it

Sort by something

Lists

key= says what to sort on.

people = [("Ana", 30), ("Bo", 25)]
print(sorted(people, key=lambda p: p[1]))
[('Bo', 25), ('Ana', 30)]
Try it

Position and count

Lists

index finds the first match.

xs = ["a", "b", "a"]
print(xs.index("b"), xs.count("a"), len(xs))
1 2 3
Try it

Slice a list

Lists

Same [start:stop:step] as strings.

xs = [0, 1, 2, 3, 4, 5]
print(xs[2:5], xs[::2], xs[::-1])
[2, 3, 4] [0, 2, 4] [5, 4, 3, 2, 1, 0]
Try it

Loop with the index

Lists

enumerate gives you position and value together.

for i, item in enumerate(["a", "b"], start=1):
    print(i, item)
1 a
2 b
Try it

Loop two lists together

Lists

zip stops at the shorter one.

for name, score in zip(["Ana", "Bo"], [9, 7]):
    print(name, score)
Ana 9
Bo 7
Try it

Flatten a nested list

Lists

A comprehension with two for clauses.

nested = [[1, 2], [3, 4]]
print([x for row in nested for x in row])
[1, 2, 3, 4]
Try it

Remove duplicates, keep order

Lists

dict.fromkeys preserves first-seen order.

xs = [3, 1, 3, 2, 1]
print(list(dict.fromkeys(xs)))
[3, 1, 2]
Try it

Read safely

Dictionaries

get() returns a default instead of crashing.

user = {"name": "Ana"}
print(user.get("name"), user.get("age", "unknown"))
Ana unknown
Try it

Add, update, delete

Dictionaries

Assign to add or overwrite.

d = {"a": 1}
d["b"] = 2
d.update({"a": 10})
del d["b"]
print(d)
{'a': 10}
Try it

Loop over pairs

Dictionaries

items() gives key and value.

for k, v in {"a": 1, "b": 2}.items():
    print(k, "->", v)
a -> 1
b -> 2
Try it

Keys, values, membership

Dictionaries

in checks keys, not values.

d = {"a": 1, "b": 2}
print(list(d.keys()), list(d.values()), "a" in d)
['a', 'b'] [1, 2] True
Try it

Count things

Dictionaries

The classic tally pattern.

words = ["a", "b", "a"]
counts = {}
for w in words:
    counts[w] = counts.get(w, 0) + 1
print(counts)
{'a': 2, 'b': 1}
Try it

Count things, the short way

Dictionaries

Counter does the same in one line.

from collections import Counter
print(Counter("mississippi").most_common(2))
[('i', 4), ('s', 4)]
Try it

Group into lists

Dictionaries

setdefault creates the list on first sight.

pairs = [("fruit", "apple"), ("veg", "leek"), ("fruit", "pear")]
g = {}
for k, v in pairs:
    g.setdefault(k, []).append(v)
print(g)
{'fruit': ['apple', 'pear'], 'veg': ['leek']}
Try it

Sort a dict by value

Dictionaries

sorted() over .items() with a key.

scores = {"Ana": 9, "Bo": 7, "Cy": 8}
print(sorted(scores.items(), key=lambda kv: -kv[1]))
[('Ana', 9), ('Cy', 8), ('Bo', 7)]
Try it

Build one from two lists

Dictionaries

zip then dict.

print(dict(zip(["a", "b"], [1, 2])))
{'a': 1, 'b': 2}
Try it

Unique values

Sets & tuples

A set drops duplicates.

print(sorted(set([1, 2, 2, 3])))
[1, 2, 3]
Try it

Compare two sets

Sets & tuples

In both, in either, in one only.

a, b = {1, 2, 3}, {2, 3, 4}
print(sorted(a & b), sorted(a | b), sorted(a - b))
[2, 3] [1, 2, 3, 4] [1]
Try it

Fast membership test

Sets & tuples

in on a set is much faster than on a list.

allowed = {"admin", "editor"}
print("admin" in allowed)
True
Try it

Tuples are fixed

Sets & tuples

Use them for values that should not change.

point = (3, 4)
x, y = point
print(x, y, len(point))
3 4 2
Try it

Count with range

Loops & comprehensions

range(start, stop, step) — stop excluded.

print(list(range(5)), list(range(2, 10, 3)))
[0, 1, 2, 3, 4] [2, 5, 8]
Try it

Build a list in one line

Loops & comprehensions

The comprehension replaces append loops.

print([n * n for n in range(6)])
[0, 1, 4, 9, 16, 25]
Try it

Filter while building

Loops & comprehensions

Add an if at the end.

print([n for n in range(10) if n % 2 == 0])
[0, 2, 4, 6, 8]
Try it

Transform a dict

Loops & comprehensions

Comprehensions work for dicts too.

prices = {"a": 10, "b": 20}
print({k: v * 1.2 for k, v in prices.items()})
{'a': 12.0, 'b': 24.0}
Try it

Stop early / skip one

Loops & comprehensions

break leaves the loop, continue skips an item.

for n in range(10):
    if n == 3:
        continue
    if n > 5:
        break
    print(n, end=" ")
print()
0 1 2 4 5
Try it

Any and all

Loops & comprehensions

Ask a yes/no question about a whole list.

xs = [2, 4, 6]
print(all(n % 2 == 0 for n in xs), any(n > 5 for n in xs))
True True
Try it

Loop over a dict sorted

Loops & comprehensions

Sort the keys as you go.

d = {"b": 2, "a": 1}
for k in sorted(d):
    print(k, d[k])
a 1
b 2
Try it

if / elif / else

Conditionals

Only the first matching branch runs.

score = 72
if score >= 90:
    print("A")
elif score >= 70:
    print("B")
else:
    print("C")
B
Try it

What counts as False

Conditionals

Empty things and zero are falsy.

for v in [0, "", [], {}, None, "x"]:
    print(repr(v), bool(v))
0 False
'' False
[] False
{} False
None False
'x' True
Try it

Pick a value inline

Conditionals

The conditional expression.

n = 7
print("even" if n % 2 == 0 else "odd")
odd
Try it

Chain comparisons

Conditionals

Reads like maths and works like it.

age = 25
print(18 <= age < 65)
True
Try it

Default for an empty value

Conditionals

or falls back when the left side is falsy.

name = ""
print(name or "anonymous")
anonymous
Try it

Define and call

Functions

def, then the name, then the inputs.

def greet(name):
    return f"Hello, {name}"
print(greet("Ana"))
Hello, Ana
Try it

Default arguments

Functions

Callers can leave them out.

def power(n, exp=2):
    return n ** exp
print(power(5), power(2, 10))
25 1024
Try it

Return several values

Functions

Really a tuple you can unpack.

def stats(xs):
    return min(xs), max(xs)
lo, hi = stats([3, 9, 1])
print(lo, hi)
1 9
Try it

Any number of arguments

Functions

*args collects the extras.

def total(*nums):
    return sum(nums)
print(total(1, 2, 3, 4))
10
Try it

Keyword arguments

Functions

**kwargs collects named extras.

def show(**opts):
    return sorted(opts.items())
print(show(size=3, color="red"))
[('color', 'red'), ('size', 3)]
Try it

A tiny inline function

Functions

lambda, mostly used as a sort key.

words = ["pear", "fig", "banana"]
print(sorted(words, key=lambda w: len(w)))
['fig', 'pear', 'banana']
Try it

Document it

Functions

The docstring is what help() shows.

def area(w, h):
    """Return the area of a rectangle."""
    return w * h
print(area(3, 4), area.__doc__)
12 Return the area of a rectangle.
Try it

Handle a failure

Errors & debugging

try the risky thing, except the failure.

try:
    n = int("abc")
except ValueError:
    print("not a number")
not a number
Try it

Catch the message

Errors & debugging

as err gives you the detail.

try:
    1 / 0
except ZeroDivisionError as err:
    print("failed:", err)
failed: division by zero
Try it

Always run cleanup

Errors & debugging

finally runs whether or not it failed.

try:
    print("working")
finally:
    print("cleaned up")
working
cleaned up
Try it

Raise your own

Errors & debugging

Fail loudly with a useful message.

def withdraw(balance, amount):
    if amount > balance:
        raise ValueError("insufficient funds")
    return balance - amount
try:
    withdraw(10, 50)
except ValueError as e:
    print(e)
insufficient funds
Try it

Check a type

Errors & debugging

isinstance is the polite way to ask.

print(isinstance(3, int), isinstance("x", (int, str)))
True True
Try it

Inspect an object

Errors & debugging

type and dir when you are lost.

print(type([]).__name__, [m for m in dir([]) if m == "append"])
list ['append']
Try it

Write and read a file

Files & data

with closes the file for you.

with open("notes.txt", "w") as f:
    f.write("line one\nline two\n")
with open("notes.txt") as f:
    print(f.read().strip())
line one
line two
Try it

Read line by line

Files & data

Loop the file object directly.

with open("notes.txt", "w") as f:
    f.write("a\nb\n")
with open("notes.txt") as f:
    for line in f:
        print(line.strip())
a
b
Try it

JSON to text and back

Files & data

dumps writes, loads reads.

import json
s = json.dumps({"b": 2, "a": 1}, sort_keys=True)
print(s, json.loads(s)["a"])
{"a": 1, "b": 2} 1
Try it

Pretty-print JSON

Files & data

indent makes it human-readable.

import json
print(json.dumps({"name": "Ana", "xp": 20}, indent=2))
{
  "name": "Ana",
  "xp": 20
}
Try it

Read CSV rows

Files & data

DictReader gives you named columns.

import csv, io
rows = csv.DictReader(io.StringIO("name,xp\nAna,20\nBo,35"))
for r in rows:
    print(r["name"], r["xp"])
Ana 20
Bo 35
Try it

Today's date

Dates & randomness

date.today() and ISO formatting.

from datetime import date
d = date(2026, 3, 9)
print(d.isoformat(), d.year, d.strftime("%d %B %Y"))
2026-03-09 2026 09 March 2026
Try it

Add days

Dates & randomness

timedelta does date arithmetic.

from datetime import date, timedelta
print(date(2026, 1, 30) + timedelta(days=3))
2026-02-02
Try it

Days between dates

Dates & randomness

Subtracting gives a timedelta.

from datetime import date
print((date(2026, 3, 1) - date(2026, 1, 1)).days)
59
Try it

Text to date

Dates & randomness

strptime parses with a format string.

from datetime import datetime
print(datetime.strptime("09/03/2026", "%d/%m/%Y").date())
2026-03-09
Try it

Random, reproducibly

Dates & randomness

Seeding makes the result repeatable.

import random
random.seed(42)
print(random.randint(1, 100), random.choice("abcde"))
82 a
Try it

Find text with a pattern

Handy standard library

re for anything a simple search cannot do.

import re
print(re.findall(r"\d+", "order 66 shipped 2 items"))
['66', '2']
Try it

Replace with a pattern

Handy standard library

re.sub swaps every match.

import re
print(re.sub(r"\s+", " ", "too    many   spaces"))
too many spaces
Try it

Validate with a pattern

Handy standard library

fullmatch checks the whole string.

import re
print(bool(re.fullmatch(r"[\w.]+@[\w.]+", "a.b@example.com")))
True
Try it

Work with paths

Handy standard library

pathlib beats gluing strings together.

from pathlib import Path
p = Path("reports") / "q1.csv"
print(p, p.suffix, p.stem)
reports/q1.csv .csv q1
Try it

Default dict values

Handy standard library

defaultdict skips the setdefault dance.

from collections import defaultdict
g = defaultdict(list)
g["fruit"].append("pear")
print(dict(g))
{'fruit': ['pear']}
Try it

Pair every combination

Handy standard library

itertools for combinatorics.

from itertools import combinations
print(list(combinations("abc", 2)))
[('a', 'b'), ('a', 'c'), ('b', 'c')]
Try it

Cache a slow function

Handy standard library

lru_cache remembers past answers.

from functools import lru_cache
@lru_cache
def fib(n):
    return n if n < 2 else fib(n-1) + fib(n-2)
print(fib(30))
832040
Try it

Name your tuple fields

Handy standard library

Readable records without a class.

from collections import namedtuple
P = namedtuple("P", "x y")
p = P(3, 4)
print(p.x, p.y, p)
3 4 P(x=3, y=4)
Try it
Beyond this site

Where to go when you need more

No site teaches everything, and pretending otherwise wastes your time. These are the free resources worth knowing about, with an honest note on what each is actually for.

When you are stuck on what the code is doing

When you want more practice

When you want to go deeper

Your next ten minutes

Write Python that does something useful.

Start free. No install, no card, no passive video marathon.

Start learning free → Explore the path