Turn Your Code Into Clean, Pythonic Idioms: A Practical Guide
This article walks through what makes code Pythonic, offering clear examples and better alternatives for loops, collections, dictionaries, unpacking, context managers, decorators, and other common patterns to help developers write more readable, efficient, and idiomatic Python.
What Is Pythonic?
Pythonic code follows the language’s design philosophy: it is concise, clear, elegant, and often more efficient. The article starts with a brief translation of Tim Peters’ "Zen of Python" and explains why simply following PEP 8 is not enough to achieve true Pythonic style.
Iterating Over Ranges and Collections
for i in [0, 1, 2, 3, 4, 5]:
print i * 2A more efficient version uses range (or xrange in Python 2):
for i in range(6):
print i * 2Iterating over a collection directly with range(len(collection)) is shown, followed by the preferred enumerate approach.
Reverse and Sorted Traversal
for i in reversed(colors):
print iUsing sorted(colors, reverse=True) for ordered output is also demonstrated.
Custom Sorting
def compare_length(c1, c2):
if len(c1) < len(c2):
return -1
if len(c1) > len(c2):
return 1
return 0
print sorted(colors, key=compare_length)In Python 3 the key=len argument replaces the custom comparator.
Loop Until a Sentinel Value
blocks = []
while True:
block = f.read(32)
if block == '':
break
blocks.append(block)The article suggests using iter with a sentinel for a cleaner solution.
Finding an Element with Early Exit
def find(seq, target):
for i, value in enumerate(seq):
if value == target:
return i
return -1The for‑else construct is presented as a more Pythonic pattern.
Dictionary Traversal and Modification
for k in d:
print k
for k, v in d.items():
print k, '-->', vUsing d.items() (or iteritems() in Python 2) is recommended over separate key and value lookups.
Building Dictionaries
d = dict(zip(names, colors))For Python 3, zip is sufficient; dict(zip(...)) creates the mapping.
Counting with Dictionaries
d = {}
for color in colors:
if color not in d:
d[color] = 0
d[color] += 1Using defaultdict(int) or d.get(color, 0) + 1 provides more concise alternatives.
Grouping Items
d = {}
for name in names:
key = len(name)
if key not in d:
d[key] = []
d[key].append(name)The setdefault method and defaultdict(list) are shown as cleaner ways to group.
Improving Readability with Keyword Arguments
twitter_search('@obama', retweets=False, numtweets=20, popular=True)Keyword arguments make function calls self‑documenting.
Returning Multiple Values with namedtuple
TestResults = namedtuple('TestResults', ['failed', 'attempted'])
result = TestResults(failed=0, attempted=4)This provides readable attribute access while retaining tuple behavior.
Unpacking Sequences
fname, lname, age, email = pTuple unpacking is faster and clearer than index‑based extraction.
Simultaneous Variable Updates
x, y, dx, dy = (
x + dx * t,
y + dy * t,
influence(m, x, y, dx, dy, partial='x'),
influence(m, x, y, dx, dy, partial='y')
)Updating several related variables in a single statement avoids intermediate state bugs.
Efficiency Tips
Avoid unnecessary data movement.
Prefer linear operations over quadratic ones.
String Concatenation
print(', '.join(names))Using str.join is far more efficient than repeated += concatenation.
Updating Sequences Efficiently
from collections import deque
names = deque(['raymond', 'rachel', 'matthew', 'roger', 'betty', 'melissa', 'judith', 'charlie'])
names.popleft()
names.appendleft('mark') dequeprovides O(1) operations at both ends.
Decorators and Context Managers
Separating business logic from management concerns improves reuse. A simple caching decorator replaces manual memoization, and functools.lru_cache is mentioned for Python 3.2+.
Using with for Resources
with open('data.txt') as f:
data = f.read()Similarly, with threading.Lock(): handles lock acquisition and release automatically.
Temporary Contexts
with ignored(OSError):
os.remove('somefile.tmp')The article shows how to implement a custom ignored (or suppress) context manager.
Redirecting stdout
with open('help.txt', 'w') as f:
with redirect_stdout(f):
help(pow)Implementation of a custom redirect_stdout context manager is provided.
List Comprehensions and Generators
print sum(i**2 for i in xrange(10))Generator expressions are preferred for memory‑efficient calculations.
Overall, the article presents a series of concrete Pythonic patterns and their more efficient, readable alternatives, encouraging developers to adopt idiomatic practices throughout their code.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
