Python - Comprehension (Iteration)

> Procedural Languages > Python > Python - Grammar (Package | Module)

1 - About

Comprehension are a way to loop over elements of:

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.

Advertising

3 - Syntax

3.1 - 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]

3.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]

4 - Example

4.1 - Initialization

S = [2 * x for x in range(101) if x ** 2 > 3]

4.2 - 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}
Advertising

5 - Documentation / Reference