List comprehensions
List comprehensions offer a more concise way to create lists. The general syntax for comprehensions is:
[result for element in collection]
For example if we wanted to create a list comprehension that doubles all the items in a list we would write:
vec = [0,1,2,3,4,5,6,7,8,9]
doubled = [x * 2 for x in vec]
print(doubled) # [0,2,4,6,8,10,12,14,16,19]
List comprehensions can also have a condition, and will skip elements that don’t match the condition.
import math
nums = [4,-24,67,100,-42.2]
roots = [math.sqrt(n) for n in nums if n >= 0]