aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorGravatar swfarnsworth <[email protected]>2021-02-06 10:35:27 -0500
committerGravatar swfarnsworth <[email protected]>2021-02-06 10:35:27 -0500
commitd333a777aff579ac9d4f38467345fb946dd46bc3 (patch)
tree756872b318485400182d2e41d4650b4079f2af34
parentMore robust example with no reference to Python versions or `str.format`. (diff)
New example to emphasize the mapping functionality rather than filtering.
Previously, the example only conveyed how the `if` statement of list comps could be used to filter a list, whereas the mapping functionality is what people primarily use list comps for.
-rw-r--r--bot/resources/tags/listcomps.md23
1 files changed, 14 insertions, 9 deletions
diff --git a/bot/resources/tags/listcomps.md b/bot/resources/tags/listcomps.md
index 0003b9bb8..ba00a4bf7 100644
--- a/bot/resources/tags/listcomps.md
+++ b/bot/resources/tags/listcomps.md
@@ -1,14 +1,19 @@
-Do you ever find yourself writing something like:
+Do you ever find yourself writing something like this?
```py
-even_numbers = []
-for n in range(20):
- if n % 2 == 0:
- even_numbers.append(n)
+>>> squares = []
+>>> for n in range(5):
+... squares.append(n ** 2)
+[0, 1, 4, 9, 16]
```
-Using list comprehensions can simplify this significantly, and greatly improve code readability. If we rewrite the example above to use list comprehensions, it would look like this:
+Using list comprehensions can make this both shorter and more readable. As a list comprehension, the same code would look like this:
```py
-even_numbers = [n for n in range(20) if n % 2 == 0]
+>>> [n ** 2 for n in range(5)]
+[0, 1, 4, 9, 16]
+```
+List comprehensions also get an `if` statement:
+```python
+>>> [n ** 2 for n in range(5) if n % 2 == 0]
+[0, 4, 16]
```
-This also works for generators, dicts and sets by using `()` or `{}` instead of `[]`.
-For more info, see [this pythonforbeginners.com post](http://www.pythonforbeginners.com/basics/list-comprehensions-in-python) or [PEP 202](https://www.python.org/dev/peps/pep-0202/).
+For more info, see [this pythonforbeginners.com post](http://www.pythonforbeginners.com/basics/list-comprehensions-in-python).