Chapter 5. Data Structures 34 Python Tutorial, Release 3.9.5 (continued from previous page) Note how the order of the for and if statements is the same in both these snippets. If the expression is a tuple (e.g. the (x, y) in the previous example), it must be parenthesized. List comprehensions can contain complex expressions and nested functions: The initial expression in a list comprehension can be any arbitrary expression, including another list comprehension. Consider the following example of a 3x4 matrix implemented as a list of 3 lists of length 4: The following list comprehension will transpose rows and columns: As we saw in the previous section, the nested listcomp is evaluated in the context of the$_{for}$ that follows it, so this example is equivalent to: >>> [[row[i] for row in matrix] for i in range(4)] [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]] >>> matrix =[ ... [1,2,3,4], ... [5,6,7,8], ... [9,10 ,11 ,12 ], ... ] >>> from math import pi >>> [str(round(pi, i)) for i in range(1,6)] ['3.1', '3.14', '3.142', '3.1416', '3.14159'] 5.1.4 Nested List Comprehensions >>> vec=[-4,-2,0,2,4] >>> # create a new list with the values doubled >>> [x*2 for x in vec] [-8, -4, 0, 4, 8] >>> # filter the list to exclude negative numbers >>> [x for x in vec if x >=0] [0, 2, 4] >>> # apply a function to all the elements >>> [abs(x) for x in vec] [4, 2, 0, 2, 4] >>> # call a method on each element >>> freshfruit =[' banana',' loganberry','passion fruit '] >>> [weapon.strip() for weapon in freshfruit] ['banana', 'loganberry', 'passion fruit'] >>> # create a list of 2-tuples like (number, square) >>> [(x, x **2) for x in range(6)] [(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)] >>> # the tuple must be parenthesized, otherwise an error is raised >>> [x, x**2 for x in range(6)] File "<stdin>", line 1, in <module> [x, x**2 for x in range(6)] ^ SyntaxError: invalid syntax >>> # flatten a list using a listcomp with two 'for' >>> vec=[[1,2,3], [4,5,6], [7,8,9]] >>> [num for elem in vec for num in elem] [1, 2, 3, 4, 5, 6, 7, 8, 9] >>> combs [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3,