10 Common Pythonic Coding Practices and Tips
This article presents ten common Pythonic coding techniques—including variable swapping, efficient loops, enumerate, string joining, context-managed file handling, list comprehensions, decorators, appropriate list usage, sequence unpacking, and dictionary iteration—explaining why they are more readable, memory‑efficient, and idiomatic for Python developers.
Python is praised for its concise syntax, and writing code that reads like pseudocode improves readability and performance; as Harold Abelson said, "Programs must be written for people to read, and only incidentally for machines to execute."
1. Variable swapping can be done without a temporary variable:
>> a = 1
>>> b = 2
>>> a, b = b, a2. Looping over a range is more Pythonic using range (or xrange in Python 2):
for i in range(6):
print i23. Iterating with index is cleaner with enumerate :
for i, color in enumerate(colors):
print i, '-->', color4. String concatenation should prefer str.join to avoid repeated temporary strings:
print ', '.join(names)5. File handling is safest with a with statement, which automatically closes the file:
with open('data.txt') as f:
data = f.read()6. List comprehensions provide a concise one‑liner for building lists:
[i*2 for i in xrange(10)]7. Decorators can abstract caching logic from business code:
def cache(func):
saved = {}
def wrapper(url):
if url in saved:
return saved[url]
page = func(url)
saved[url] = page
return page
return wrapper
@cache
def web_lookup(url):
return urllib.urlopen(url).read()8. Choosing the right list structure improves performance; for frequent insertions/removals at both ends, collections.deque is preferable:
from collections import deque
names = deque(['raymond', 'rachel', ...])
names.popleft()
names.appendleft('mark')9. Sequence unpacking assigns multiple variables in a single statement:
name, gender, age, email = p10. Dictionary iteration is most efficient using items() (or iteritems() in Python 2) to avoid extra lookups:
for k, v in d.items():
print k, '-->', vThese Pythonic patterns make code cleaner, faster, and easier to maintain; many more exist, and exploring open‑source projects can provide further inspiration.
360 Quality & Efficiency
360 Quality & Efficiency focuses on seamlessly integrating quality and efficiency in R&D, sharing 360’s internal best practices with industry peers to foster collaboration among Chinese enterprises and drive greater efficiency value.
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.