case — Intermediate Playground
Defines a pattern branch inside a match statement (3.10+)
Python Playground
# Type patterns with capture
def process(value):
match value:
case int(n):
print(f"Integer: {n}")
case str(s):
print(f"String: {s!r}")
case list() as items:
print(f"List with {len(items)} items")
case dict() as d:
print(f"Dict with keys: {list(d.keys())}")
case None:
print("None value")
case _:
print(f"Other: {type(value).__name__}")
for v in [42, "hello", [1, 2], {"a": 1}, None, 3.14]:
process(v)
# Starred patterns
match [1, 2, 3, 4, 5]:
case [first, *rest]:
print(f"First: {first}, rest: {rest}")
match [1]:
case [x, *rest] if not rest:
print(f"Single element: {x}")
Output
Click "Run" to execute your code
case patterns can check types and capture values simultaneously. Use * patterns for variable-length sequences.
Challenge
Try modifying the code above to explore different behaviors. Can you extend the example to handle a new use case?