Idiomatic Python
Idiomatic Python#
Here are a few things you can watch out for to improve how obvious and fast your code is. Often, people coming from other programming languages don’t take advantage of the Python way.
Looping#
colours = ['red', 'green', 'blue', 'orange']
for colour in colours:
print(colour)
# Not
for i in range(len(colours)):
print(colours[i])
Reversing a Loop#
for colour in reversed(colours):
print(colour)
# Not
for i in range(len(colours) - 1, -1, -1):
print(colours[i])
Using Indices#
Use enumerate
for i, colour in enumerate(colours):
print(i, '-->', colour)
Looping over 2 collections#
Use zip
colours = ['red', 'green', 'blue', 'orange']
names = ['raymond', 'rachel', 'matthew']
for name, colour in zip(names, colours):
print(name, colour)
In Python 3 zip is lazy already, so there is nothing to swap in. itertools.izip
is the Python 2 name and only belongs in old code.