ARMAGEDDON POP

Music Philosophy Art Math Chess Programming and much more ...

April
23
Wednesday
2025
2025 04 23

Example: Filtering a List (Imperative vs Declarative)



๐Ÿ” 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:

  • The iteration (for n in numbers)
  • The condition (if n % 2 == 0)
  • The result collection (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.