Skip to content
Tutorials Center
My learning

Topics

Lesson 93 of 149 ยท Beyond the Basics

Writing Pythonic Code

Write Python the way experienced developers do. Learn PEP 8 style, the Zen of Python, everyday idioms like enumerate and unpacking, and the anti-patterns to avoid.

Python lets you solve most problems in several ways, and code that works is not always code that reads well. Experienced Python developers call clear, idiomatic code Pythonic: it uses the language's built-in tools the way they were designed, so the intent jumps off the page.

This lesson collects the habits that make the biggest difference. You'll meet the style guide every Python project follows (PEP 8), the short philosophy behind the language (the Zen of Python), a set of everyday idioms with before-and-after examples, and the anti-patterns that give away code written by someone fighting the language instead of using it.

The Zen of Python

Python hides a small poem inside itself. It's a list of guiding principles written by one of the language's early core developers, and it has shipped with Python for more than twenty years. Run this:

Python import this

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Some lines are jokes, but several are worth remembering as you write code: prefer explicit to implicit, simple to complex, and flat to nested; readability counts; errors should never pass silently. Nearly every idiom in this lesson is one of those principles applied to a specific situation.

PEP 8: the style guide

PEP 8 is the official style guide for Python code. "PEP" stands for Python Enhancement Proposal, the documents in which Python's design is discussed. Following PEP 8 means any Python developer can open your file and feel at home. The rules you'll use every day:

Topic Convention
Indentation 4 spaces per level, never tabs
Line length at most 79 characters (many teams allow up to 88 or 99)
Variables, functions lower_snake_case: total_price, load_users()
Classes CapWords: ShoppingCart, HttpClient
Constants UPPER_SNAKE_CASE: MAX_RETRIES = 3
"Internal" names a leading underscore: _cache, _parse_row()
Blank lines 2 around top-level functions and classes, 1 between methods
Spaces around = and operators (x = a + b), not inside brackets, none around = in keyword arguments (f(sep=", "))
Imports at the top, one per line, grouped: standard library, third-party, your own

You don't have to memorize every rule. Tools do the work for you: Ruff and Black reformat code automatically, and linters such as Ruff or flake8 point out style problems and likely bugs. Run one in your editor, set up as described in Virtual Environments and Project Setup, and style stops being something you think about.

Consistency beats rules. PEP 8 itself says to follow a project's existing style when it differs. When you join a codebase, match what's already there.

Looping like a Pythonista

Python's for loop walks over the items of a collection directly. You almost never need an index counter. Compare the C-style versions with the Pythonic ones:

Python Loops without index bookkeeping

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

enumerate() and zip() remove a whole category of off-by-one bugs, because there is no index to get wrong.

Building collections

When a loop exists only to build a new list, dictionary or set, a comprehension says the same thing in one line. Built-ins such as sum(), any(), all(), min() and max() replace many hand-written loops entirely:

Python Comprehensions and built-ins

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Comprehensions are for building things. If a loop's job is a side effect, like printing or saving, a normal for loop is clearer. And if a comprehension needs three for clauses and two conditions, it's time to go back to a loop.

Truthiness, None and comparisons

