List Comprehensions
- A list comprehension is a compact way to write an expression that expands to a whole list.
- List comprehension can almost substitute for the lambda function especially as map(), filter() and reduce().
Examples
# compute a list of their squares of elements in a list
nums = [1, 2, 3, 4]
squares = [ n * n for n in nums ] ## [1, 4, 9, 16]
>>> port_numbers = [22,25,80,139,443]
>>> [k for k in port_numbers]
[22, 25, 80, 139, 443]
>>>
>>> numbers = [2,4,6,8]
>>> [k*2 for k in numbers]
[4, 8, 12, 16]
- You can add an if test to the right of the for-loop to narrow the result. The if test is evaluated for each element, including only the elements where the test is true.
>>> port_numbers = [22,25,80,139,443,8080,9999,55555]
>>>
>>> [k for k in port_numbers if k<1023]
[22, 25, 80, 139, 443]
Using List comprehensions
List comprehensions are extremely powerful and compact.
You might be tempted to use them a lot to optimize your code but readbility matters.
Use comprehensions for optimizing one or two lines but nothing more than that.