# Python's list comprehension List comprehension are the best feature of Python. They allow us to map and filter the elements of lists. ## Mapping You can change each element of a list. ``` >>> xs = [x * x for x in range(10)] >>> xs [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] >>> [x + 10 for x in xs] [10, 11, 14, 19, 26, 35, 46, 59, 74, 91] ``` ### Syntax ``` [ for in ] ``` The result of `` will be the value of the element. ### Comparison ``` result = [] for in : result.append() ``` ## Filter You can filter out elements. ``` >>> [x for x in range(10) if x % 2 == 0] [0, 2, 4, 6, 8] >>> [x * x for x in range(10) if x > 5] [36, 49, 64, 81] ``` ### Syntax ``` [ for in if ] ``` The result of `` will be the value of the element if `` is `True`. ### Comparison ``` result = [] for in : if : result.append() ``` ## Other comprehension ### Dictionnary ``` >>> {k: v * v for k, v in {"foo": 1, "bar": 2}.items()} {"foo": 1, "bar": 4} ``` ### Set ``` >>> {x for x in [1, 2, 3, 1, 1, 1, 2, 1]} {1, 2, 3} ``` ### Generator ``` >>> gen = (x * x for x in range(10)) >>> next(gen) 0 >>> next(gen) 1 >>> next(gen) 4 ```