Python List Comprehensions Vs A Traditional Approach

December, 2022

This is how I'm helping wrap my brain around python list comprehensions. It's a comparison of a list comprehension and the way I would have coded it without the comprehension. Each example starts with a list that has some words and some empty string in them. The functionality is to create a new list without the empty strings

Traditional Approach


samples = ['alfa', '', 'bravo', 'charlie', '']

results = []

for sample in samples:
    if sample != '':
        results.append(sample)

print(results)


['alfa', 'bravo', 'charlie']

List Comprehension Approach


samples = ['alfa', '', 'bravo', 'charlie', '']

results = [sample for sample in samples if sample != '']

print(results)

['alfa', 'bravo', 'charlie']

Notes

The comprehension can also be split on multiple lines which I sometimes do to help me parse what's happening. I expect that as I get better at them, I'll need to do that less


results = [
    sample for sample in samples
    if sample != ''
]

Also, "Traditional approach" might not be the best term, but I couldn't come up with anything better