The aim of this page📝is to introduce comprehensions and their use for lists. Comprehensions are
- syntactic sugar
- readable
- expressive
- self-documenting by being close to natural language
- or concise syntax for the description of:
- lists
- sets
- dicts
- it seems to be declarative like SQL is declarative
- the expressino can be any python expression
- usually the produce a items in a new list - this makes it similar to map (there you modify the existing values)
#[expression(item) for item in iterable]
list = ['pavol', 'ignatius', 'benedictus']
lengths = [len(name) for name in list]
- this is the synonym for the following imperative code
lengths = []
for name in list:
lengths.append(len(name))
- same syntax, only in curly braces - the example is just an illustrative deduplication of the length of the first 19 integers
from math import factorial
s = {len(str(factorial(x))) for x in range(20)}
type(s)
<class 'set'>
print(s)
{1,2,3,4,5,6,7,8,9,10,11,13,14,15,16,18}