13.1. Comprehension About
13.1.1. Summary
Loop leaks out values
Syntax:
>>>
... result = [<APPEND> for <VARIABLE> in <ITERABLE>]
13.1.2. Problem
>>> data = ['alice', 'bob', 'carol']
>>>
>>> result = []
>>> for name in data:
... result.append(name)
>>>
>>> print(result)
['alice', 'bob', 'carol']
13.1.3. Solution
>>> data = ['alice', 'bob', 'carol']
>>>
>>> result = [name for name in data]
>>>
>>> print(result)
['alice', 'bob', 'carol']
13.1.4. Naming
Use shorter variable names
x
is common name
>>> data = ['alice', 'bob', 'carol']
>>>
>>> result = [name for name in data]
>>> result = [x for x in data]
13.1.5. Scope
Variables leak from loops
Variables do not leak from comprehensions
For loop:
>>> print(x)
Traceback (most recent call last):
NameError: name 'x' is not defined
>>>
>>> data = ['alice', 'bob', 'carol']
>>>
>>> result = []
>>> for x in data:
... result.append(x)
>>>
>>> print(x)
carol
Comprehension:
>>> print(x)
Traceback (most recent call last):
NameError: name 'x' is not defined
>>>
>>> data = ['alice', 'bob', 'carol']
>>> result = [x for x in data]
>>>
>>> print(x)
Traceback (most recent call last):
NameError: name 'x' is not defined
13.1.6. Rationale
Manipulate Numbers
Manipulate Strings
Manipulate Numbers:
>>> data = [1, 2, 3, 4]
>>>
>>> [x**2 for x in data]
[1, 4, 9, 16]
Manipulate Strings:
>>> data = ['alice', 'bob', 'carol']
>>>
>>> [x.upper() for x in data]
['ALICE', 'BOB', 'CAROL']
13.1.7. Use Case - 1
Increment
>>> DATA = [1, 2, 3, 4]
>>>
>>> [x+1 for x in DATA]
[2, 3, 4, 5]
13.1.8. Use Case - 2
Decrement
>>> DATA = [1, 2, 3, 4]
>>>
>>> [x-1 for x in DATA]
[0, 1, 2, 3]
13.1.9. Use Case - 3
Even or Odd
>>> DATA = [1, 2, 3, 4]
>>>
>>> [x%2==0 for x in DATA]
[False, True, False, True]
13.1.10. Assignments
# %% About
# - Name: Comprehension About Range
# - Difficulty: easy
# - Lines: 1
# - Minutes: 2
# %% 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
# %% English
# 1. Define `result: list[int]` with
# numbers from 0 to 5 (without 5)
# 2. Non-functional requirements:
# - Use list comprehension
# - Use `range()` function
# - Run doctests - all must succeed
# %% Polish
# 1. Zdefiniuj `result: list[int]` z
# liczbami od 0 do 5 (bez 5)
# 2. Non-functional requirements:
# - Użyj list comprehension
# - Użyj funkcji `range()`
# - Uruchom doctesty - wszystkie muszą się powieść
# %% Example
# >>> result
# [0, 1, 2, 3, 4]
# %% Hints
# - `[... for ... in ...]`
# - `range()`
# - `range` parameter `start` is inclusive
# - `range` parameter `stop` is exclusive
# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'
>>> assert type(result) is list, \
'Variable `result` has an invalid type; expected: `list`.'
>>> assert all(type(x) is int for x in result), \
'Variable `result` has elements of an invalid type; all items should be: `int`.'
>>> result
[0, 1, 2, 3, 4]
"""
# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -f -v myfile.py`
# %% Imports
# %% Types
result: list[int]
# %% Data
# %% Result
result = ...
# %% About
# - Name: Comprehension About Squares
# - Difficulty: easy
# - Lines: 1
# - Minutes: 2
# %% 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
# %% English
# 1. Define `result: list[int]` with
# numbers from 0 to 5 (without 5) raised to the power of two (squared)
# 2. Non-functional requirements:
# - Use list comprehension
# - Use `range()` function
# - Run doctests - all must succeed
# %% Polish
# 1. Zdefiniuj `result: list[int]` z
# liczbami od 0 do 5 (bez 5) podniesionymi do potęgi dwa (kwadraty)
# 2. Non-functional requirements:
# - Użyj list comprehension
# - Użyj funkcji `range()`
# - Uruchom doctesty - wszystkie muszą się powieść
# %% Example
# >>> result
# [0, 1, 4, 9, 16]
# %% Hints
# - `[... for ... in ...]`
# - `range()`
# - `range()` parameter `start` is inclusive
# - `range()` parameter `stop` is exclusive
# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'
>>> assert type(result) is list, \
'Variable `result` has an invalid type; expected: `list`.'
>>> assert all(type(x) is int for x in result), \
'Variable `result` has elements of an invalid type; all items should be: `int`.'
>>> result
[0, 1, 4, 9, 16]
"""
# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -f -v myfile.py`
# %% Imports
# %% Types
result: list[int]
# %% Data
# %% Result
result = ...
# %% About
# - Name: Comprehension About Upper
# - Difficulty: easy
# - Lines: 1
# - Minutes: 2
# %% 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
# %% English
# 1. Define `result: list[str]` with
# capitalized letters from `DATA`
# 2. Non-functional requirements:
# - Use `DATA` variable
# - Use list comprehension
# - Run doctests - all must succeed
# %% Polish
# 1. Zdefiniuj `result: list[str]` z
# literami z `DATA` zapisanymi wielkimi literami
# 2. Non-functional requirements:
# - Użyj zmiennej `DATA`
# - Use list comprehension
# - Uruchom doctesty - wszystkie muszą się powieść
# %% Example
# >>> result
# ['A', 'B', 'C', 'D']
# %% Hints
# - `str.upper()`
# - `[... for ... in ...]`
# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'
>>> assert type(result) is list, \
'Variable `result` has an invalid type; expected: `list`.'
>>> assert all(type(x) is str for x in result), \
'Variable `result` has elements of an invalid type; all items should be: `str`.'
>>> result
['A', 'B', 'C', 'D']
"""
# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -f -v myfile.py`
# %% Imports
# %% Types
result: list[str]
# %% Data
DATA = ['a', 'b', 'c', 'd']
# %% Result
result = ...