Copyright (C) 2000-2012 |
GNU Info (python2.1-tut.info)List ComprehensionsList Comprehensions ------------------- List comprehensions provide a concise way to create lists without resorting to use of `map()', `filter()' and/or `lambda'. The resulting list definition tends often to be clearer than lists built using those constructs. Each list comprehension consists of an expression following by a `for' clause, then zero or more `for' or `if' clauses. The result will be a list resulting from evaluating the expression in the context of the `for' and `if' clauses which follow it. If the expression would evaluate to a tuple, it must be parenthesized. >>> freshfruit = [' banana', ' loganberry ', 'passion fruit '] >>> [weapon.strip() for weapon in freshfruit] ['banana', 'loganberry', 'passion fruit'] >>> vec = [2, 4, 6] >>> [3*x for x in vec] [6, 12, 18] >>> [3*x for x in vec if x > 3] [12, 18] >>> [3*x for x in vec if x < 2] [] >>> [{x: x**2} for x in vec] [{2: 4}, {4: 16}, {6: 36}] >>> [[x,x**2] for x in vec] [[2, 4], [4, 16], [6, 36]] >>> [x, x**2 for x in vec] # error - parens required for tuples File "<stdin>", line 1 [x, x**2 for x in vec] ^ SyntaxError: invalid syntax >>> [(x, x**2) for x in vec] [(2, 4), (4, 16), (6, 36)] >>> vec1 = [2, 4, 6] >>> vec2 = [4, 3, -9] >>> [x*y for x in vec1 for y in vec2] [8, 6, -18, 16, 12, -36, 24, 18, -54] >>> [x+y for x in vec1 for y in vec2] [6, 5, -7, 8, 7, -5, 10, 9, -3] automatically generated by info2www version 1.2.2.9 |