From 3d0be3647a4560b4e461dbdfca09de7536e04f57 Mon Sep 17 00:00:00 2001 From: Charles Cabergs Date: Tue, 24 Nov 2020 14:35:41 +0100 Subject: Added python's list comprehension draft --- blog/python_list_comprehension.md | 87 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 87 insertions(+) create mode 100644 blog/python_list_comprehension.md (limited to 'blog') 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 + +``` +[ 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 +``` -- cgit