18 Sep: Comprehending Python List Comprehensions
Python list comprehensions provide a short cut to the common task of performing an operation on every list member:
for i in list:
if i < 10:
j.append(i + 5)
The same code written as a list comprehension looks like this:
j = [i + 5 for i in list if i < 10]
Which has these components:
- i + 5: perform this operation on each list member
- for i in list: walk through this list with each member becoming variable i
- if i < 10: optional statement to decide whether to perform the operation