list: list Comprehension
list Comprehension
- Provide a concise way to create lists.
- Consists of brackets containing an expression followed by a for clause, then zero or more for or if clauses.
- Result will be a new list resulting from evaluating the expression in the context of the for and if clauses which follow it.
- >>> combs = [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y] >>> combs [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)] # same as >>> combs = [] >>> for x in [1,2,3]: ... for y in [3,1,4]: ... if x != y: ... combs.append((x, y)) ... >>> combs [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)].
Semantic portal