list: list Comprehension

list Comprehension

>>> squares = [x**2 for x in range(10)]
>>> squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
  • 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)].

Related concepts

list Comprehension

list: list Comprehension — Structure map

Clickable & Draggable!

list: list Comprehension — Related pages: