Python list comprehensions
There is a very useful Python notation called list comprehension that can be used for creating and manipulating lists. The official Python tutorial has a short section on list comprehensions, but as described in the tutorial the same results can be obtained using for-loops. So, I can understand that programmers new to Python either skips this section, or just overlooks the usefulness of the notation.
I recently came across a post on Scott Johnson's Fuzzyblog on the topic of subtracting arrays of strings. In the post Scott seeks to reproduce Ruby's array subtraction in Python.
The following lists are given
all_experts = ['expert_1.py', 'expert_2.py', 'expert_3.py', 'expert_4.py']
experts_so_far = ['expert_1.py']
Now, calculate the list remaining_experts
that contains the entries in all_experts
that are not in experts_so_far
.
The most concise way to do this in Python is to use a list comprehension:
remaining_experts = [e for e in all_experts if e not in experts_so_far]
The alternative version, unwrapping the for-loop, is more elaborate (and much slower):
remaining_experts = []
for e in all_experts:
if e not in experts_so_far:
remaining_experts.append(e)
Clearly, there are advantages gained in readability and compactness by using list comprehensions, also for new Python programmers.