Python Code Golf
Eight tasks, one rule: make the tests pass in as few characters as you can.
How to play
Each hole starts with a working solution written the long way. It already passes the tests — your job is to make it shorter without breaking it. Press Run tests whenever you want; the character counter and the bar update as you type, and the bar turns green once you are at or under par.
The five techniques that win most holes
- Lambda instead of def.
f=lambda n:n*2is 14 characters; thedefversion is 47. - Comprehensions instead of append loops. Four lines of
out=[],for,if,appendcollapse into[x for x in xs if …]. - Slicing.
s[::-1]reverses anything indexable. No loop, noreversed(), no join. - Booleans are integers.
sum(c in'aeiou'for c in s)counts matches, becauseTrueis 1. (Note the space you can drop beforefor.) - Return the comparison.
return s==s[::-1]instead of anifthat returnsTrueorFalse— a pattern worth using in real code too.
A warning worth printing on the wall
Golfed code is deliberately unreadable, and the habits that win here will lose you a code review. 'Fizz'*(n%3<1)
is clever and nobody wants to maintain it. Treat this as a vocabulary exercise: the point is to know that comprehensions,
slicing and truthiness exist and exactly how they behave, so that in real code you reach for the clear version of the same idea
instead of writing fifteen lines by hand.
Where these tricks come from
- Lists and comprehensions — the single biggest source of saved characters.
- Strings and slicing —
[::-1],[1:],in. - Functions and lambdas — when a lambda is appropriate and when it is not.
- The standard library —
sum,any,all,dict.fromkeys.
Frequently asked questions
What is code golf?
A programming game where the goal is the shortest possible solution. The 'par' for each hole is our own best effort; beating it is genuinely satisfying and teaches you the compact parts of the language.
How is my score counted?
Every character in the editor counts, including spaces and newlines, with trailing whitespace trimmed. The character counter updates as you type.
Does short code mean good code?
Not in production — clarity beats brevity every time at work. Golf is a training exercise: it forces you to learn comprehensions, slicing, truthiness and the built-ins, and that knowledge makes your ordinary code better too.
Are the tests real?
Yes. Your code and the assertions run on CPython compiled to WebAssembly in your browser, so a pass means it genuinely works.
What tricks should I learn first?
Lambdas instead of def, list comprehensions instead of append loops, slicing with s[::-1], summing booleans to count matches, and dict.fromkeys to deduplicate while keeping order. Every hole here is built around one of them.