diff options
| author | Charles Cabergs <me@cacharle.xyz> | 2020-11-24 14:35:41 +0100 |
|---|---|---|
| committer | Charles Cabergs <me@cacharle.xyz> | 2020-11-24 14:35:41 +0100 |
| commit | 3d0be3647a4560b4e461dbdfca09de7536e04f57 (patch) | |
| tree | 40eaa463fa71caf6392cfd35efb362ec01b0ee4b /blog/python_list_comprehension.md | |
| parent | efe6f0326400fd02b14ccaaed451eb9b306c7fe5 (diff) | |
| download | cacharle.xyz-list-comprehension.tar.gz cacharle.xyz-list-comprehension.tar.bz2 cacharle.xyz-list-comprehension.zip | |
Added python's list comprehension draftlist-comprehension
Diffstat (limited to 'blog/python_list_comprehension.md')
| -rw-r--r-- | blog/python_list_comprehension.md | 87 |
1 files changed, 87 insertions, 0 deletions
diff --git a/blog/python_list_comprehension.md b/blog/python_list_comprehension.md new file mode 100644 index 0000000..73cd116 --- /dev/null +++ b/blog/python_list_comprehension.md @@ -0,0 +1,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 +``` |
