11.3. For Unpack

11.3.1. Recap

  • for user in users:

Unpacking:

>>> a, b = 1, 2
>>> a, b = (1, 2)
>>> k, v = (1, 2)
>>> key, value = (1, 2)
>>> firstname, lastname = ('Mark', 'Watney')

11.3.2. Problem

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

11.3.3. Solution

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

11.3.4. List of Tuples

>>> 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 sl, sw, pl, pw, species in DATA:
...     print(f'{species} -> {sl}')
setosa -> 5.1
versicolor -> 5.7
virginica -> 6.3

11.3.5. List of Sequences

>>> DATA = [
...     (1, 2),
...     ('mwatney', 'Mark Watney'),
...     ('groups', ['users', 'staff', 'admins']),
...     (['mwatney@nasa.gov', 'mwatney@gmail.com'], 'emails'),
...     (('Mark', 'Watney'), [40, 175, 75.5]),
... ]
>>>
>>> for first, second in DATA:
...     print(f'{first} -> {second}')
1 -> 2
mwatney -> Mark Watney
groups -> ['users', 'staff', 'admins']
['mwatney@nasa.gov', 'mwatney@gmail.com'] -> emails
('Mark', 'Watney') -> [40, 175, 75.5]

11.3.6. 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 Unpack Months
# - Difficulty: easy
# - Lines: 3
# - Minutes: 5

# %% English
# 1. Use `DATA: list[tuple]`
# 2. Define `result: dict` with month number and name:
#    - Keys: month number
#    - Values: month name
# 3. Use unpack syntax in a for loop
# 4. Run doctests - all must succeed

# %% Polish
# 1. Użyj `DATA: list[tuple]`
# 2. Zdefiniuj `result: dict` z numerem miesiąca i nazwą:
#    - Klucz: numer miesiąca
#    - Wartość: nazwa miesiąca
# 3. Użyj składni rozpakowania w pętli for
# 4. Uruchom doctesty - wszystkie muszą się powieść

# %% Tests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'

>>> from pprint import pprint

>>> assert result is not Ellipsis, \
'Assign your result to variable `result`'
>>> assert type(result) is dict, \
'Variable `result` has invalid type, should be dict'

>>> assert all(type(x) is int for x in result.keys())
>>> assert all(type(x) is str for x in result.values())
>>> assert all(x in result.keys() for x in range(1, 13))
>>> assert all(v in result.values() for k,v in DATA)

>>> 13 not in result
True
>>> 0 not in result
True

>>> pprint(result)
{1: 'January',
 2: 'February',
 3: 'March',
 4: 'April',
 5: 'May',
 6: 'June',
 7: 'July',
 8: 'August',
 9: 'September',
 10: 'October',
 11: 'November',
 12: 'December'}
"""

DATA = [
    (1, 'January'),
    (2, 'February'),
    (3, 'March'),
    (4, 'April'),
    (5, 'May'),
    (6, 'June'),
    (7, 'July'),
    (8, 'August'),
    (9, 'September'),
    (10, 'October'),
    (11, 'November'),
    (12, 'December'),
]

# Define `result: dict` with month number and name:
# - Keys: month number
# - Values: month name
# Use unpack syntax in a for loop
# type: dict[int,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 Unpack Between
# - Difficulty: easy
# - Lines: 4
# - Minutes: 5

# %% English
# 1. Use `DATA: list[tuple]` variable
# 2. Define `result: list[tuple]` with first names and last names
#    of people whose age between 40 and 50 years old
# 3. Use unpack syntax in a `for` loop
# 5. Run doctests - all must succeed

# %% Polish
# 1. Użyj zmiennej `DATA: list[tuple]`
# 2. Zdefiniuj `result: list[tuple]` z imionami i nazwiskami osób,
#    których wiek jest pomiędzy 40 i 50 lat
# 3. Użyj składni rozpakowania w pętli `for`
# 5. Uruchom doctesty - wszystkie muszą się powieść

# %% Why
# - Check if you can filter data
# - Check if you know string methods
# - Check if you know how to iterate over `list[dict]`

# %% Tests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'

>>> from pprint import pprint

>>> assert result is not Ellipsis, \
'Assign result to variable: `result`'
>>> assert type(result) is list, \
'Result must be a list'
>>> assert len(result) > 0, \
'Result cannot be empty'
>>> assert all(type(element) is tuple for element in result), \
'All elements in result must be a tuple'

>>> pprint(result, width=30)
[('Mark', 'Watney'),
 ('Melissa', 'Lewis'),
 ('Alex', 'Vogel')]
"""

