About
Comprehension are a way to loop over elements of:
- a Python - Set,
Comprehensions permit to build collections out of other collections.
Comprehensions allow one to express computations over the elements of a set, list, or dictionary without a traditional for-loop.
Use of comprehensions leads to more compact and more readable code, code that more clearly expresses the mathematical idea behind the computation being expressed.
Comprehensions are implemented using a function scope.
Articles Related
Syntax
IF as a filter
An IF that filter a sequence
[ EXP for x in seq if COND ]
Example
>>> list = [1, 2, 3]
>>> [x for x in list if x == 2]
[2]
IF as a ternary
An IF as a ternary operator to transform the element of the sequence
[ EXP IF condition then EXP else EXP for x in seq ]
Example
>>> list = [1, 2, 3]
>>> [x if x==2 else 0 for x in list]
[0, 2, 0]
Example
Initialization
S = [2 * x for x in range(101) if x ** 2 > 3]
Count Number of Occurrence in a List
The following piece of code create a dictionary with as key the element and as value, the number of occurrence of the element in the list
>>> tokens
[1, 2, 3, 2]
>>> {x:tokens.count(x) for x in tokens}
{1: 1, 2: 2, 3: 1}