Python treats empty collections, 0, "" and None as false (see Booleans and Truthiness). Use that instead of comparing lengths. A few related habits:

  • Write if items: rather than if len(items) > 0:, and if not name: rather than if name == "":.
  • Compare with None using is: if result is None:, never == None. (Here's why.)
  • Never write if flag == True:. Just write if flag:.
  • Use chained comparisons: if 0 <= age < 130:.
  • Check types with isinstance(x, int), not type(x) == int, so subclasses work too.
  • Test membership with in: if color in ("red", "green", "blue"):.

Unpacking, swapping and the throwaway name

Unpacking assigns several names at once and makes code self-describing. An underscore _ is the conventional name for a value you have to accept but don't care about:

Python Unpacking idioms

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Strings and dictionaries

A few everyday idioms that come up in almost every program:

  • Build strings with f-strings (see String Formatting) rather than + and str(): f"{name} is {age}".
  • Join pieces with str.join() instead of += in a loop. ", ".join(words) is clearer and much faster for long lists.
  • Read dictionary values with .get() when a key might be missing: config.get("theme", "light").
  • Count and group with the right tool: collections.Counter and defaultdict (see collections) replace "if key not in dict" boilerplate.
  • Merge dictionaries with |: settings = defaults | user_choices.

EAFP: ask forgiveness, not permission

Many languages encourage you to check that something will work before you try it ("Look Before You Leap", LBYL). Python culture often prefers the opposite: just try it and handle the failure ("Easier to Ask Forgiveness than Permission", EAFP). With try/except the happy path stays clean, and you avoid race conditions where the situation changes between the check and the action:

Python LBYL vs EAFP

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice that the LBYL check isdigit() wrongly rejects "-3" and " 5 ", which int() handles fine. Checks that try to predict whether an operation will succeed are easy to get subtly wrong; letting the operation itself decide is often more accurate.

Common anti-patterns

These patterns work, but they're red flags in code review. Run the example to see why the first one is genuinely dangerous:

Python Two classic traps

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

More to avoid:

  • Bare except: or except Exception: pass. It hides real bugs, even typos. Catch the specific exceptions you expect, and never silence errors without a reason.
  • from module import *. You can no longer tell where a name came from, and names collide silently. Import the module or the specific names.
  • Opening files without with. A context manager closes the file even when an error happens.
  • Getters and setters for everything. Use plain attributes, and switch to a property only when you need logic.
  • Classes that should be functions. A class with one method and an __init__ is often just a function in disguise.
  • Clever one-liners. If you need a comment to explain a line, split it into named steps.

Pythonic doesn't mean short. The goal is clarity. A three-line loop with good names beats a dense one-liner that the reader has to decode.

Names, docstrings and type hints

Finally, the habits that make code readable months later:

  • Choose names that say what a value is: unpaid_invoices, not lst2. Functions are verbs (send_reminder()), booleans read like questions (is_active, has_discount).
  • Give public functions a docstring explaining what they do, what they take and what they return.
  • Add type hints to function signatures. They document intent and let editors catch mistakes early.
  • Keep functions small and focused on one job. If you can't name a function without "and", it probably does two things.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the Pythonic way to loop over a list when you also need each item's position?

    enumerate() yields (index, item) pairs, with no manual counter and no off-by-one risk. index() is slow and wrong for duplicate items.
  2. 2. How should you check whether result is None?

    None is a single object, so compare identity with is. not result would also be true for 0, empty strings and empty lists.
  3. 3. Why is def add(item, items=[]): a problem?

    Default values are evaluated once, when the function is defined. Every call that uses the default appends to the same list. Use None and create the list inside.
  4. 4. What does EAFP mean in practice?

    "Easier to Ask Forgiveness than Permission": attempt the operation inside try and catch the specific error you expect.
  5. 5. Which name follows PEP 8 for a class?

    Classes use CapWords. lower_snake_case is for functions and variables, and UPPER_SNAKE_CASE is for constants.

Summary

  • Pythonic code uses the language's built-in tools so its intent is obvious; import this shows the guiding principles.
  • Follow PEP 8 (4-space indents, snake_case functions, CapWords classes) and let a formatter like Ruff or Black enforce it.
  • Loop over items directly, with enumerate() and zip() when needed; build collections with comprehensions and sum/any/all/max.
  • Use truthiness, is None, chained comparisons, unpacking, f-strings, join() and dict.get().
  • Prefer EAFP with specific exceptions; avoid mutable defaults, bare except, import * and shadowing built-ins.
  • Clear names, docstrings and type hints matter more than clever one-liners.

Next: Measuring and Improving Performance.