Fundamentals 9 min read

Master Pythonic Coding: 20 Essential Tips for Clean, Efficient Code

This article presents twenty practical Pythonic techniques, contrasting discouraged patterns with recommended idioms such as tuple swapping, unpacking, using the in operator, efficient string handling, proper dictionary iteration, generator usage, context managers, and more, each illustrated with clear before‑and‑after code examples.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Master Pythonic Coding: 20 Essential Tips for Clean, Efficient Code

One of Python's greatest strengths is its concise syntax; clean, readable code often resembles pseudocode. To write Pythonic (elegant, idiomatic, tidy) code, study exemplary projects on GitHub such as requests, flask, and tornado. Below are common Pythonic patterns.

0. Write code for people first, then for machines

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

1. Tuple swapping

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

# Recommended
a, b = b, a  # creates a tuple and unpacks it

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. Use the in operator

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

# Recommended
if fruit in ["apple", "orange", "berry"]:
    # using <code>in</code> is more concise

4. Efficient string concatenation

# 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. Iterate over dictionary keys directly

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

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

6. Check key existence with in

# Not recommended
if my_dict.has_key(key):
    # do something

# Recommended
if key in my_dict:
    # do something

7. Use dict.get or setdefault for defaults

# 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:
    # using get
    navs[portfolio] = navs.get(portfolio, 0) + position * prices[equity]
    # or using setdefault
    navs.setdefault(portfolio, 0)
    navs[portfolio] += position * prices[equity]

8. Use any / all instead of manual flags

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

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

9. Iterate with enumerate for index

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

# 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

# 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

12. Prefer generators over building 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
        i += 1

13. Use imap / ifilter for lazy evaluation

# 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

14. Use with for file handling

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

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

15. Use with to suppress exceptions (Python 3)

# 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")

16. Use with for locks

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

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

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 stylepythonic
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.