Fundamentals 10 min read

Unlock Pythonic Elegance: 20 Best Practices for Cleaner Code

This article presents twenty Pythonic idioms—ranging from swapped assignment and unpacking to using generators, context managers, and built‑in functions—each with a discouraged version and a recommended, more readable alternative, helping developers write cleaner, more efficient Python code.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Unlock Pythonic Elegance: 20 Best Practices for Cleaner Code

One of Python's biggest advantages is its concise syntax; good code should be clean, tidy, and easy to read like pseudocode. Writing Pythonic (elegant, idiomatic) code requires learning from excellent open‑source projects such as requests, Flask, and Tornado. Below are common Pythonic patterns with “not recommended” and “recommended” examples.

0. Programs must be readable before they run

“Programs must be written for people to read, and only incidentally for machines to execute.”

1. Swapped assignment

## Not recommended
temp = a
a = b
b = a

## Recommended
a, b = b, a  # creates a tuple then unpacks

2. Unpacking

## Not recommended
l = ['David', 'Pythonista', '+1-514-555-1234']
first_name = l[0]
last_name = l[1]
phone_number = l[2]

## Recommended
l = ['David', 'Pythonista', '+1-514-555-1234']
first_name, last_name, phone_number = l
# Python 3 only
first, *middle, last = another_list

3. Using the "in" operator

## Not recommended
if fruit == "apple" or fruit == "orange" or fruit == "berry":
    # multiple checks
    pass

## Recommended
if fruit in ["apple", "orange", "berry"]:
    # use in for brevity
    pass

4. String operations

## Not recommended
colors = ['red', 'blue', 'green', 'yellow']
result = ''
for s in colors:
    result += s  # creates a new string each iteration

## Recommended
colors = ['red', 'blue', 'green', 'yellow']
result = ''.join(colors)  # no extra memory allocation

5. Dictionary key list

## Not recommended
for key in my_dict.keys():
    # my_dict[key] ...
    pass

## Recommended
for key in my_dict:
    # my_dict[key] ...
    pass
# Only use my_dict.keys() when you need a static list of keys.

6. Dictionary key existence

## Not recommended
if my_dict.has_key(key):
    # ...do something with d[key]
    pass

## Recommended
if key in my_dict:
    # ...do something with d[key]
    pass

7. Using dict get and setdefault

## Not recommended
navs = {}
for (portfolio, equity, position) in data:
    if portfolio not in navs:
        navs[portfolio] = 0
    navs[portfolio] += position * prices[equity]

## Recommended
navs = {}
for (portfolio, equity, position) in data:
    # use get method
    navs[portfolio] = navs.get(portfolio, 0) + position * prices[equity]
    # or use setdefault method
    navs.setdefault(portfolio, 0)
    navs[portfolio] += position * prices[equity]

8. Truthiness checks

## Not recommended
if x == True:
    pass
if len(items) != 0:
    pass
if items != []:
    pass

## Recommended
if x:
    pass
if items:
    pass

9. Looping with index

## Not recommended
items = 'zero one two three'.split()
i = 0
for item in items:
    print i, item
    i += 1

for i in range(len(items)):
    print i, items[i]

## Recommended
items = 'zero one two three'.split()
for i, item in enumerate(items):
    print i, item

10. List comprehensions

## Not recommended
new_list = []
for item in a_list:
    if condition(item):
        new_list.append(fn(item))

## Recommended
new_list = [fn(item) for item in a_list if condition(item)]

11. Nested list comprehensions

## Not recommended
for sub_list in nested_list:
    if list_condition(sub_list):
        for item in sub_list:
            if item_condition(item):
                # do something
                pass

## Recommended
gen = (item for sl in nested_list if list_condition(sl)
               for item in sl if item_condition(item))
for item in gen:
    # do something
    pass

12. Use generators instead of lists

## Not recommended
def my_range(n):
    i = 0
    result = []
    while i < n:
        result.append(fn(i))
        i += 1
    return result  # returns a list

## Recommended
def my_range(n):
    i = 0
    while i < n:
        yield fn(i)  # use generator instead of list
        i += 1

13. Prefer imap/ifilter over map/filter

## Not recommended
reduce(rf, filter(ff, map(mf, a_list)))

## Recommended
from itertools import ifilter, imap
reduce(rf, ifilter(ff, imap(mf, a_list)))
# lazy evaluation improves memory efficiency for large data operations.

14. Use any/all functions

## Not recommended
found = False
for item in a_list:
    if condition(item):
        found = True
        break
if found:
    # do something
    pass

## Recommended
if any(condition(item) for item in a_list):
    # do something
    pass

15. Property usage

## Not recommended
class Clock(object):
    def __init__(self):
        self.__hour = 1
    def setHour(self, hour):
        if 25 > hour > 0:
            self.__hour = hour
        else:
            raise BadHourException
    def getHour(self):
        return self.__hour

## Recommended
class Clock(object):
    def __init__(self):
        self.__hour = 1
    def __setHour(self, hour):
        if 25 > hour > 0:
            self.__hour = hour
        else:
            raise BadHourException
    def __getHour(self):
        return self.__hour
    hour = property(__getHour, __setHour)

16. Use with for file handling

## Not recommended
f = open("some_file.txt")
try:
    data = f.read()
    # other file operations
finally:
    f.close()

## Recommended
with open("some_file.txt") as f:
    data = f.read()
    # other file operations

17. Use with to suppress exceptions (Python 3 only)

## Not recommended
try:
    os.remove("somefile.txt")
except OSError:
    pass

## Recommended
from contextlib import ignored  # Python 3 only
with ignored(OSError):
    os.remove("somefile.txt")

18. Use with for locking

## Not recommended
import threading
lock = threading.Lock()
lock.acquire()
try:
    # critical section
    pass
finally:
    lock.release()

## Recommended
import threading
lock = threading.Lock()
with lock:
    # critical section
    pass

19. References

Idiomatic Python: http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html

PEP 8 – Style Guide for Python Code: http://www.python.org/dev/peps/pep-0008/

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

code styleIdiomatic Python
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.