12.5. Comprehension Filter
12.5.1. Problem
>>> DATA = [1, 2, 3, 4]
>>>
>>> result = []
>>> for x in DATA:
... if x % 2 == 0:
... result.append(x)
>>>
>>> print(result)
[2, 4]
12.5.2. Solution
>>> DATA = [1, 2, 3, 4]
>>> result = [x for x in DATA if x%2==0]
>>>
>>> print(result)
[2, 4]
12.5.3. Syntax
>>>
... result = [<RETURN> for <VARIABLE> in <ITERABLE> if <CONDITION>]
12.5.4. Filter list[tuple]
>>> DATA = [
... ('Mark', 'Watney', 41),
... ('Melissa', 'Lewis', 40),
... ('Rick', 'Martinez', 39),
... ('Alex', 'Vogel', 40),
... ('Chris', 'Beck', 36),
... ('Beth', 'Johanssen', 29),
... ]
>>>
>>> result = [(firstname, lastname)
... for firstname,lastname,age in DATA
... if age >= 40 and age < 50]
>>>
>>> print(result)
[('Mark', 'Watney'),
('Melissa', 'Lewis'),
('Alex', 'Vogel')]
12.5.5. Filter list[dict]
>>> users = [
... {'is_admin': True, 'login': 'mwatney'},
... {'is_admin': True, 'login': 'mlewis'},
... {'is_admin': True, 'login': 'rmartinez'},
... {'is_admin': False, 'login': 'avogel'},
... ]
>>>
>>>
>>> admins = []
>>> for user in users:
... if user['is_admin']:
... admins.append(user['login'])
>>>
>>> print(admins)
['mwatney', 'mlewis', 'rmartinez']
>>> users = [
... {'is_admin': True, 'login': 'mwatney'},
... {'is_admin': True, 'login': 'mlewis'},
... {'is_admin': True, 'login': 'rmartinez'},
... {'is_admin': False, 'login': 'avogel'},
... ]
>>>
>>>
>>> admins = [user['login']
... for user in users
... if user['is_admin']]
>>>
>>> print(admins)
['mwatney', 'mlewis', 'rmartinez']
12.5.6. Convention
>>> result = [pow(x, 2) for x in range(0, 5) if x % 2 == 0]
>>> result = [pow(x,2) for x in range(0,5) if x%2==0]
>>> result = [pow(x,2)
... for x in range(0,5)
... if x % 2 == 0]
>>> result = [pow(x,2)
... for x in range(0,5)
... if x % 2 == 0]
12.5.7. Use Case - 1
>>> DATA = [
... ('sepal_length', 'sepal_width', 'petal_length', 'petal_width', 'species'),
... (5.8, 2.7, 5.1, 1.9, 'virginica'),
... (5.1, 3.5, 1.4, 0.2, 'setosa'),
... (5.7, 2.8, 4.1, 1.3, 'versicolor'),
... (6.3, 2.9, 5.6, 1.8, 'virginica'),
... (6.4, 3.2, 4.5, 1.5, 'versicolor'),
... (4.7, 3.2, 1.3, 0.2, 'setosa'),
... (7.0, 3.2, 4.7, 1.4, 'versicolor'),
... ]
>>> [row[:-1] for row in DATA[1:] if row[-1] == 'setosa']
[(5.1, 3.5, 1.4, 0.2), (4.7, 3.2, 1.3, 0.2)]
>>> [(sl,sw,pl,pw) for sl,sw,pl,pw,species in DATA[1:] if species=='setosa']
[(5.1, 3.5, 1.4, 0.2), (4.7, 3.2, 1.3, 0.2)]
12.5.8. Assignments
# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author
# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`
# %% About
# - Name: Comprehension Filter Even
# - Difficulty: easy
# - Lines: 1
# - Minutes: 3
# %% English
# 1. Use list comprehension
# 2. Generate `result: list[int]`
# of even numbers from 0 to 10 (without 10)
# 3. Run doctests - all must succeed
# %% Polish
# 1. Użyj rozwinięcia listowego
# 2. Wygeneruj `result: list[int]`
# parzystych liczb z przedziału 0 do 10 (bez 10)
# 3. Uruchom doctesty - wszystkie muszą się powieść
# %% Hints
# - `range()`
# - `%`
# - `==`
# %% Tests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'
>>> assert type(result) is list, \
'Result should be a list'
>>> assert all(type(x) is int for x in result), \
'Result should be a list of int'
>>> result
[0, 2, 4, 6, 8]
"""
DATA = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
# Even numbers from 0 to 10 (without 10)
# type: list[int]
result = ...