12.4. Comprehension Map
12.4.1. To Float
>>> DATA = [1, 2, 3]
>>>
>>> [float(x) for x in DATA]
[1.0, 2.0, 3.0]
12.4.2. To Str
>>> DATA = [1, 2, 3]
>>>
>>> [str(x) for x in DATA]
['1', '2', '3']
12.4.3. Round
>>> DATA = [1.1111, 2.2222, 3.3333]
>>>
>>> [round(x,1) for x in DATA]
[1.1, 2.2, 3.3]
12.4.4. To Tuple
>>> 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'),
... ]
>>>
>>> [tuple(row[0:4]) for row in DATA[1:]]
[(5.8, 2.7, 5.1, 1.9),
(5.1, 3.5, 1.4, 0.2),
(5.7, 2.8, 4.1, 1.3),
(6.3, 2.9, 5.6, 1.8),
(6.4, 3.2, 4.5, 1.5),
(4.7, 3.2, 1.3, 0.2)]
12.4.5. Use Case - 1
Convert DATA to CSV
Method str.join()
requires all arguments to be strings. If your data
has other types in it, such as int
in the following examples, method
will fail:
>>> DATA = [1, 2, 3]
>>>
>>> ','.join(DATA)
Traceback (most recent call last):
TypeError: sequence item 0: expected str instance, int found
You can convert those values to string using comprehension:
>>> DATA = [1, 2, 3]
>>>
>>> ','.join(str(x) for x in DATA)
'1,2,3'
12.4.6. Use Case - 2
Raise number to the n-th power
>>> DATA = [1, 2, 3]
>>>
>>> [pow(x,2) for x in DATA]
[1, 4, 9]
>>>
>>> [pow(2,x) for x in DATA]
[2, 4, 8]
>>>
>>> [pow(x,x) for x in DATA]
[1, 4, 27]
12.4.7. Use Case - 3
Map list[dict]
>>> users = [
... {'is_admin': True, 'name': 'Melissa Lewis'},
... {'is_admin': True, 'name': 'Mark Watney'},
... {'is_admin': False, 'name': 'Rick Martinez'},
... {'is_admin': True, 'name': 'Alex Vogel'},
... ]
>>>
>>>
>>> admin = [{'firstname': user['name'].split()[0],
... 'lastname': user['name'].split()[1]}
... for user in users
... if user['is_admin']]
>>>
>>> print(admin)
[{'firstname': 'Melissa', 'lastname': 'Lewis'},
{'firstname': 'Mark', 'lastname': 'Watney'},
{'firstname': 'Alex', 'lastname': 'Vogel'}]
12.4.8. Use Case - 4
>>> users = [
... {'is_admin': True, 'name': 'Melissa Lewis'},
... {'is_admin': True, 'name': 'Mark Watney'},
... {'is_admin': False, 'name': 'Rick Martinez'},
... {'is_admin': True, 'name': 'Alex Vogel'},
... ]
>>>
>>>
>>> admins = [{'firstname': user['name'].split()[0].capitalize(),
... 'lastname': user['name'].split()[1][0]+'.'}
... for user in users
... if user['is_admin']]
>>>
>>> print(admins)
[{'firstname': 'Melissa', 'lastname': 'L.'},
{'firstname': 'Mark', 'lastname': 'W.'},
{'firstname': 'Alex', 'lastname': 'V.'}]
12.4.9. 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 About Float
# - Difficulty: easy
# - Lines: 1
# - Minutes: 2
# %% English
# 1. Define `result: list[float]` with
# converted to float values from `DATA`
# 2. Non-functional requirements:
# - Use `DATA` variable
# - Use list comprehension
# - Run doctests - all must succeed
# %% Polish
# 1. Zdefiniuj `result: list` z
# przekształconymi na float wartościami z `DATA`
# 2. Non-functional requirements:
# - Użyj zmiennej `DATA`
# - Use list comprehension
# - Uruchom doctesty - wszystkie muszą się powieść
# %% Hints
# - `float()`
# - `[... for ... in ...]`
# %% 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 float for x in result), \
'Result should be a list of float'
>>> result
[0.0, 1.0, 2.0, 3.0, 4.0]
"""
DATA = [0, 1, 2, 3, 4]
# Converted to float values from `DATA`
# type: list[float]
result = ...
# %% 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 About Round
# - Difficulty: easy
# - Lines: 1
# - Minutes: 2
# %% English
# 1. Define `result: list[float]` with
# rounded values in `DATA` to 2 decimal places
# 2. Non-functional requirements:
# - Use `DATA` variable
# - Use list comprehension
# - Run doctests - all must succeed
# %% Polish
# 1. Zdefiniuj `result: list` z
# zaaokrąglonymi wartościami w `DATA` do 2 miejsc po przecinku
# 2. Non-functional requirements:
# - Użyj zmiennej `DATA`
# - Use list comprehension
# - Uruchom doctesty - wszystkie muszą się powieść
# %% Hints
# - `round()`
# - `[... for ... in ...]`
# %% 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 float for x in result), \
'Result should be a list of float'
>>> result
[1.11, 2.22, 3.33, 4.44]
"""
DATA = [1.1111, 2.2222, 3.3333, 4.4444]
# Rounded values in `DATA` to 2 decimal places
# type: list[float]
result = ...
# %% 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 List Str
# - Difficulty: easy
# - Lines: 1
# - Minutes: 2
# %% English
# 1. Define `result: list[float]` with
# converted to str values from `DATA`
# 2. Non-functional requirements:
# - Use `DATA` variable
# - Use list comprehension
# - Run doctests - all must succeed
# %% Polish
# 1. Zdefiniuj `result: list` z
# przekształconymi na str wartościami z `DATA`
# 2. Non-functional requirements:
# - Użyj zmiennej `DATA`
# - Use list comprehension
# - Uruchom doctesty - wszystkie muszą się powieść
# %% Hints
# - `str()`
# - `[... for ... in ...]`
# %% 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 str for x in result), \
'Result should be a list of str'
>>> result
['Mark', 'Watney', '41']
"""
DATA = ['Mark', 'Watney', 41]
# Converted to str values from `DATA`
# type: list[float]
result = ...
# %% 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 List Join
# - Difficulty: easy
# - Lines: 1
# - Minutes: 2
# %% English
# 1. Define `result: str` with
# comma-separated string from `DATA` values
# 2. Non-functional requirements:
# - Use `DATA` variable
# - Use list comprehension
# - Run doctests - all must succeed
# %% Polish
# 1. Zdefiniuj `result: str` ze
# stringiem z oddzielonymi przecinkiem wartościami z `DATA`
# 2. Non-functional requirements:
# - Użyj zmiennej `DATA`
# - Użyj list comprehension
# - Uruchom doctesty - wszystkie muszą się powieść
# %% Hints
# - `str.join()`
# - `str()`
# - `[... for ... in ...]`
# %% Tests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'
>>> assert type(result) is str, \
'Variable `result` has invalid type, should be str'
>>> result
'Mark,Watney,41'
"""
DATA = ['Mark', 'Watney', 41]
# Comma-separated string from `DATA` values
# type: str
result = ...
# %% 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 List Translate
# - Difficulty: easy
# - Lines: 1
# - Minutes: 3
# %% English
# 1. Use list comprehension to iterate over `DATA`
# 2. If letter is in `PL` then use conversion value as letter
# 3. Add letter to `result`
# 4. Run doctests - all must succeed
# %% Polish
# 1. Użyj rozwinięcia listowego do iteracji po `DATA`
# 2. Jeżeli litera jest w `PL` to użyj skonwertowanej wartości jako litera
# 3. Dodaj literę do `result`
# 4. Uruchom doctesty - wszystkie muszą się powieść
# %% Hints
# - `str.join()`
# - `dict.get()`
# %% Tests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'
>>> assert type(result) is str
>>> result
'zazolc gesla jazn'
"""
PL = {
'ą': 'a',
'ć': 'c',
'ę': 'e',
'ł': 'l',
'ń': 'n',
'ó': 'o',
'ś': 's',
'ż': 'z',
'ź': 'z',
}
DATA = 'zażółć gęślą jaźń'
# DATA with PL diacritic characters replaced with ASCII letters
# type: str
result = ...