12.2. For Nested
Loop inside a loop
Used to iterate over nested data
12.2.1. Nested Loops
You can have loop inside a loop:
>>> DATA = [[1, 2, 3],
... [4, 5, 6],
... [7, 8, 9]]
>>>
>>>
>>> total = 0
>>> for row in DATA:
... for value in row:
... total += value
>>>
>>> total
45
12.2.2. Iterating List of List
Matrix
Suggested variable name:
row
>>> DATA = [[1, 2, 3],
... [4, 5, 6],
... [7, 8, 9]]
>>>
>>>
>>> for row in DATA:
... a = row[0]
... b = row[1]
... c = row[2]
... print(f'{a=} {b=} {c=}')
...
a=1 b=2 c=3
a=4 b=5 c=6
a=7 b=8 c=9
12.2.3. Iterating List of Pairs
>>> users = [
... ('Alice', 'Apricot'),
... ('Bob', 'Banana'),
... ('Carol', 'Corn'),
... ]
>>>
>>>
>>> for user in users:
... firstname = user[0]
... lastname = user[1]
... print (f'{firstname=}, {lastname=}')
...
firstname='Alice', lastname='Apricot'
firstname='Bob', lastname='Banana'
firstname='Carol', lastname='Corn'
12.2.4. Iterating List of Sequence
>>> DATA = [
... (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'),
... ]
>>>
>>>
>>> for row in DATA:
... values = row[0:4]
... species = row[4]
... print(f'{species=}, {values=}')
...
species='setosa', values=(5.1, 3.5, 1.4, 0.2)
species='versicolor', values=(5.7, 2.8, 4.1, 1.3)
species='virginica', values=(6.3, 2.9, 5.6, 1.8)
12.2.5. Iterating List of Dicts
>>> DATA = [
... {'firstname': 'Alice', 'lastname': 'Apricot'},
... {'firstname': 'Bob', 'lastname': 'Banana'},
... {'firstname': 'Carol', 'lastname': 'Corn'},
... ]
>>>
>>> for row in DATA:
... keys = list(row.keys())
... values = list(row.values())
... print(f'{keys=}, {values=}')
...
keys=['firstname', 'lastname'], values=['Alice', 'Apricot']
keys=['firstname', 'lastname'], values=['Bob', 'Banana']
keys=['firstname', 'lastname'], values=['Carol', 'Corn']
12.2.6. Iterating Mixed
DATA = ['Alice', 'Apricot', ('alice@example.com', 'alice@example.edu'), 25]
Let's analyze the following example. We received data as follows:
>>> DATA = ['Alice', 'Apricot', ('alice@example.com', 'alice@example.edu'), 25]
The desired format should be:
Alice
Apricot
alice@example.com
alice@example.edu
30
How to convert DATA
to desired format?
>>> DATA = ['Alice', 'Apricot', ('alice@example.com', 'alice@example.edu'), 25]
>>>
>>> for item in DATA:
... if type(item) in (tuple, list):
... for x in item:
... print(x)
... else:
... print(item)
Alice
Apricot
alice@example.com
alice@example.edu
25
12.2.7. Convention
outer
- for outer loop elementinner
- for inner loop elementi
- row numberj
- column numberrow
- row valuescolumn
- column valuesx
- row valuesy
- column valuesNote that
i
may interfere withi
used as loop counter
12.2.8. Assignments
# %% About
# - Name: For Nested Mean
# - Difficulty: easy
# - Lines: 5
# - Minutes: 5
# %% 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. Calculate mean `sepal_length` value
# 2. Run doctests - all must succeed
# %% Polish
# 1. Wylicz średnią wartość `sepal_length`
# 2. Uruchom doctesty - wszystkie muszą się powieść
# %% Example
# 5.911111111111111
# %% Hints
# - `sum() / len()`
# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'
>>> assert result is not Ellipsis, \
'Assign your result to variable `result`'
>>> assert type(result) is float, \
'Variable `result` has invalid type, should be float'
>>> result
5.911111111111111
"""
# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`
# %% Imports
# %% Types
result: float
# %% Data
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'),
(7.6, 3.0, 6.6, 2.1, 'virginica'),
(4.6, 3.1, 1.5, 0.2, 'setosa'),
]
header = DATA[0]
rows = DATA[1:]
# %% Result
result = ...
# %% About
# - Name: For Nested Unique Keys
# - Difficulty: easy
# - Lines: 5
# - Minutes: 5
# %% 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 unique keys from `DATA`
# 2. Do not use `set`
# 3. Run doctests - all must succeed
# %% Polish
# 1. Zdefiniuj `result: list[str]` z unikalnymi kluczami z `DATA`
# 2. Nie używaj `set`
# 3. Uruchom doctesty - wszystkie muszą się powieść
# %% Example
# ['petal_length', 'petal_width', 'sepal_length', 'sepal_width', 'species']
# %% Hints
# - `dict.keys()`
# - `list.append()`
# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'
>>> assert result is not Ellipsis, \
'Assign your result to variable `result`'
>>> assert type(result) is list, \
'Variable `result` has invalid type, should be list'
>>> assert all(type(x) is str for x in result)
>>> from pprint import pprint
>>> result = sorted(result)
>>> pprint(result, width=79, sort_dicts=False)
['petal_length', 'petal_width', 'sepal_length', 'sepal_width', 'species']
"""
# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`
# %% Imports
# %% Types
result: list[str]
# %% Data
DATA = [
{'sepal_length': 5.1, 'sepal_width': 3.5, 'species': 'setosa'},
{'petal_length': 4.1, 'petal_width': 1.3, 'species': 'versicolor'},
{'sepal_length': 6.3, 'petal_width': 1.8, 'species': 'virginica'},
{'sepal_length': 5.0, 'petal_width': 0.2, 'species': 'setosa'},
{'sepal_width': 2.8, 'petal_length': 4.1, 'species': 'versicolor'},
{'sepal_width': 2.9, 'petal_width': 1.8, 'species': 'virginica'},
]
# %% Result
result = ...
# %% About
# - Name: For Nested Unique Keys
# - Difficulty: easy
# - Lines: 4
# - Minutes: 3
# %% 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: set[str]` with unique keys from `DATA`
# 2. Do not use `set.update()`
# 3. Run doctests - all must succeed
# %% Polish
# 1. Zdefiniuj `result: set[str]` z unikalnymi kluczami z `DATA`
# 2. Nie używaj `set.update()`
# 3. Uruchom doctesty - wszystkie muszą się powieść
# %% Example
# {'petal_length', 'petal_width', 'sepal_length', 'sepal_width', 'species'}
# %% Hints
# - `dict.keys()`
# - `set.add()`
# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'
>>> assert result is not Ellipsis, \
'Assign your result to variable `result`'
>>> assert type(result) is set, \
'Variable `result` has invalid type, should be set'
>>> assert all(type(x) is str for x in result)
>>> from pprint import pprint
>>> result = sorted(result)
>>> pprint(result, width=79, sort_dicts=False)
['petal_length', 'petal_width', 'sepal_length', 'sepal_width', 'species']
"""
# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`
# %% Imports
# %% Types
result: set[str]
# %% Data
DATA = [
{'sepal_length': 5.1, 'sepal_width': 3.5, 'species': 'setosa'},
{'petal_length': 4.1, 'petal_width': 1.3, 'species': 'versicolor'},
{'sepal_length': 6.3, 'petal_width': 1.8, 'species': 'virginica'},
{'sepal_length': 5.0, 'petal_width': 0.2, 'species': 'setosa'},
{'sepal_width': 2.8, 'petal_length': 4.1, 'species': 'versicolor'},
{'sepal_width': 2.9, 'petal_width': 1.8, 'species': 'virginica'},
]
# %% Result
result = ...
# %% About
# - Name: For Nested Unique Keys
# - Difficulty: easy
# - Lines: 3
# - Minutes: 3
# %% 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: set[str]` with unique keys from `DATA`
# 2. Do not use `list`
# 3. Run doctests - all must succeed
# %% Polish
# 1. Zdefiniuj `result: set[str]` z unikalnymi kluczami z `DATA`
# 2. Nie używaj `list`
# 3. Uruchom doctesty - wszystkie muszą się powieść
# %% Example
# {'petal_length', 'petal_width', 'sepal_length', 'sepal_width', 'species'}
# %% Hints
# - `dict.keys()`
# - `set.update()`
# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'
>>> assert result is not Ellipsis, \
'Assign your result to variable `result`'
>>> assert type(result) is set, \
'Variable `result` has invalid type, should be set'
>>> assert all(type(x) is str for x in result)
>>> from pprint import pprint
>>> result = sorted(result)
>>> pprint(result, width=79, sort_dicts=False)
['petal_length', 'petal_width', 'sepal_length', 'sepal_width', 'species']
"""
# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`
# %% Imports
# %% Types
result: set[str]
# %% Data
DATA = [
{'sepal_length': 5.1, 'sepal_width': 3.5, 'species': 'setosa'},
{'petal_length': 4.1, 'petal_width': 1.3, 'species': 'versicolor'},
{'sepal_length': 6.3, 'petal_width': 1.8, 'species': 'virginica'},
{'sepal_length': 5.0, 'petal_width': 0.2, 'species': 'setosa'},
{'sepal_width': 2.8, 'petal_length': 4.1, 'species': 'versicolor'},
{'sepal_width': 2.9, 'petal_width': 1.8, 'species': 'virginica'},
]
# %% Result
result = ...