13.3. For Unpack — Python
Unpack
List of Tuples
username, password = ('Alice', 'Apricot')for firstname,lastname in users
Problem:
>>> name = ('Alice', 'Apricot') >>> firstname = name[0] >>> lastname = name[1]
Solution:
>>> username, password = ('Alice', 'Apricot')
13.3.1. Problem
for user in DATA[1:]
>>> DATA = [ ... ('firstname', 'lastname', 'age'), ... ('Alice', 'Apricot', 30), ... ('Bob', 'Blackthorn', 31), ... ('Carol', 'Corn', 32), ... ('Dave', 'Durian', 33), ... ('Eve', 'Elderberry', 34), ... ('Mallory', 'Melon', 15), ... ] >>> >>> for user in DATA[1:]: ... firstname = user[0] ... lastname = user[1] ... age = user[2] ... print(f'{firstname=}, {lastname=}, {age=}') ... firstname='Alice', lastname='Apricot', age=30 firstname='Bob', lastname='Blackthorn', age=31 firstname='Carol', lastname='Corn', age=32 firstname='Dave', lastname='Durian', age=33 firstname='Eve', lastname='Elderberry', age=34 firstname='Mallory', lastname='Melon', age=15
13.3.2. Solution
for firstname, lastname, age in DATA[1:]
>>> DATA = [ ... ('firstname', 'lastname', 'age'), ... ('Alice', 'Apricot', 30), ... ('Bob', 'Blackthorn', 31), ... ('Carol', 'Corn', 32), ... ('Dave', 'Durian', 33), ... ('Eve', 'Elderberry', 34), ... ('Mallory', 'Melon', 15), ... ] >>> >>> for firstname, lastname, age in DATA[1:]: ... print(f'{firstname=}, {lastname=}, {age=}') ... firstname='Alice', lastname='Apricot', age=30 firstname='Bob', lastname='Blackthorn', age=31 firstname='Carol', lastname='Corn', age=32 firstname='Dave', lastname='Durian', age=33 firstname='Eve', lastname='Elderberry', age=34 firstname='Mallory', lastname='Melon', age=15
13.3.3. Recap
Unpacking:
a, b = 1, 2Instead
for row in datayou can unpackfor a,b in dataUnpack List of Tuples
13.3.4. 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ść # %% Expected # >>> 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'} # %% Hints # - `a, b = (1, 2)` # - `dict[key] = value` # %% Doctests """ >>> import sys; sys.tracebacklimit = 0 >>> assert sys.version_info >= (3, 9), \ 'Python has an is invalid version; expected: `3.9` or newer.' >>> from pprint import pprint >>> assert 'result' in globals(), \ 'Variable `result` is not defined; assign result of your program to it.' >>> assert result is not Ellipsis, \ 'Variable `result` has an invalid value; assign result of your program to it.' >>> assert type(result) is dict, \ 'Variable `result` has an invalid type; expected: `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 -f -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ść # %% Expected # >>> result # [('Alice', 'Apricot'), # ('Bob', 'Blackthorn'), # ('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 has an is invalid version; expected: `3.9` or newer.' >>> from pprint import pprint >>> assert 'result' in globals(), \ 'Variable `result` is not defined; assign result of your program to it.' >>> assert result is not Ellipsis, \ 'Variable `result` has an invalid value; assign result of your program to it.' >>> assert type(result) is list, \ 'Variable `result` has an invalid type; expected: `list`.' >>> assert len(result) > 0, \ 'Variable `result` has an invalid length; expected more than zero elements.' >>> assert all(type(x) is tuple for x in result), \ 'Variable `result` has elements of an invalid type; all items should be: `tuple`.' >>> pprint(result, width=30) [('Alice', 'Apricot'), ('Bob', 'Blackthorn'), ('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 -f -v myfile.py` # %% Imports # %% Types result: list[tuple[str,str]] # %% Data DATA = [ ('firstname', 'lastname', 'age'), ('Alice', 'Apricot', 30), ('Bob', 'Blackthorn', 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ść # %% Expected # >>> 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 has an is invalid version; expected: `3.9` or newer.' >>> from pprint import pprint >>> assert 'result' in globals(), \ 'Variable `result` is not defined; assign result of your program to it.' >>> assert result is not Ellipsis, \ 'Variable `result` has an invalid value; assign result of your program to it.' >>> assert type(result) is list, \ 'Variable `result` has an invalid type; expected: `list`.' >>> assert len(result) > 0, \ 'Variable `result` has an invalid length; expected more than zero elements.' >>> assert all(type(x) is str for x in result), \ 'Variable `result` has elements of an invalid type; all items should be: `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 -f -v myfile.py` # %% Imports # %% Types result: list[str] # %% Data DATA = [ ('firstname', 'lastname', 'email'), ('Alice', 'Apricot', 'alice@example.com'), ('Bob', 'Blackthorn', '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 group names from `DATA` # 3. Skip if user has no group (i.e. group is `None`) # 4. 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 grup z `DATA` # 3. Pomiń, jeśli użytkownik nie ma grupy (tzn. grupa jest `None`) # 4. Użyj składni rozpakowania w pętli for # 5. Uruchom doctesty - wszystkie muszą się powieść # %% Expected # >>> result # {'users', 'staff', 'admins'} # %% 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 has an is invalid version; expected: `3.9` or newer.' >>> assert 'result' in globals(), \ 'Variable `result` is not defined; assign result of your program to it.' >>> assert result is not Ellipsis, \ 'Variable `result` has an invalid value; assign result of your program to it.' >>> assert type(result) is set, \ 'Variable `result` has an invalid type; expected: `set`.' >>> assert len(result) > 0, \ 'Variable `result` has an invalid length; expected more than zero elements.' >>> assert None not in result, \ 'None cannot be in `result` - it is not a group name' >>> assert all(type(x) is str for x in result), \ 'Variable `result` has elements of an invalid type; all items should be: `str`.' >>> assert len(result) == 3, \ 'Variable `result` has an invalid length; expected: `3`.' >>> 'users' in result True >>> 'staff' in result True >>> 'admins' in result True """ # %% Run # - PyCharm: right-click in the editor and `Run Doctest in ...` # - PyCharm: keyboard shortcut `Control + Shift + F10` # - Terminal: `python -m doctest -f -v myfile.py` # %% Imports # %% Types result: set[str] # %% Data DATA = [ ('firstname', 'lastname', 'group'), ('Alice', 'Apricot', 'users'), ('Bob', 'Blackthorn', 'users'), ('Carol', 'Corn', 'staff'), ('Dave', 'Durian', 'staff'), ('Eve', 'Elderberry', 'admins'), ('Mallory', 'Melon', None), ] # %% Result result = ...