Concise Python idioms: comparisons, unpacking and comprehensions
A short tour of Python idioms (unpacking, comprehensions, zip, enumerate, f-strings, itertools) that replace longer loops.
A few common Python shortcuts, shown next to the classic way of writing the same thing. The examples are rewritten; for a fuller list, see the gto76 Python cheatsheet.
Conditional expression in a return
Instead of a full if / else:
def compare(a, b):
return a if a > b else b
Multiple assignment
arr_list = [1, 4, 7]
a, b, c = arr_list
a is 1, b is 4 and c is 7.
List comprehension
Instead of a loop with append:
arr_list = [1, 4, 7]
result = [x * 2 for x in arr_list]
Result: [2, 8, 14]
Compare two lists element by element with zip
a = [1, 5, 8]
b = [3, 4, 7]
result = [min(pair) for pair in zip(a, b)]
Result: [1, 4, 7]
Sort a list of lists on the second element
arr_list = [[1, 4], [3, 3], [5, 7]]
arr_list.sort(key=lambda x: x[1])
Result: [[3, 3], [1, 4], [5, 7]]
Filter, then transform
arr_list = [-1, 1, 3, 5]
result = list(map(lambda x: x**2, filter(lambda x: x > 0, arr_list)))
Result: [1, 9, 25]. A list comprehension gives the same result: [x**2 for x in arr_list if x > 0].
Check that the elements are unique
A set removes duplicates: if the length changes, the list contains duplicates.
arr_list = [1, 4, 4, 6, 9]
len(arr_list) == len(set(arr_list))
Result: False
String formatting
Before Python 3.6:
a, b, c = 1, 5, 9
print('a is {}; b is {}; c is {}'.format(a, b, c))
Python 3.6 and later (f-strings):
print(f'a is {a}; b is {b}; c is {c}')
Loop with an index: enumerate
Instead of range(len(...)):
arr_list = [1, 5, 9]
for i, j in enumerate(arr_list):
print(f'Index: {i}; Value: {j}')
Unpacking with a star
arr_list = [1, 4, 6, 8, 10, 11]
a, *b, c = arr_list
a is 1, b is [4, 6, 8, 10] and c is 11.
Combinations and permutations
The itertools module is required.
import itertools
str_list = ['A', 'C', 'F']
list(itertools.combinations(str_list, 2))
Result: [('A', 'C'), ('A', 'F'), ('C', 'F')]
list(itertools.permutations(str_list, 2))
Result: [('A', 'C'), ('A', 'F'), ('C', 'A'), ('C', 'F'), ('F', 'A'), ('F', 'C')]