Comprehensions
Comprehensions are considered as most "Pythonic" way of constructing needed data on-the-fly.
List comprehension
Dictionary comprehension
Set comprehensions
Generator expression*
List comprehension
Bread and butter of day-to-day Python programming
🪄 Code:
📟 Output:
🪄 Code:
📟 Output:
🪄 Code:
📟 Output:
Dictionary comprehension
Useful to create a dictionary with the same (default) value or predefined by some logic
🪄 Code:
📟 Output:
🪄 Code:
📟 Output:
Set comprehension
Not so widely used but still can be quite helpful. For example if you read lines from the file you can collect unqiue ones.
🪄 Code:
📟 Output:
Generator expression
"Kind of" comprehension but instead of returning sequence as other do, generator expression returns generator object.
🪄 Code:
📟 Output:
🪄 Code:
Last updated