Let's see how list comprehensions work by comparing them to a for
loop that performs a similar operation. Enter the following code in a text file or an input cell in a worksheet:
list1 = [' a ', ' b ', 'c '] list1_stripped = [] for s in list1: list1_stripped.append(s.strip()) print(list1_stripped) list1_stripped_2 = [s.strip() for s in list1] print(list1_stripped_2) list2 = [] for val in srange(0.0, 10.0, 1.0): if val % 2 == 0: list2.append(numerical_approx(val**2, digits=3)) print(list2) list3 = [numerical_approx(val**2, digits=3) for val in srange(0.0, 10.0, 1.0) if val % 2 == 0] print(list3)
Run the example. You should get: