01. Writing Pythonic Code
Python has its own style of writing code that emphasizes readability, simplicity, and elegance. Writing "Pythonic" code means following the conventions and idioms that experienced Python developers use.
Why Pythonic Code Matters
- Readable: Code is written once but read many times (by you and others).
- Maintainable: Follows a consistent style, easier to update or debug.
- Community Standard: Most open-source Python projects follow these practices.
PEP 8 - The Style Guide
PEP 8 is the official Python style guide. Key rules:
- Indentation: 4 spaces per level (no tabs).
- Line length: Keep lines -> 79 characters.
- Naming conventions:
- Variables & functions -> snake_case
- Classes -> CamelCase
- Constants -> ALL_CAPS
- Imports: One per line, at the top of the file.
Example:
# Good (Pythonic)
def calculate_area(radius):
return 3.14 * radius * radius
# Bad (Non-Pythonic)
def CalculateArea(R): return 3.14*R*R
Readability Counts (The Zen of Python)
Try this:
import this
You will see "The Zen of Python" - guiding principles like:
- Beautiful is better than ugly
- Simple is better than complex
- Readability counts
Pythonic code is about living by these rules.
Idiomatic Python vs Non-Pythonic Code
Example 1 - Swapping variables
# Non-Pythonic
temp = a
a = b
b = temp
# Pythonic
a, b = b, a
Example 2 - Checking membership
# Non-Pythonic
if name in ["Alice", "Bob", "Charlie"]:
...
# Pythonic (faster and clearer with set)
if name in {"Alice", "Bob", "Charlie"}:
...
Example 3 - Looping with index
# Non-Pythonic
i = 0
for value in values:
print(i, value)
i += 1
# Pythonic (use enumerate)
for i, value in enumerate(values):
print(i, value)
Practice Challenge
Rewrite this snippet in a more Pythonic way:
# Given list of numbers, print squares of even numbers
numbers = [1, 2, 3, 4, 5, 6]
squares = []
for n in numbers:
if n % 2 == 0:
squares.append(n*n)
print(squares)
Hint: Use a list comprehension.
Wrap-Up
- Pythonic code is readable, elegant, community-aligned.
- Follow PEP 8 for consistency.
- Prefer idioms (enumerate, multiple assignment, comprehensions).
- Remember: Readability counts.