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 value of field `age`
# 2. Run doctests - all must succeed
# %% Polish
# 1. Wylicz średnią wartość pola `age`
# 2. Uruchom doctesty - wszystkie muszą się powieść
# %% Example
# >>> result
# 29.166666666666668
# %% Hints
# - `sum() / len()`
# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'
>>> assert result is not Ellipsis, \
'Variable `result` has an invalid value; assign result of your program to it.'
>>> assert type(result) is float, \
'Variable `result` has an invalid type; expected: `float`.'
>>> result
29.166666666666668
"""
# %% 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 = [
{'firstname': 'Alice', 'lastname': 'Apricot', 'age': 30},
{'firstname': 'Bob', 'lastname': 'Blackthorn', 'age': 31},
{'firstname': 'Carol', 'lastname': 'Corn', 'age': 32},
{'firstname': 'Dave', 'lastname': 'Durian', 'age': 33},
{'firstname': 'Eve', 'lastname': 'Elderberry', 'age': 34},
{'firstname': 'Mallory', 'lastname': 'Melon', 'age': 15},
]
# %% Result
result = ...
# %% 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 value of field `age`
# 2. Run doctests - all must succeed
# %% Polish
# 1. Wylicz średnią wartość pola `age`
# 2. Uruchom doctesty - wszystkie muszą się powieść
# %% Example
# >>> result
# 29.166666666666668
# %% Hints
# - `sum() / len()`
# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'
>>> assert result is not Ellipsis, \
'Variable `result` has an invalid value; assign result of your program to it.'
>>> assert type(result) is float, \
'Variable `result` has an invalid type; expected: `float`.'
>>> result
29.166666666666668
"""
# %% 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 = [
('firstname', 'lastname', 'age'),
('Alice', 'Apricot', 30),
('Bob', 'Blackthorn', 31),
('Carol', 'Corn', 32),
('Dave', 'Durian', 33),
('Eve', 'Elderberry', 34),
('Mallory', 'Melon', 15),
]
# %% 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
# >>> result
# {'age', 'firstname', 'lastname'}
# %% 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, \
'Variable `result` has an invalid value; assign result of your program to it.'
>>> assert type(result) is list, \
'Variable `result` has an invalid type; expected: `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)
['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: list[str]
# %% Data
DATA = [
{'firstname': 'Alice', 'lastname': 'Apricot'},
{'firstname': 'Bob', 'age': 30},
{'lastname': 'Corn', 'firstname': 'Carol'},
{'lastname': 'Durian', 'age': 50},
{'age': 60, 'firstname': 'Eve'},
{'age': 10, 'lastname': 'Mallory', },
]
# %% 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
# >>> result
# {'age', 'firstname', 'lastname'}
# %% 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, \
'Variable `result` has an invalid value; assign result of your program to it.'
>>> assert type(result) is set, \
'Variable `result` has an invalid type; expected: `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': 30},
{'lastname': 'Corn', 'firstname': 'Carol'},
{'lastname': 'Durian', 'age': 50},
{'age': 60, 'firstname': 'Eve'},
{'age': 10, 'lastname': 'Mallory', },
]
# %% 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, \
'Variable `result` has an invalid value; assign result of your program to it.'
>>> assert type(result) is set, \
'Variable `result` has an invalid type; expected: `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': 30},
{'lastname': 'Corn', 'firstname': 'Carol'},
{'lastname': 'Durian', 'age': 50},
{'age': 60, 'firstname': 'Eve'},
{'age': 10, 'lastname': 'Mallory', },
]
# %% Result
result = ...