Unlock Pythonic Iteration: Clean, Efficient Ways to Loop Over Collections
This guide reveals Pythonic techniques for iterating over ranges, lists, dictionaries, and multiple collections, showing how to write concise, readable loops, use built‑in functions like zip and enumerate, and apply advanced tools such as defaultdict, ChainMap, and context managers for cleaner and faster code.
Python’s community emphasizes writing code that is not only functional but also clear and elegant. Below are idiomatic patterns for common looping tasks and related utilities.
Iterating Over a Range
for i in range(6):
print(i * 2)For large ranges, xrange (Python 2) or the built‑in range (Python 3) provides an iterator that saves memory.
Iterating Over a Collection
colors = ['red', 'green', 'blue', 'yellow']
for i in range(len(colors)):
print(colors[i])A more Pythonic form uses enumerate:
for i, color in enumerate(colors):
print(i, '-->', color)Reverse Iteration
for i in range(len(colors)-1, -1, -1):
print(colors[i])Or simply reversed(colors) in Python 3.
Iterating Over Two Collections
names = ['raymond', 'rachel', 'matthew']
colors = ['red', 'green', 'blue']
for name, color in zip(names, colors):
print(name, '-->', color)Use itertools.izip in Python 2 for better memory usage.
Dictionary Keys and Items
d = {'matthew': 'blue', 'rachel': 'green', 'raymond': 'red'}
for k in d:
print(k)
for k, v in d.items():
print(k, '-->', v)In Python 2, d.iteritems() returns an iterator.
Building Dictionaries
names = ['raymond', 'rachel', 'matthew']
colors = ['red', 'green', 'blue']
d = dict(zip(names, colors))Counting with Dictionaries
d = {}
for color in colors:
d[color] = d.get(color, 0) + 1
# Result: {'red': 1, 'green': 1, 'blue': 1}For more convenience, collections.defaultdict(int) can be used.
Grouping Items
d = {}
for name in names:
key = len(name)
d.setdefault(key, []).append(name)
# Example: {5: ['raymond'], 6: ['rachel', 'matthew']}Configuration with ChainMap
from collections import ChainMap
config = ChainMap(cli_args, os.environ, defaults)This merges dictionaries without copying.
Readability Enhancements
Prefer keyword arguments over positional ones for clarity, e.g.,
twitter_search('@obama', retweets=False, numtweets=20, popular=True).
namedtuple for Structured Results
from collections import namedtuple
TestResults = namedtuple('TestResults', ['failed', 'attempted'])
result = TestResults(failed=0, attempted=4)Unpacking Sequences
fname, lname, age, email = pSimultaneous Variable Updates
x, y, dx, dy = (
x + dx * t,
y + dy * t,
influence(m, x, y, dx, dy, 'x'),
influence(m, x, y, dx, dy, 'y')
)Performance Tips
Avoid unnecessary data movement.
Prefer linear operations over quadratic ones.
String Joining
print(', '.join(names))Efficient Sequence Updates
Use collections.deque for fast pops and appends at both ends.
Decorators and Context Managers
@cache
def web_lookup(url):
return urllib.urlopen(url).read()In Python 3.2+, functools.lru_cache provides caching.
Local Decimal Context
from decimal import localcontext, Decimal, getcontext
with localcontext() as ctx:
ctx.prec = 50
print(Decimal(355) / Decimal(113))File Handling with with
with open('data.txt') as f:
data = f.read()Locking with with
lock = threading.Lock()
with lock:
print('Critical section')Suppressing Exceptions
from contextlib import suppress
with suppress(OSError):
os.remove('somefile.tmp')Redirecting stdout
from contextlib import redirect_stdout
with open('help.txt', 'w') as f, redirect_stdout(f):
help(pow)List Comprehensions vs Generators
print(sum(i**2 for i in range(10)))This generator expression computes the sum without building an intermediate list.
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.
