12.2. For Nested
Loop inside a loop
Used to iterate over nested data
Iterating List of List
Iterating List of Pairs
Iterating List of Sequence
Iterating List of Dicts
Iterating Mixed
12.2.1. Iterating List of List
Matrix
Suggested variable name:
row
>>> 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 Pairs
>>> users = [
... ('Alice', 'Apricot'),
... ('Bob', 'Blackthorn'),
... ('Carol', 'Corn'),
... ]
>>>
>>>
>>> for user in users:
... firstname = user[0]
... lastname = user[1]
... print (f'{firstname=}, {lastname=}')
...
firstname='Alice', lastname='Apricot'
firstname='Bob', lastname='Blackthorn'
firstname='Carol', lastname='Corn'
12.2.3. 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.4. Iterating List of Dicts
>>> DATA = [
... {'firstname': 'Alice', 'lastname': 'Apricot'},
... {'firstname': 'Bob', 'lastname': 'Blackthorn'},
... {'firstname': 'Carol', 'lastname': 'Corn'},
... ]
>>>
>>> for row in DATA:
... firstname = row['firstname']
... lastname = row['lastname']
... print(f'{firstname=}, {lastname=}')
...
firstname='Alice', lastname='Apricot'
firstname='Bob', lastname='Blackthorn'
firstname='Carol', lastname='Corn'
12.2.5. Iterating Mixed
DATA = ['Alice', 'Apricot', ('alice@example.com', 'alice@example.edu'), 30]
Let's analyze the following example. We received data as follows:
>>> DATA = ['Alice', 'Apricot', ('alice@example.com', 'alice@example.edu'), 30]
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'), 30]
>>>
>>> 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
30
12.2.6. 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.7. Recap
Loop inside a loop
Used to iterate over nested data
Iterating List of List
Iterating List of Pairs
Iterating List of Sequence
Iterating List of Dicts
Iterating Mixed
List of List:
>>> DATA = [[1, 2, 3],
... [4, 5, 6],
... [7, 8, 9]]
>>>
>>>
>>> for row in DATA:
... for value in row:
... print(value)
1
2
3
4
5
6
7
8
9
List of Pairs:
>>> users = [
... ('Alice', 'Apricot'),
... ('Bob', 'Blackthorn'),
... ('Carol', 'Corn'),
... ]
>>>
>>> for user in users:
... firstname = user[0]
... lastname = user[1]
... print(f'{firstname=}, {lastname=}')
firstname='Alice', lastname='Apricot'
firstname='Bob', lastname='Blackthorn'
firstname='Carol', lastname='Corn'
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'{values=}, {species=}')
values=(5.1, 3.5, 1.4, 0.2), species='setosa'
values=(5.7, 2.8, 4.1, 1.3), species='versicolor'
values=(6.3, 2.9, 5.6, 1.8), species='virginica'
List of Dicts:
>>> DATA = [
... {'firstname': 'Alice', 'lastname': 'Apricot'},
... {'firstname': 'Bob', 'lastname': 'Blackthorn'},
... {'firstname': 'Carol', 'lastname': 'Corn'},
... ]
>>>
>>> for row in DATA:
... firstname = row['firstname']
... lastname = row['lastname']
... print(f'{firstname=}, {lastname=}')
firstname='Alice', lastname='Apricot'
firstname='Bob', lastname='Blackthorn'
firstname='Carol', lastname='Corn'
Mixed:
>>> DATA = ['Alice', 'Apricot', ('alice@example.com', 'alice@example.edu'), 30]
>>>
>>> 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
30
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 -f -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. Collect unique keys from `DATA`
# 2. Result assign to variable `result: list[str]`
# 3. Use `list.append()`
# 4. Run doctests - all must succeed
# %% Polish
# 1. Zbierz unikalne klucze z `DATA`
# 2. Wynik przypisz do zmiennej `result: list[str]`
# 3. Użyj `list.append()`
# 4. 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 -f -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. Collect unique keys from `DATA`
# 2. Result assign to variable `result: set[str]`
# 3. Use `set.add()`
# 4. Run doctests - all must succeed
# %% Polish
# 1. Zbierz unikalne klucze z `DATA`
# 2. Wynik przypisz do zmiennej `result: set[str]`
# 3. Użyj `set.add()`
# 4. 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 -f -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. Collect unique keys from `DATA`
# 2. Result assign to variable `result: set[str]`
# 3. Use `set.update()`
# 4. Run doctests - all must succeed
# %% Polish
# 1. Zbierz unikalne klucze z `DATA`
# 2. Wynik przypisz do zmiennej `result: set[str]`
# 3. Użyj `set.update()`
# 4. Uruchom doctesty - wszystkie muszą się powieść
# %% Example
# >>> result
# {'age', 'firstname', 'lastname'}
# %% 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)
['age', 'firstname', 'lastname']
"""
# %% 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: set[str]
# %% Data
DATA = [
{'firstname': 'Alice', 'lastname': 'Apricot'},
{'firstname': 'Bob', 'age': 31},
{'lastname': 'Corn', 'firstname': 'Carol'},
{'lastname': 'Durian', 'age': 33},
{'age': 34, 'firstname': 'Eve'},
{'age': 15, 'lastname': 'Mallory', },
]
# %% Result
result = ...