8.8. Loop For Unpacking

8.8.1. Recap

>>> a, b = 1, 2
>>> a, b = (1, 2)
>>> k, v = (1, 2)
>>> key, value = (1, 2)
>>> role, name = ('commander', 'Melissa Lewis')

8.8.2. List of Pairs

>>> DATA = [
...     ('commander', 'Melissa Lewis'),
...     ('botanist', 'Mark Watney'),
...     ('chemist', 'Alex Vogel')]
>>>
>>> for role, name in DATA:
...     print(f'{role} -> {name}')
commander -> Melissa Lewis
botanist -> Mark Watney
chemist -> Alex Vogel

8.8.3. 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 sepal_length, sepal_width, petal_length, petal_width, species in DATA:
...     print(f'{species} -> {sepal_length}')
setosa -> 5.1
versicolor -> 5.7
virginica -> 6.3
>>> 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, s in DATA:
...     print(f'{s} -> {sl}')
setosa -> 5.1
versicolor -> 5.7
virginica -> 6.3

8.8.4. Unpacking Assignment

>>> *features, label = (5.8, 2.7, 5.1, 1.9, 'virginica')
>>>
>>> features
[5.8, 2.7, 5.1, 1.9]
>>> label
'virginica'
>>> DATA = [
...     (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')]
>>>
>>> for *features, label in DATA:
...     avg = sum(features) / len(features)
...     print(f'{label} -> {avg}')
virginica -> 3.875
setosa -> 2.55
versicolor -> 3.475
>>> DATA = [
...     (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')]
>>>
>>> for *X,y in DATA:
...     avg = sum(X) / len(X)
...     print(f'{y} -> {avg}')
virginica -> 3.875
setosa -> 2.55
versicolor -> 3.475

8.8.5. Unused Values

>>> 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 sepal_length, _, _, _, species in DATA:
...     print(f'{species} -> {sepal_length}')
setosa -> 5.1
versicolor -> 5.7
virginica -> 6.3
>>> DATA = [
...     (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')]
>>>
>>> for sepal_length, *_, species in DATA:
...     print(f'{species} -> {sepal_length}')
virginica -> 5.8
setosa -> 5.1
versicolor -> 5.7

8.8.6. Mixed

>>> DATA = [
...     (1, 2),
...     ('name', 'Mark Watney'),
...     ('agency', ['NASA', 'ESA', 'POLSA']),
...     ((1, 2), ['botanist', 'commander', 'pilot']),
...     (['Ares1', 'Are2', 'Ares3'], 1)]
>>>
>>> for first, second in DATA:
...     print(f'{first} -> {second}')
1 -> 2
name -> Mark Watney
agency -> ['NASA', 'ESA', 'POLSA']
(1, 2) -> ['botanist', 'commander', 'pilot']
['Ares1', 'Are2', 'Ares3'] -> 1

8.8.7. Assignments

Code 8.20. Solution
"""
* Assignment: Loop Unpacking Months
* Required: yes
* Complexity: easy
* Lines of code: 2 lines
* Time: 5 min

English:
    1. Use `enumerate()` to convert `MONTH` into `result: dict[int,str]`:
        a. Keys: month number
        b. Values: month name
    2. Run doctests - all must succeed

Polish:
    1. Użyj `enumerate()` do konwersji `MONTH` w `result: dict[int,str]`:
        a. klucz: numer miesiąca
        b. wartość: nazwa miesiąca
    2. Uruchom doctesty - wszystkie muszą się powieść

Tests:
    >>> import sys; sys.tracebacklimit = 0

    >>> 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(x in result.values() for x in MONTHS)

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

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

MONTHS = ['January', 'February', 'March', 'April',
          'May', 'June', 'July', 'August', 'September',
          'October', 'November', 'December']

# Dict with month number and name. Start with 1
# type: dict[int,str]
result = ...

Code 8.21. Solution
"""
* Assignment: Loop Unpacking Endswith
* Required: yes
* Complexity: medium
* Lines of code: 4 lines
* Time: 8 min

English:
    1. Define `result: set[str]`
    2. Iterating over `DATA` unpack row to `*features` and `label`
    3. Append to `result` species with endings in `SUFFIXES`
    4. Run doctests - all must succeed

Polish:
    1. Zdefiniuj `result: set[str]`
    2. Iterując po `DATA` rozpakuj wiersz do `*features` oraz `label`
    3. Dodaj do `result` nazwy gatunków z końcówkami w `SUFFIXES`
    4. Uruchom doctesty - wszystkie muszą się powieść

Hints:
    * `str.endswith()`
    * `set.pop()`

Tests:
    >>> import sys; sys.tracebacklimit = 0

    >>> 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
    False
"""

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

SUFFIXES = ('ca', 'osa')

features: tuple
label: set
species: str

# Species names with word endings in `SUFFIXES`
# type: set[str]
result = ...