13.2. For Nested
Loop inside a loop
Used to iterate over nested data
Iterating List of Lists
Iterating List of Tuples
Iterating List of Dicts
Iterating Mixed
13.2.1. Iterating List of Lists
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
13.2.2. Iterating List of Tuples
firstname = row[0]lastname = row[1]age = row[2]
>>> DATA = [
... ('firstname', 'lastname', 'age'),
... ('Alice', 'Apricot', 30),
... ('Bob', 'Blackthorn', 31),
... ('Carol', 'Corn', 32),
... ('Dave', 'Durian', 33),
... ('Eve', 'Elderberry', 34),
... ('Mallory', 'Melon', 15),
... ]
>>>
>>>
>>> for row in DATA[1:]:
... firstname = row[0]
... lastname = row[1]
... age = row[2]
... print(f'Hello {firstname=}, {lastname=}, {age=}')
...
Hello firstname='Alice', lastname='Apricot', age=30
Hello firstname='Bob', lastname='Blackthorn', age=31
Hello firstname='Carol', lastname='Corn', age=32
Hello firstname='Dave', lastname='Durian', age=33
Hello firstname='Eve', lastname='Elderberry', age=34
Hello firstname='Mallory', lastname='Melon', age=15
13.2.3. Iterating List of Dicts
firstname = row['firstname']lastname = row['lastname']age = row['age']
>>> 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},
... ]
>>>
>>>
>>> for row in DATA:
... firstname = row['firstname']
... lastname = row['lastname']
... age = row['age']
... print(f'Hello {firstname=}, {lastname=}, {age=}')
...
Hello firstname='Alice', lastname='Apricot', age=30
Hello firstname='Bob', lastname='Blackthorn', age=31
Hello firstname='Carol', lastname='Corn', age=32
Hello firstname='Dave', lastname='Durian', age=33
Hello firstname='Eve', lastname='Elderberry', age=34
Hello firstname='Mallory', lastname='Melon', age=15
13.2.4. 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
13.2.5. Convention
outer- for outer loop elementinner- for inner loop elementi- row numberj- column numberrow- row valuescolumn- column valuesx- row valuesy- column valuesNote that
imay interfere withiused as loop counter
13.2.6. Recap
Loop inside a loop
Used to iterate over nested data
Iterating List of Lists
Iterating List of Tuples
Iterating List of Dicts
Iterating Mixed
List of Lists:
>>> 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 Tuples:
>>> 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 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
13.2.7. Assignments
# %% About
# - Name: For About Endswith
# - 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` with email addresses from `DATA`,
# having domain name mentioned in `DOMAINS`
# 2. Domain name is a part of the email address after `@` character
# 3. Run doctests - all must succeed
# %% Polish
# 1. Zdefiniuj `result: list` z adresami email z `DATA`,
# mającymi domenę wymienioną w `DOMAINS`
# 2. Nazwa domeny to część adresu email po znaku `@`
# 3. Uruchom doctesty - wszystkie muszą się powieść
# %% Expected
# >>> result
# ['alice@example.com',
# 'bob@example.com',
# 'carol@example.com',
# 'mallory@example.net']
# %% Why
# - Check if you can filter data
# - Check if you know string methods
# - Check if you know how to iterate over list[dict]
# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python has an is invalid version; expected: `3.9` or newer.'
>>> from pprint import pprint
>>> assert 'result' in globals(), \
'Variable `result` is not defined; assign result of your program to it.'
>>> 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 len(result) > 0, \
'Variable `result` has an invalid length; expected more than zero elements.'
>>> assert all(type(x) is str for x in result), \
'Variable `result` has elements of an invalid type; all items should be: `str`.'
>>> result = sorted(result)
>>> pprint(result)
['alice@example.com',
'bob@example.com',
'carol@example.com',
'mallory@example.net']
"""
# %% 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 = [
{'name': 'Alice', 'email': 'alice@example.com'},
{'name': 'Bob', 'email': 'bob@example.com'},
{'name': 'Carol', 'email': 'carol@example.com'},
{'name': 'Dave', 'email': 'dave@example.org'},
{'name': 'Eve', 'email': 'eve@example.org'},
{'name': 'Mallory', 'email': 'mallory@example.net'},
]
DOMAINS = ('example.com', 'example.net')
# %% 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ść
# %% Expected
# >>> result
# 29.166666666666668
# %% Hints
# - `sum() / len()`
# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python has an is invalid version; expected: `3.9` or newer.'
>>> assert 'result' in globals(), \
'Variable `result` is not defined; assign result of your program to it.'
>>> 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 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ść
# %% Expected
# >>> result
# 29.166666666666668
# %% Hints
# - `sum() / len()`
# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python has an is invalid version; expected: `3.9` or newer.'
>>> assert 'result' in globals(), \
'Variable `result` is not defined; assign result of your program to it.'
>>> 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 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ść
# %% Expected
# >>> result
# ['age', 'firstname', 'lastname']
# %% Hints
# - `dict.keys()`
# - `list.append()`
# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python has an is invalid version; expected: `3.9` or newer.'
>>> assert 'result' in globals(), \
'Variable `result` is not defined; assign result of your program to it.'
>>> 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 = ...