Python provides a shortcut to create lists from other lists by specyfying a formula to be applied to each element:
>>> [x*x for x in [1,2,3]] [1, 4, 9]This stands for:
l = [] for x in [1,2,3]: l.append(x*x)
Exercise 11.2. Converting a list from integers to floats | |
Given a list of integers, generate the list of the corresponding floats. |
You can filter the source list by providing a condition:
>>> [x*x for x in [1,2,3] if x < 3] [1, 4]You can create any type of elements of the new list, e.g sub-lists, strings, booleans:
>>> [ [x, x+1] for x in [1,2,3]] [[1, 2], [2, 3], [3, 4]] >>> [ "--" + str(x) + "--" for x in [1,2,3]] ['--1--', '--2--', '--3--'] >>> seq = "abcdefghji" >>> [ isAminoAcid(c) for c in seq] [True, True, True, True, True, True, True, True, False, True]You can iterate over several lists:
>>> [x + y for x in [0,1,2] for y in [0,1,2]] [0, 1, 2, 1, 2, 3, 2, 3, 4]This construct is equivalent to:
l = [] for x in [0,1,2]: for y in [0,1,2]: l.append(x+y)
Exercise 11.3. Generate the list of all possible codons | |
Generate a list of all the codons in the form (c1, c2, c3). |