Coding Python
Home›Python Coding Games›Python Code Golf

Python Code Golf

Eight tasks, one rule: make the tests pass in as few characters as you can.

Hole 1

Tests
    Your code 0 chars Par 0 Best —
    Make it shorterPython 3
    1

    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

    1. Lambda instead of def. f=lambda n:n*2 is 14 characters; the def version is 47.
    2. Comprehensions instead of append loops. Four lines of out=[], for, if, append collapse into [x for x in xs if …].
    3. Slicing. s[::-1] reverses anything indexable. No loop, no reversed(), no join.
    4. Booleans are integers. sum(c in'aeiou'for c in s) counts matches, because True is 1. (Note the space you can drop before for.)
    5. Return the comparison. return s==s[::-1] instead of an if that returns True or False — 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

    Golf on the train with the app's editor — the Coding Python app runs real Python 3 on your phone, with examples, quizzes and challenges built in.
    Get it free

    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.

    ← All Python coding games  Try Bug Squash →