Do you want to master Python π list comprehensions?
Do you want to become more proficient working with lists in Python π?
If you answered with βyesβ, then here's a cheatsheet of mine to help you out.
This is also a thread π𧡠that breaks it down and explains everything:
First off, here is the anatomy of a list comprehension.
There's 4 parts to a list comp:
1. enclosing brackets to create the list [];
2. expression that transforms your data;
3. `for` iteration over the initial data;
4. (optional!) condition to filter some data.
Do list comprehensions look confusing?
Maybe.
But that's because you didn't realise that list comprehensions have equivalent `for` loops!
The coloured boxes below show the equivalent bits in the list comp and in the `for` loop:
If you type `import this` in a Python REPL, you will be presented with the Zen of Python, a document with some guidelines that you can follow when writing code.