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
Was this helpful?