From 8dc74e59e8c92306242ec49c5cc1cc4f79db145b Mon Sep 17 00:00:00 2001 From: waldek Date: Wed, 3 Nov 2021 16:07:10 +0100 Subject: [PATCH] adds list comprehesion --- learning_python3.md | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/learning_python3.md b/learning_python3.md index c208bb1..63a5399 100644 --- a/learning_python3.md +++ b/learning_python3.md @@ -1473,6 +1473,39 @@ Plus you could add a prompt that asks how big the shift should be (ROT13, ROT16, # List comprehension This is a bit of an advanced topic but I'm putting it here to show you a very unique and powerful feature of python. +It's an *in-line* combination of `list`, `for` and conditional logic which allows us to make lists of lists which obey certain conditions. +You can [learn](https://12ft.io/proxy?q=https%3A%2F%2Frealpython.com%2Flist-comprehension-python%2F) about it online. + +```python3 +mixed_list = ["one", "2", "three", "4", "5", "six6", "se7en", "8"] + +digits = [d for d in mixed_list if d.isdigit()] + +print(digits) +``` + +The code above can be recreated **without** list comprehension as well, it will just be *a lot* longer. + +```python3 +mixed_list = ["one", "2", "three", "4", "5", "six6", "se7en", "8"] + +digits = [] +for d in mixed_list: + if d.isdigit(): + digits.append(d) + +print(digits) +``` + +As the `d` in the list comprehension is **always** a digit, we can convert it to an integer on the spot! + +```python3 +mixed_list = ["one", "2", "three", "4", "5", "six6", "se7en", "8"] + +digits = [int(d) for d in mixed_list if d.isdigit()] + +print(digits) +``` # Handling files