DATA = [
    ('Mark', 'Watney', 41),
    ('Melissa', 'Lewis', 40),
    ('Rick', 'Martinez', 39),
    ('Alex', 'Vogel', 40),
    ('Chris', 'Beck', 36),
    ('Beth', 'Johanssen', 29),
]

# Define `result: list[tuple]` with first names and last names
# of people whose age is between 40 and 50 years old
# Use unpack syntax in a for loop
# 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 Unpack Endswith
# - Difficulty: easy
# - Lines: 4
# - Minutes: 5

# %% English
# 1. Use `DATA: list[tuple]`
# 2. Define `result: list` with:
#    email addresses from `DATA` with domain names listed in `DOMAINS`
# 3. Use unpack syntax in a for loop
# 4. Run doctests - all must succeed

# %% Polish
# 1. Użyj `DATA: list[tuple]`
# 2. Zdefiniuj `result: list` z:
#    adresami email z `DATA` z domenami wymienionymi w `DOMAINS`
# 3. Użyj składni rozpakowania w pętli for
# 4. Uruchom doctesty - wszystkie muszą się powieść

# %% Why
# - Check if you can filter data
# - Check if you know string methods
# - Check if you know how to iterate over `list[dict]`

# %% Tests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'

>>> from pprint import pprint

>>> assert result is not Ellipsis, \
'Assign result to variable: `result`'
>>> assert type(result) is list, \
'Result must be a list'
>>> assert len(result) > 0, \
'Result cannot be empty'
>>> assert all(type(element) is str for element in result), \
'All elements in result must be a str'

>>> result = sorted(result)
>>> pprint(result)
['avogel@esa.int',
 'bjohanssen@nasa.gov',
 'cbeck@nasa.gov',
 'mlewis@nasa.gov',
 'mwatney@nasa.gov',
 'rmartinez@nasa.gov']
"""

DATA = [
    ('Mark', 'Watney', 'mwatney@nasa.gov'),
    ('Melissa', 'Lewis', 'mlewis@nasa.gov'),
    ('Rick', 'Martinez', 'rmartinez@nasa.gov'),
    ('Alex', 'Vogel', 'avogel@esa.int'),
    ('Chris', 'Beck', 'cbeck@nasa.gov'),
    ('Beth', 'Johanssen', 'bjohanssen@nasa.gov'),
    ('Pan', 'Twardowski', 'ptwardowski@polsa.gov.pl'),
    ('Ivan', 'Ivanovich', 'iivanovich@roscosmos.ru'),
]

DOMAINS = ('esa.int', 'nasa.gov')

# Define `result: list` with:
# email addresses from `DATA` with domain names listed in `DOMAINS`
# Use unpack syntax in a for loop
# 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 Unpack Unique
# - Difficulty: easy
# - Lines: 3
# - Minutes: 5

# %% English
# 1. Use `DATA: list[tuple]`
# 2. Define `result: set` with unique species names from `DATA`
# 3. Use unpack syntax in a for loop
# 5. Run doctests - all must succeed

# %% Polish
# 1. Użyj `DATA: list[tuple]`
# 2. Zdefiniuj `result: set` z unikalnymi nazwami gatunków z `DATA`
# 3. Użyj składni rozpakowania w pętli for
# 4. Uruchom doctesty - wszystkie muszą się powieść

# %% 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, \
'Result must be a set'
>>> assert len(result) > 0, \
'Result cannot be empty'
>>> assert all(type(element) is str for element in result), \
'All elements in result must be a str'

>>> 'virginica' in result
True
>>> 'setosa' in result
True
>>> 'versicolor' in result
True
"""

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

# Define `result: set` with unique species names from `DATA`
# Use unpack syntax in a for loop
# type: set[str]
result = ...