10.4. Iterator Enumerate — Python
Enumerate sequence
Lazy evaluated
enumerate(iterable, start=0)Required
iterable- 1 or many sequences or iterator objectOptional
start=0- number to starts with, default zero (0)Return an
enumerateobjectThe enumerate object yields pairs containing a count (from start, defaults to zero) and a value yielded by the iterable argument
10.4.1. Problem
>>> data = ['Alice', 'Bob', 'Carol'] >>> >>> result = [] >>> index = 0 >>> for value in data: ... result.append((index, value)) ... index += 1
10.4.2. Solution
>>> data = ['Alice', 'Bob', 'Carol'] >>> >>> result = enumerate(data)
10.4.3. Lazy Evaluation
>>> data = ['Alice', 'Bob', 'Carol'] >>> result = enumerate(data) >>> >>> next(result) (0, 'Alice') >>> >>> next(result) (1, 'Bob') >>> >>> next(result) (2, 'Carol') >>> >>> next(result) Traceback (most recent call last): StopIteration
10.4.4. Iteration
Unpacking in a
forloop
>>> data = ['Alice', 'Bob', 'Carol'] >>> >>> for result in enumerate(data): ... print(result) (0, 'Alice') (1, 'Bob') (2, 'Carol')
>>> data = ['Alice', 'Bob', 'Carol'] >>> >>> for index, value in enumerate(data): ... print(f'{index=}, {value=}') index=0, value='Alice' index=1, value='Bob' index=2, value='Carol'
10.4.5. Offset
>>> data = ['Alice', 'Bob', 'Carol'] >>> >>> for result in enumerate(data, start=1): ... print(result) (1, 'Alice') (2, 'Bob') (3, 'Carol')
>>> data = ['Alice', 'Bob', 'Carol'] >>> >>> for result in enumerate(data, start=10): ... print(result) (10, 'Alice') (11, 'Bob') (12, 'Carol')
10.4.6. As List
>>> data = ['Alice', 'Bob', 'Carol'] >>> result = enumerate(data) >>> >>> list(result) [(0, 'Alice'), (1, 'Bob'), (2, 'Carol')]
10.4.7. As Dict
>>> data = ['Alice', 'Bob', 'Carol'] >>> result = enumerate(data) >>> >>> dict(result) {0: 'Alice', 1: 'Bob', 2: 'Carol'}
10.4.8. Dict Comprehension
>>> data = ['Alice', 'Bob', 'Carol']
As dict:
>>> {index:value for index,value in enumerate(data, start=1)} {1: 'Alice', 2: 'Bob', 3: 'Carol'}
Reverse dict:
>>> {value:index for index,value in enumerate(data, start=1)} {'Alice': 1, 'Bob': 2, 'Carol': 3}
Stringify keys:
>>> {f'{index}':value for index,value in enumerate(data, start=1)} {'1': 'Alice', '2': 'Bob', '3': 'Carol'}
Zero-fill keys:
>>> {f'{index:02}':value for index,value in enumerate(data, start=1)} {'01': 'Alice', '02': 'Bob', '03': 'Carol'}
10.4.9. Case Study
DATA = """3,4,setosa,virginica,versicolor 5.8,2.7,5.1,1.9,1 5.1,3.5,1.4,0.2,0 5.7,2.8,4.1,1.3,2""" header, *lines = DATA.splitlines() nrows, nvalues, *labels = header.split(',') encoder = dict(enumerate(labels)) encoder # {0: 'setosa', 1: 'virginica', 2: 'versicolor'}
10.4.10. Assignments
# %% About # - Name: Iterator Enumerate Dict # - Difficulty: easy # - Lines: 1 # - Minutes: 2 # %% 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. Define `result: dict` # 2. Assign to `result` converted `DATA` to `dict` # 3. Use `enumerate()` i `dict()` # 4. Run doctests - all must succeed # %% Polish # 1. Zdefiniuj `result: dict` # 2. Przypisz do `result` przekonwertowane `DATA` do `dict` # 3. Użyj `enumerate()` i `dict()` # 4. Uruchom doctesty - wszystkie muszą się powieść # %% Expected # result # {0: 'users', 1: 'staff', 2: 'admins'} # %% Hints # - `dict()` # - `enumerate()` # %% Doctests """ >>> import sys; sys.tracebacklimit = 0 >>> assert sys.version_info >= (3, 9), \ 'Python has an is invalid version; expected: `3.9` or newer.' >>> assert type(result) is dict, \ 'Variable `result` has an invalid type; expected: `dict`.' >>> assert all(type(x) is int for x in result.keys()), \ 'Variable `result.keys()` has elements of an invalid type; all items should be: `int`.' >>> assert all(type(x) is str for x in result.values()), \ 'Variable `result.values()` has elements of an invalid type; all items should be: `str`.' >>> result {0: 'users', 1: 'staff', 2: 'admins'} """ # %% 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 = ['users', 'staff', 'admins'] # %% Result result = ...
# %% About # - Name: Iterator Enumerate Start # - Difficulty: easy # - Lines: 1 # - Minutes: 2 # %% 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. Convert `DATA` into dict: # - key: int - month number # - value: str - month name # 2. Use `enumerate()` and dict comprehension # 3. Run doctests - all must succeed # %% Polish # 1. Przekonwertuj `DATA` w słownik: # - klucz: int - numer miesiąca # - wartość: str - nazwa miesiąca # 2. Użyj `enumerate()` i dict comprehension # 3. Uruchom doctesty - wszystkie muszą się powieść # %% Expected # >>> result # {0: 'January', # 1: 'February', # 2: 'March', # 3: 'April', # 4: 'May', # 5: 'June', # 6: 'July', # 7: 'August', # 8: 'September', # 9: 'October', # 10: 'November', # 11: 'December'} # %% Hints # - `dict()` # - `enumerate()` # %% Doctests """ >>> import sys; sys.tracebacklimit = 0 >>> assert sys.version_info >= (3, 9), \ 'Python has an is invalid version; expected: `3.9` or newer.' >>> assert type(result) >>> assert -1 not in result >>> assert 0 in result >>> assert 12 not in result >>> assert 13 not in result >>> assert result[0] == 'January' >>> assert all(type(x) is int for x in result.keys()) >>> assert all(type(x) is str for x in result.values()) >>> from pprint import pprint >>> pprint(result, width=30, sort_dicts=False) {0: 'January', 1: 'February', 2: 'March', 3: 'April', 4: 'May', 5: 'June', 6: 'July', 7: 'August', 8: 'September', 9: 'October', 10: 'November', 11: '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 = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December', ] # %% Result result = ...
# %% About # - Name: Iterator Enumerate Start # - Difficulty: easy # - Lines: 1 # - Minutes: 2 # %% 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. Convert `DATA` into dict: # - key: int - month number # - value: str - month name # 2. Use `enumerate()` and dict comprehension # 3. Enumerate starting from 1 # 4. Run doctests - all must succeed # %% Polish # 1. Przekonwertuj `DATA` w słownik: # - klucz: int - numer miesiąca # - wartość: str - nazwa miesiąca # 2. Użyj `enumerate()` i dict comprehension # 3. Enumerację zacznij od 1 # 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 # - `dict()` # - `enumerate()` # %% Doctests """ >>> import sys; sys.tracebacklimit = 0 >>> assert sys.version_info >= (3, 9), \ 'Python has an is invalid version; expected: `3.9` or newer.' >>> type(result) <class 'dict'> >>> 0 not in result True >>> 13 not in result True >>> result[1] == 'January' True >>> assert all(type(x) is int for x in result.keys()) >>> assert all(type(x) is str for x in result.values()) >>> from pprint import pprint >>> pprint(result, width=30, sort_dicts=False) {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 = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December', ] # %% Result result = ...
# %% About # - Name: Iterator Enumerate Start # - Difficulty: easy # - Lines: 1 # - Minutes: 2 # %% 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. Convert `DATA` into dict: # - key: str - month number (convert to str) # - value: str - month name # 2. Use `enumerate()` and dict comprehension # 3. Enumerate starting from 1 # 4. Run doctests - all must succeed # %% Polish # 1. Przekonwertuj `DATA` w słownik: # - klucz: str - numer miesiąca (zamień na str) # - wartość: str - nazwa miesiąca # 2. Użyj `enumerate()` i dict comprehension # 3. Enumerację zacznij od 1 # 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 # - dict comprehension # - `str()` # - `enumerate()` # %% Doctests """ >>> import sys; sys.tracebacklimit = 0 >>> assert sys.version_info >= (3, 9), \ 'Python has an is invalid version; expected: `3.9` or newer.' >>> type(result) <class 'dict'> >>> '0' not in result True >>> '13' not in result True >>> result['1'] == 'January' True >>> assert all(type(x) is str for x in result.keys()) >>> assert all(type(x) is str for x in result.values()) >>> from pprint import pprint >>> pprint(result, width=30, sort_dicts=False) {'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[str,str] # %% Data DATA = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December', ] # %% Result result = ...
# %% About # - Name: Iterator Enumerate ZeroPadded # - Difficulty: easy # - Lines: 1 # - Minutes: 2 # %% 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. Convert `DATA` into dict: # - key: str - month number (convert to str) # - value: str - month name # 2. Use `enumerate()` and dict comprehension # 3. Enumerate starting from 1 # 4. Month number must be two letter string # (zero padded) - np. 01, 02, ..., 09, 10, 11, 12 # 5. Run doctests - all must succeed # %% Polish # 1. Przekonwertuj `DATA` w słownik: # - klucz: str - numer miesiąca (zamień na str) # - wartość: str - nazwa miesiąca # 2. Użyj `enumerate()` i dict comprehension # 3. Enumerację zacznij od 1 # 4. Numer miesiąca ma być dwuznakowym stringiem # (dopełnionym zerem) - np. 01, 02, ..., 09, 10, 11, 12 # 5. Uruchom doctesty - wszystkie muszą się powieść # %% Expected # >>> result # {'01': 'January', # '02': 'February', # '03': 'March', # '04': 'April', # '05': 'May', # '06': 'June', # '07': 'July', # '08': 'August', # '09': 'September', # '10': 'October', # '11': 'November', # '12': 'December'} # %% Hints # - dict comprehension # - `enumerate()` # - `str.zfill()` # - `f'{number:02}'` # %% Doctests """ >>> import sys; sys.tracebacklimit = 0 >>> assert sys.version_info >= (3, 9), \ 'Python has an is invalid version; expected: `3.9` or newer.' >>> type(result) <class 'dict'> >>> '00' not in result True >>> '13' not in result True >>> result['01'] == 'January' True >>> assert all(type(x) is str for x in result.keys()) >>> assert all(type(x) is str for x in result.values()) >>> assert all(len(x) == 2 for x in result.keys()) >>> from pprint import pprint >>> pprint(result, width=30, sort_dicts=False) {'01': 'January', '02': 'February', '03': 'March', '04': 'April', '05': 'May', '06': 'June', '07': 'July', '08': 'August', '09': '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[str,str] # %% Data DATA = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December', ] # %% Result result = ...
# %% About # - Name: Iterator Enumerate Impl # - Difficulty: medium # - Lines: 7 # - 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. Write own implementation of a built-in `enumerate()` function # 2. Define function `myenumerate` with parameters: # - parameter `iterable: list | tuple` # - parameter `start: int` # 3. Don't validate arguments and assume, that user will: # - always pass valid type of arguments # - iterable length will always be greater than 0 # 4. Do not use built-in function `enumerate()` # 5. Use `yield` keyword # 6. Run doctests - all must succeed # %% Polish # 1. Zaimplementuj własne rozwiązanie wbudowanej funkcji `enumerate()` # 2. Zdefiniuj funkcję `myenumerate` z parametrami: # - parametr `iterable: list | tuple` # - parametr `start: int` # 3. Nie waliduj argumentów i przyjmij, że użytkownik: # - zawsze poda argumenty poprawnych typów # - długość iterable będzie większa od 0 # 4. Nie używaj wbudowanej funkcji `enumerate()` # 5. Użyj słowa kluczowego `yield` # 6. Uruchom doctesty - wszystkie muszą się powieść # %% Expected # >>> list(myenumerate(['January', 'February', 'March'])) # [(0, 'January'), (1, 'February'), (2, 'March')] # # >>> list(myenumerate(['January', 'February', 'March'], start=1)) # [(1, 'January'), (2, 'February'), (3, 'March')] # # >>> dict(myenumerate(['January', 'February', 'March'], start=1)) # {1: 'January', 2: 'February', 3: 'March'} # %% Hints # - https://github.com/python/cpython/blob/main/Objects/enumobject.c # - `range()` # - `len()` # - `list.append()` # %% Doctests """ >>> import sys; sys.tracebacklimit = 0 >>> assert sys.version_info >= (3, 9), \ 'Python has an is invalid version; expected: `3.9` or newer.' >>> from inspect import isfunction >>> assert isfunction(myenumerate) >>> result = myenumerate(['January', 'February', 'March']) >>> list(result) [(0, 'January'), (1, 'February'), (2, 'March')] >>> result = myenumerate(['January', 'February', 'March'], start=1) >>> list(result) [(1, 'January'), (2, 'February'), (3, 'March')] >>> result = myenumerate(['January', 'February', 'March'], start=1) >>> dict(result) {1: 'January', 2: 'February', 3: 'March'} """ # %% 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 from typing import Callable myenumerate: Callable[[tuple|list, int], list[tuple]] # %% Data # %% Result def myenumerate(iterable, start=0): ...