Fundamentals 15 min read

Master Pythonic Loops: Elegant Techniques for Cleaner Code

The article presents Raymond Hettinger's PyCon 2013 notes on writing Pythonic code, covering loops, collections, dictionary handling, performance tips, context managers, and best practices, with examples and improved alternatives to help developers write clear, efficient, and idiomatic Python.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Master Pythonic Loops: Elegant Techniques for Cleaner Code

This note, based on Raymond Hettinger's 2013 PyCon talk, shows how to write Pythonic code that is concise, readable, and efficient.

Looping over a range

Use range for Python 3 (or xrange for Python 2) to avoid creating an intermediate list.

for i in range(6):
    print(i * 2)

Iterating over a collection

Iterate directly over the collection instead of using indices.

colors = ['red', 'green', 'blue']
for i in range(len(colors)):
    print(colors[i])
# Better
for color in colors:
    print(color)

Enumerate and zip

When you need both index and value, use enumerate. To iterate two sequences in parallel, use zip (or izip in Python 2).

for i, color in enumerate(colors):
    print(i, '-->', color)

names = ['raymond', 'rachel']
for name, color in zip(names, colors):
    print(name, '-->', color)

Dictionary iteration

Iterate over keys with for k in d or d.keys(). For key‑value pairs, use d.items() (or iteritems() in Python 2).

d = {'matthew': 'blue', 'rachel': 'green'}
for k, v in d.items():
    print(k, '-->', v)

Counting with dictionaries

Simple counting can be done with a normal dict, but defaultdict(int) or collections.Counter is more idiomatic.

from collections import defaultdict
counts = defaultdict(int)
for color in colors:
    counts[color] += 1

Grouping items

Use defaultdict(list) or setdefault to group values by a computed key.

from collections import defaultdict
by_len = defaultdict(list)
for name in names:
    by_len[len(name)].append(name)

ChainMap for configuration merging

Combine defaults, environment variables, and command‑line arguments without copying data.

from collections import ChainMap
config = ChainMap(cli_args, os.environ, defaults)

Readability tricks

Prefer keyword arguments and namedtuple for multiple return values.

from collections import namedtuple
Result = namedtuple('Result', ['failed', 'attempted'])
res = Result(failed=0, attempted=4)

Simultaneous variable updates

Swap or update several variables in one statement.

x, y, dx, dy = x + dx*t, y + dy*t, influence(..., partial='x'), influence(..., partial='y')

Efficient sequence updates

When you need fast insert/remove at both ends, use collections.deque instead of a list.

from collections import deque
names = deque(['raymond', 'rachel'])
names.appendleft('mark')
names.popleft()

Decorators and context managers

Separate business logic from management concerns with decorators (e.g., @cache) and the with statement.

@cache
def web_lookup(url):
    return urllib.urlopen(url).read()

Use built‑in context managers such as redirect_stdout or create your own with contextlib.contextmanager.

from contextlib import redirect_stdout
with open('help.txt', 'w') as f, redirect_stdout(f):
    help(pow)

File handling and locks

Prefer the with open(...) pattern for automatic closing, and acquire locks with with lock: instead of manual acquire / release.

with open('data.txt') as f:
    data = f.read()

with lock:
    critical_section()

These idioms collectively make Python code more Pythonic, easier to read, and often faster.

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.

PythonCollectionsLoopscontext managersidiomatic
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.