Pythonic code
Python has its own set of idioms and patterns that build on its dynamic typing model and design philosophy from the Zen of Python. The code that uses these idioms and patterns is considered Pythonic code. This code is correct, readable, and aligned with the intended use of the language.
In practice, writing Pythonic code means leveraging the language’s strengths instead of fighting against them. Here are some best practices that you can apply to make your code more Pythonic:
- Embrace EAFP (Easier to Ask Forgiveness than Permission). Rather than checking every possible precondition up front with an LBYL (Look Before You Leap) style, just try the operation and handle the exception if the code fails. This practice reduces the overhead of repetitive checks, avoids missing checks, prevents certain race conditions, and aligns with Python’s principle: errors should never pass silently.
- Favor duck typing over strict type checking. Instead of constantly checking types with
isinstance()before performing an action, rely on behaviors. If an object behaves like the expected type, then you just use it. This is known as duck typing and can make your code more flexible, extensible, and less tightly coupled to specific data types. - Use context managers to manage resources. Instead of manually running setup and teardown stages in resource management, use context managers and the
withstatement. They ensure that resources, such as files, locks, and network connections, are cleaned up reliably, even in the event of errors. - Use comprehensions and generator expressions for data transformation. Comprehensions and generator expressions offer a concise, readable, efficient, and Pythonic way to transform or filter data, compared to manual loops.
- Lean on common Python idioms and built-ins. Common idioms, such as
if __name__ == "__main__"and iteration patterns, features like unpacking, f-strings, and built-ins likeenumerate(),zip(),any()orall(), can make code more Pythonic.
To see some of these practices in action, consider the following function, which totals the lengths of a sequence of strings:
🔴 Avoid this:
>>> def total_length(items):
... result = 0
... if isinstance(items, list):
... for i in range(len(items)):
... result += len(items[i])
... return result
...
>>> total_length(["Hello", "Pythonista!"])
16
This function works, but it’s tightly coupled to lists, uses a non-Pythonic iteration pattern, overuses indexing, and relies on isinstance() checks, ignoring other iterable types. It’s also verbose and difficult to understand.
Here’s a more Pythonic version that relies on duck typing, built-ins, and a comprehension:
✅ Favor this:
>>> def total_length(items):
... return sum(len(item) for item in items)
...
>>> total_length(["Hello", "Pythonista!"])
16
Now, your function works with any iterable of strings, such as lists, tuples, or custom sequence types. It’s shorter, clearer, and focuses on its high-level intent: * sum the lengths of all input strings*.
Related Resources
Tutorial
LBYL vs EAFP: Preventing or Handling Errors in Python
Choose your Python coding style: look before you leap (LBYL) vs easier to ask forgiveness than permission (EAFP). See clear pros, cons, and examples.
For additional information on related topics, take a look at the following resources:
- Duck Typing in Python: Writing Flexible and Decoupled Code (Tutorial)
- Python's with Statement: Manage External Resources Safely (Tutorial)
- What Does if __name__ == "__main__" Do in Python? (Tutorial)
- Python's Built-in Functions: A Complete Exploration (Tutorial)
- Python for Loops: The Pythonic Way (Tutorial)
- Python while Loops: Repeating Tasks Conditionally (Tutorial)
- Python enumerate(): Simplify Loops That Need Counters (Tutorial)
- Using the Python zip() Function for Parallel Iteration (Tutorial)
- How to Use Generators and yield in Python (Tutorial)
- Python's F-String for String Interpolation and Formatting (Tutorial)
- When to Use a List Comprehension in Python (Tutorial)
- Python Set Comprehensions: How and When to Use Them (Tutorial)
- Python Dictionary Comprehensions: How and When to Use Them (Tutorial)
- The Walrus Operator: Python's Assignment Expressions (Tutorial)
- Python's all(): Check Your Iterables for Truthiness (Tutorial)
- Python's sum(): The Pythonic Way to Sum Values (Tutorial)
- Iterators and Iterables in Python: Run Efficient Iterations (Tutorial)
- Using the len() Function in Python (Tutorial)
- Handling or Preventing Errors in Python: LBYL vs EAFP (Course)
- Getting to Know Duck Typing in Python (Course)
- Context Managers and Using Python's with Statement (Course)
- Context Managers and Python's with Statement (Quiz)
- What Does if __name__ == "__main__" Mean in Python? (Course)
- Python Name-Main Idiom (Quiz)
- Python's Built-in Functions: A Complete Exploration (Quiz)
- For Loops in Python (Definite Iteration) (Course)
- Python for Loops: The Pythonic Way (Quiz)
- Mastering While Loops (Course)
- Python while Loops: Repeating Tasks Conditionally (Quiz)
- Looping With Python enumerate() (Course)
- Python's enumerate() (Quiz)
- Parallel Iteration With Python's zip() Function (Course)
- Python Generators 101 (Course)
- How to Use Generators and yield in Python (Quiz)
- Python 3's F-Strings: An Improved String Formatting Syntax (Course)
- Python F-Strings (Quiz)
- Understanding Python List Comprehensions (Course)
- When to Use a List Comprehension in Python (Quiz)
- Python Set Comprehensions: How and When to Use Them (Quiz)
- Building Dictionary Comprehensions in Python (Course)
- Python Dictionary Comprehensions: How and When to Use Them (Quiz)
- Python Assignment Expressions and Using the Walrus Operator (Course)
- The Walrus Operator: Python's Assignment Expressions (Quiz)
- Summing Values the Pythonic Way With sum() (Course)
- Efficient Iterations With Python Iterators and Iterables (Course)
- Iterators and Iterables in Python: Run Efficient Iterations (Quiz)
- Python's len() Function (Course)
By Leodanis Pozo Ramos • Updated Feb. 2, 2026