In Python, I often work with list processing, which essentially is applying a C-like switch to each element, and doing something with it depending on the case to which it matched.
I have two approaches to how to work with such lists which create 90% of my codebase. I am looking for a possible solution to reduce this clutter and make the code more readable.
The first approach (implementation 1) is based on appending to the list in a loop. While it looks clean and readable it takes too much space for such a simple problem. The second approach (implementation 2) takes less space (probably good enough) but is significantly less readable.
Am I missing some pythonic way of handling lists?
input = [(1, 2), None, (3, 4), (2, 2), None, (7, 1)]
# implementation 1
output = []
for i in input:
if i is None:
output.append(i)
else:
[a, b] = i
if (a + b) % 2 == 0:
output.append((i[0] * 2, i[1]))
else:
output.append((i[0], i[1] * 3))
# implementation 2
output = [
(
((i[0] * 2, i[1]) if ((i[0] + i[1]) % 2 == 0) else (i[0], i[1] * 3))
if i is not None
else None
)
for i in input
]
print(output)
# [(1, 6), None, (3, 12), (4, 2), None, (14, 1)]