Iterations and Comprehensions
# the for loop way
# --+ create an empty list
L = []
# --+ create a for loop appending the square of some items
>>> for i in range(3):
... L.append(i ** 2)
# --+ print the list
>>> print(L)
[0, 1, 4]
# the list comprehension way
>>> L = [i ** 2 for i in range(3)]
>>> print(L)
[0, 1, 4]# the lists
>>> LETTERS = ["x", "y", "z"]
>>> COLORS = ["blue", "green", "red"]
# implementing a nested for loop with a list comprehension
>>> LETTER2COLOR = ["{} <-> {}".format(i, j) for i in LETTERS for j in COLORS]
['x <-> blue',
'x <-> green',
'x <-> red',
'y <-> blue',
'y <-> green',
'y <-> red',
'z <-> blue',
'z <-> green',
'z <-> red']# the lists
>>> LETTERS = ["x", "y", "z"]
>>> COLORS = ["blue", "green", "red"]
# implementing a nested for loop with a list comprehension
>>> LETTER2COLOR = ["{} <-> {}".format(i, j) for i, j in zip(LETTERS, COLORS)]
['x <-> blue', 'y <-> green', 'z <-> red']# import the function log from math
from math import log
# the object to manipulate
>>> L1 = [0, 1, 2]
# the for loop way
# --+ the empty list
L2 = []
# --+ the for loop appending the log of some items
>>> for i in L1:
... if i > 0:
... L2.append(log(i))
... else:
... L2.append(log(i + 0.001))
# --+ print the list
>>> print(L2)
[-6.907755278982137, 0.0, 0.6931471805599453]
# the list comprehension way
# --+ the list comprehension is a one-liner!
>>> L2 = [log(i) if i > 0 else log(i + 0.001) for i in L1]
# --+ print the list
>>> print(L2)
[-6.907755278982137, 0.0, 0.6931471805599453]