Skip to main content

Small syntax that shows up everywhere: ternary, swap & match

Level 1: Level 1: Foundationseasy11 minconditionalscontrol-flowunpackingtuples

Write a conditional expression, swap and unpack tuples, and branch with match/case.

Three shorthands you will read before you write

Nothing in this lesson is a new idea. Each piece is a shorter way to say something you can already say with if. That is exactly why it matters: all three turn up in the first real codebase you open, and code you cannot read is code you cannot safely change. The judgement worth learning is when the short form is genuinely clearer and when it is merely shorter.

A conditional expression: a if cond else b

An if block is a statement: it does something. a if cond else b is an expression: it evaluates to a value, so it fits where a statement cannot go, such as inside a return, an f-string, or a list.

status = "adult" if age >= 18 else "minor"

# exactly the same decision, written as a statement
if age >= 18:
    status = "adult"
else:
    status = "minor"

Read it from the middle outwards: check the condition, then take the value on the left or the one on the right. Reach for it when both branches produce a value for the same thing and the whole line still reads comfortably. Stop the moment you want three outcomes: "a" if x else "b" if y else "c" is legal, is unreadable, and is a reliable way to lose a code review.

Check yourself
You write value = fetch() if cached else compute(), where both functions are slow. How many of them actually run?

Swapping, and tuple unpacking underneath it

a, b = b, a

One line, no temporary variable. It works because of the order Python does things: the right-hand side is evaluated first into the tuple (b, a), and only then is that tuple unpacked into the names on the left. Nothing is ever half-assigned in between.

Swapping is just the most famous use of tuple unpacking, which works on any sequence of the right length:

point = (3, 4)
x, y = point            # x is 3, y is 4

first, second = "ab"    # any sequence, not just tuples

The counts have to match. x, y = (1, 2, 3) raises ValueError: too many values to unpack (expected 2) and x, y, z = (1, 2) raises ValueError: not enough values to unpack. That strictness is a feature: when the shape of your data changes, you hear about it immediately instead of silently binding the wrong piece to the wrong name.

Check yourself
a is 1 and b is 2. After the single line a, b = b, a, what does a hold?

match / case

Python 3.10 added match. It takes one value and tries case patterns top to bottom, running the first that matches:

match code:
    case 200:
        return "ok"
    case 301 | 302:
        return "redirect"
    case 404:
        return "not found"
    case _:
        return "unknown"

| means "either of these". case _ is the wildcard that matches anything, playing the part else plays in an if chain. There is no fall-through: exactly one body runs and you never write break.

Used only that way it is a tidier elif chain, and an elif chain would have been fine. match earns its keep when the patterns describe shape rather than equality:

match event:
    case {"type": "click", "x": x, "y": y}:
        return f"click at {x},{y}"
    case {"type": "key", "key": key}:
        return f"key {key}"
    case _:
        return "unknown event"

Each case checks the structure of the data and binds the pieces it names in the same step. Written with if, that is a pile of key checks and lookups repeated in every branch. This is why the feature is called structural pattern matching and not "switch".

Check yourself
OK = 200 sits at the top of your file. Inside a match you write case OK:, then case 404:, then case _:. What happens?

The shape of the exercises

Apply is the swap: return two values in ascending order, exchanging them in one line when they arrive backwards. Practice is a match: turn an HTTP status code into a label, with | for the two redirect codes and case _ for everything else.

Interview nuance: nobody asks you to recite match syntax, but everybody reads your code while you write it. A conditional expression inside a return reads as fluent, and a nested one reads as showing off. The tuple swap is the small tell that you think about what Python evaluates first rather than about assignment statements in sequence. And knowing that match binds shape rather than just comparing equality is what keeps you from describing it as "Python finally got a switch statement", which is the answer that says you read the release notes and never used it.

Worked example (Python)
a, b = 9, 4
a, b = b, a
print(a, b)                          # 4 9

age = 20
print("adult" if age >= 18 else "minor")

def label(code):
    match code:
        case 200:
            return "ok"
        case 301 | 302:
            return "redirect"
        case _:
            return "unknown"

print(label(302))                    # redirect

Apply

Your turn

The task this lesson builds to.

Implement ascending(a, b): return the two values as a list in order, [smaller, larger].

Do it with a swap. When a is greater than b, exchange them in one line with a, b = b, a, then return [a, b]. Equal values come back unchanged.

3 hints and 4 automated checks are waiting in the workspace.

Practice

Make it stick

A second problem on the same idea, so it survives past today.

Your status dashboard shows raw HTTP codes and on-call keeps having to look them up, so you are adding the human labels.

Implement status_label(code): return "ok" for 200, "redirect" for both 301 and 302, "not found" for 404, and "unknown" for anything else. Write it with match/case, using | for the two redirect codes and case _ for the catch-all.

3 hints and 4 automated checks are waiting in the workspace.