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