11.2. For Nested

  • Loop inside a loop

  • Used to iterate over nested data

11.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

11.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

11.2.3. Iterating List of Pairs

>>> users = [
...     ('Mark', 'Watney'),
...     ('Melissa', 'Lewis'),
...     ('Rick', 'Martinez'),
... ]
>>>
>>>
>>> for user in users:
...     firstname = user[0]
...     lastname = user[1]
...     print (f'{firstname=}, {lastname=}')
...
firstname='Mark', lastname='Watney'
firstname='Melissa', lastname='Lewis'
firstname='Rick', lastname='Martinez'

11.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)

11.2.5. Iterating List of Dicts

>>> DATA = [
...     {'firstname': 'Mark', 'lastname': 'Watney'},
...     {'firstname': 'Melissa', 'lastname': 'Lewis'},
...     {'firstname': 'Rick', 'lastname': 'Martinez'},
... ]
>>>
>>> for row in DATA:
...     keys = list(row.keys())
...     values = list(row.values())
...     print(f'{keys=}, {values=}')
...
keys=['firstname', 'lastname'], values=['Mark', 'Watney']
keys=['firstname', 'lastname'], values=['Melissa', 'Lewis']
keys=['firstname', 'lastname'], values=['Rick', 'Martinez']

11.2.6. Iterating Mixed

Let's analyze the following example. We received data as follows:

>>> DATA = [('Mark', 'Watney'), 'mwatney', 41, 175.5, [True, None, False]]

The desired format should be:

Mark
Watney
mwatney
41
175.5
True
None
False

How to convert DATA to desired format?

>>> DATA = [('Mark', 'Watney'), 'mwatney', 41, 175.5, [True, None, False]]
>>>
>>> for item in DATA:
...     if type(item) in (tuple, list):
...         for x in item:
...             print(x)
...     else:
...         print(item)
Mark
Watney
mwatney
41
175.5
True
None
False

11.2.7. Convention

  • outer - for outer loop element

  • inner - for inner loop element

  • i - row number

  • j - column number

  • row - row values

  • column - column values

  • x - row values

  • y - column values

  • Note that i may interfere with i used as loop counter

11.2.8. Assignments

# %% 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

# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`

# %% About
# - Name: For Nested Mean
# - Difficulty: easy
# - Lines: 5
# - Minutes: 5

# %% 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ść

# %% Hints
# - `sum() / len()`
# - `from statistics import mean`

# %% Tests
"""
>>> 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
"""

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:]

# Arithmetic mean from `sepal_length` column
# type: float
result = ...


# %% 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

# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`

# %% About
# - Name: For Nested Unique Keys
# - Difficulty: easy
# - Lines: 5
# - Minutes: 5

# %% 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ść

# %% Hints
# - `row.keys()`
# - `list.append()`

# %% Tests
"""
>>> 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']
"""

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'},
]

# Define `result: list[str]` with unique keys from `DATA`
# Do not use `set`
# type: list[str]
result = ...


# %% 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

# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`

# %% About
# - Name: For Nested Unique Keys
# - Difficulty: easy
# - Lines: 4
# - Minutes: 3

# %% 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ść

# %% Hints
# - `row.keys()`
# - `list.append()`

# %% Tests
"""
>>> 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']
"""

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'},
]

# Define `result: set[str]` with unique keys from `DATA`
# Do not use `set.update()`
# type: set[str]
result = ...


# %% 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

# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`

# %% About
# - Name: For Nested Unique Keys
# - Difficulty: easy
# - Lines: 3
# - Minutes: 3

# %% 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ść

# %% Hints
# - `row.keys()`
# - `set.add()`
# - `set.update()`

# %% Tests
"""
>>> 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']
"""

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'},
]

# Define `result: set[str]` with unique keys from `DATA`
# Do not use `list`
# type: set[str]
result = ...