12.3. For Unpack

  • Unpacking: a, b = 1, 2

  • for firstname,lastname in users

  • Unpack List of Tuples

12.3.1. Recap

  • Unpacking: a, b = 1, 2

Problem:

>>> user = ('alice', 'secret')
>>> username = user[0]
>>> password = user[1]

Solution:

>>> username, password = ('alice', 'secret')

12.3.2. Problem

  • for user in users

>>> USERS = [
...     ('alice', 'secret'),
...     ('bob', 'qwerty'),
...     ('carol', '123456'),
...     ('dave', 'abc123'),
...     ('eve', 'password1'),
...     ('mallory', 'NULL'),
... ]
>>>
>>> for user in USERS:
...     username = user[0]
...     password = user[1]
...     print(f'{username=}, {password=}')
...
username='alice', password='secret'
username='bob', password='qwerty'
username='carol', password='123456'
username='dave', password='abc123'
username='eve', password='password1'
username='mallory', password='NULL'

12.3.3. Solution

  • for firstname,lastname in users

>>> USERS = [
...     ('alice', 'secret'),
...     ('bob', 'qwerty'),
...     ('carol', '123456'),
...     ('dave', 'abc123'),
...     ('eve', 'password1'),
...     ('mallory', 'NULL'),
... ]
>>>
>>> for username, password in USERS:
...     print(f'{username=}, {password=}')
...
username='alice', password='secret'
username='bob', password='qwerty'
username='carol', password='123456'
username='dave', password='abc123'
username='eve', password='password1'
username='mallory', password='NULL'

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

12.3.5. Recap

  • Unpacking: a, b = 1, 2

  • Instead for row in data you can unpack for a,b in data

  • Unpack List of Tuples

>>> USERS = [
...     ('alice', 'secret'),
...     ('bob', 'qwerty'),
...     ('carol', '123456'),
... ]
>>>
>>> for username, password in USERS:
...     print(f'{username=}, {password=}')
...
username='alice', password='secret'
username='bob', password='qwerty'
username='carol', password='123456'

12.3.6. Assignments

# %% About
# - Name: For Unpack Months
# - Difficulty: easy
# - Lines: 3
# - 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. 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ść

# %% Example
# {1: 'January',
#  2: 'February',
#  3: 'March',
#  ...,
#  11: 'November',
#  12: 'December'}

# %% Hints
# - `a, b = (1, 2)`
# - `dict[key] = value`

# %% Doctests
"""
>>> 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'}
"""

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

# %% Imports

# %% Types
result: dict[int,str]

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

# %% Result
result = ...

# %% About
# - Name: For Unpack Between
# - Difficulty: easy
# - Lines: 4
# - 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. Use `DATA: list[tuple]` variable
# 2. Define `result: list[tuple]` with first names and last names
#    of people whose age is greater or equal to 18
# 3. Use unpack syntax in a `for` loop
# 4. 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 większy lub równy 18
# 3. Użyj składni rozpakowania w pętli `for`
# 4. Uruchom doctesty - wszystkie muszą się powieść

# %% Example
# >>> result
# [('Alice', 'Apricot'),
#  ('Bob', 'Banana'),
#  ('Carol', 'Corn'),
#  ('Dave', 'Durian'),
#  ('Eve', 'Elderberry')]

# %% Hints
# - `x >= 18`
# - `a, b, c = (1, 2, 3)`
# - `list.append()`

# %% 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 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)
[('Alice', 'Apricot'),
 ('Bob', 'Banana'),
 ('Carol', 'Corn'),
 ('Dave', 'Durian'),
 ('Eve', 'Elderberry')]
"""

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

# %% Imports

# %% Types
result: list[tuple[str,str]]

# %% Data
DATA = [
    ('firstname', 'lastname', 'age'),
    ('Alice', 'Apricot', 30),
    ('Bob', 'Banana', 31),
    ('Carol', 'Corn', 32),
    ('Dave', 'Durian', 33),
    ('Eve', 'Elderberry', 34),
    ('Mallory', 'Melon', 15),
]

header = DATA[0]
data = DATA[1:]

# %% Result
result = ...

# %% About
# - Name: For Unpack Endswith
# - Difficulty: easy
# - Lines: 4
# - 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. 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ść

# %% Example
# >>> result
# ['alice@example.com',
#  'bob@example.com',
#  'carol@example.com',
#  'dave@example.org',
#  'eve@example.org']

# %% Hints
# - `a, b, c = (1, 2, 3)`
# - `str.split()`
# - `x in list`
# - `list.append`

# %% 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 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)
['alice@example.com',
 'bob@example.com',
 'carol@example.com',
 'dave@example.org',
 'eve@example.org']
"""

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

# %% Imports

# %% Types
result: list[str]

# %% Data
DATA = [
    ('firstname', 'lastname', 'email'),
    ('Alice', 'Apricot', 'alice@example.com'),
    ('Bob', 'Banana', 'bob@example.com'),
    ('Carol', 'Corn', 'carol@example.com'),
    ('Dave', 'Durian', 'dave@example.org'),
    ('Eve', 'Elderberry', 'eve@example.org'),
    ('Mallory', 'Melon', 'mallory@example.net'),
]

DOMAINS = ('example.com', 'example.org')

header = DATA[0]
data = DATA[1:]

# %% Result
result = ...

# %% About
# - Name: For Unpack Unique
# - Difficulty: easy
# - Lines: 3
# - 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. 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ść

# %% Example
# {'virginica', 'setosa', 'versicolor'}

# %% Hints
# - `a,b,c,d,e = (1,2,3,4,5)`
# - `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, \
'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
"""

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

# %% Imports

# %% Types
result: set[str]

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

# %% Result
result = ...