12.4. Loop Unpacking Assignment

12.4.1. Recap

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

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

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

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

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

12.4.6. Mixed

>>> DATA = [(1, 2),
...         ('name', 'Jan Twardowski'),
...         ('species', ['setosa', 'versicolor', 'virginica']),
...         ((1, 2), ['Johnson Space Center', 'Kennedy Space Center']),
...         (['NASA', 'ESA', 'Roscosmos'], 1)]
>>>
>>> for first, second in DATA:
...     print(f'{first} -> {second}')
1 -> 2
name -> Jan Twardowski
species -> ['setosa', 'versicolor', 'virginica']
(1, 2) -> ['Johnson Space Center', 'Kennedy Space Center']
['NASA', 'ESA', 'Roscosmos'] -> 1

12.4.7. Enumerate

  • Pythonic way

  • Preferred over i=0 and i+=1 for every iteration

  • enumerate() will return counter and value for every iteration

>>> DATA = ['a', 'b', 'c']
>>> result = enumerate(DATA)
>>>
>>> next(result)
(0, 'a')
>>> next(result)
(1, 'b')
>>> next(result)
(2, 'c')
>>> next(result)
Traceback (most recent call last):
StopIteration

enumerate() will return counter and value for every iteration:

>>> DATA = ['a', 'b', 'c']
>>>
>>> for i, letter in enumerate(DATA):
...     print(f'{i} -> {letter}')
0 -> a
1 -> b
2 -> c

enumerate() can start with custom number:

>>> DATA = ['a', 'b', 'c']
>>>
>>> for i, letter in enumerate(DATA, start=5):
...     print(f'{i} -> {letter}')
5 -> a
6 -> b
7 -> c
>>> 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 i, row in enumerate(DATA):
...     print(f'{i} -> {row}')
0 -> (5.1, 3.5, 1.4, 0.2, 'setosa')
1 -> (5.7, 2.8, 4.1, 1.3, 'versicolor')
2 -> (6.3, 2.9, 5.6, 1.8, 'virginica')

12.4.8. Zip

>>> roles = ['commander', 'botanist', 'chemist']
>>> crew = ['Melissa Lewis', 'Mark Watney', 'Alex Vogel']
>>> result = zip(roles, crew)
>>>
>>> next(result)
('commander', 'Melissa Lewis')
>>> next(result)
('botanist', 'Mark Watney')
>>> next(result)
('chemist', 'Alex Vogel')
>>> next(result)
Traceback (most recent call last):
StopIteration
>>> roles = ['commander', 'botanist', 'chemist']
>>> crew = ['Melissa Lewis', 'Mark Watney', 'Alex Vogel']
>>>
>>> for role, name in zip(roles, crew):
...     print(f'{role} -> {name}')
commander -> Melissa Lewis
botanist -> Mark Watney
chemist -> Alex Vogel

12.4.9. Assignments

Code 12.14. 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

    >>> type(result)
    <class '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[int,str]: dict with month number and name. Start with 1
result = ...

Code 12.15. Solution
"""
* Assignment: Loop Unpacking Endswith
* Required: yes
* Complexity: medium
* Lines of code: 4 lines
* Time: 13 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 danych 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

    >>> type(result)
    <class 'set'>

    >>> '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

# set[str]: species names ending with 'ca' or 'osa'
result = ...