aboutsummaryrefslogtreecommitdiff
path: root/blog/python_list_comprehension.md
blob: 73cd1164634f8aa39593da7e6b13b472a22f3eb8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
# 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

```
[<expr> for <element> in <iterable>]
```

The result of `<expr>` will be the value of the element.

### Comparison

```
result = []
for <element> in <iterable>:
    result.append(<expr>)
```

## 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

```
[<expr> for <element> in <iterable> if <condition>]
```

The result of `<expr>` will be the value of the element if `<condition>` is `True`.

### Comparison

```
result = []
for <element> in <iterable>:
    if <condition>:
        result.append(<expr>)
```

## 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
```