Music Philosophy Art Math Chess Programming and much more ...
๐ Example: Filtering a List (Imperative vs Declarative)
Let’s say we have this list:
[1, 2, 3, 4, 5, 6]
We want to extract only the even numbers.
๐งฑ Imperative Style
numbers = [1, 2, 3, 4, 5, 6]
evens = []
for n in numbers:
if n % 2 == 0:
evens.append(n)
print(evens)
# Output: [2, 4, 6]
Here, we explicitly manage:
for n in numbers
)if n % 2 == 0
)evens.append(n)
)We told the computer how to do it, step by step.
๐งผ Declarative Style
numbers = [1, 2, 3, 4, 5, 6]
evens = list(filter(lambda n: n % 2 == 0, numbers))
print(evens)
# Output: [2, 4, 6]
Or, even more idiomatic in Python:
evens = [n for n in numbers if n % 2 == 0]
Here, we describe what we want — "a list of n from numbers where n is even" — and let the language take care of how it's done internally.