Signature
Here is the signature for common usage of enumerate-
enumerate(iterable: Iterable[_T],
start: int = ...
) -> enumerate
Here is the full signature of the enumerate class-
class enumerate(Iterator[Tuple[int, _T]], Generic[_T]):
def __init__(self, iterable: Iterable[_T], start: int = ...) -> None: ...
def __iter__(self) -> Iterator[Tuple[int, _T]]: ...
def __next__(self) -> Tuple[int, _T]: ...
if sys.version_info >= (3, 9):
def __class_getitem__(cls, item: Any) -> GenericAlias: ...
PythonUsage
enumerate() adds a counter to an iterable. The iterable can be a string, list, tuple, or dictionary.
enumerate() returns an “enumerate” object, that produces an index/serial and value pair while iterating over it. This way we can track the position of the item and value at the same time.
Here are some common usage of enumerate()-
big_box_list = ["big", "box", "code"]
# enumerate over the list
for i, item in enumerate(big_box_list):
print(i, item)
# enumerate over the list, and start the counter from 1
for i, item in enumerate(big_box_list, start=1):
print(i, item)
big_box_str = "My test str"
# enumerate over a string
for i, ch in enumerate(big_box_str):
print(i, ch)
big_box_dict = {"first": 100, "second": 200, "third": 300}
# enumerate over a dictionary
for i, (key, value) in enumerate(big_box_dict.items()):
print(f"counter: {i}, key: {key}, value: {value}")
# enumerate over the lines froma file
with open("sample.txt", "r") as file:
for line_number, line in enumerate(file, start=1):
print(f"Line {line_number}: {line.strip()}")
PythonOutput:
0 big
1 box
2 code
1 big
2 box
3 code
0 M
1 y
2
3 t
4 e
5 s
6 t
7
8 s
9 t
10 r
counter: 0, key: first, value: 100
counter: 1, key: second, value: 200
counter: 2, key: third, value: 300
Line 1: d41d8cd98f00b204e9800998ecf8427e
Line 2: 098f6bcd4621d373cade4e832627b4f6
Line 3: 5d41402abc4b2a76b9719d911017c592
Line 4: e99a18c428cb38d5f260853678922e03
Line 5: 9a1158154dfa42caddbd0694a4e9bdc8
PlaintextParameters
Param Name | Type | Description |
---|---|---|
iterable | Iterable[_T] | Any iterable in Python, like – string, tuple, list, dictionary, etc. |
start | int | From which number the counter starts |
Return Value
Type | Description |
---|---|
enumerate | An instance/object of “enumerate” class. |
Problem without enumerate()
If we want a counter while iterating over an iterator in Python, we can do it like the code below.
big_box_list = ["big", "box", "code"]
for i in range(len(big_box_list)):
print(i, big_box_list[i])
PythonOutput:
0 big
1 box
2 code
PlaintextHowever, the code is not easy to read, and often needs some extra care and maintenance.
Examples
Let’s take a look at some examples to understand how enumerate() can help us to simplify the code, when we need it-
Example #1: enumerate() Over a List
enumerate provides an easy-to-read and maintain code, by providing a counter/serial/index over the items of an iterable.
Check the code below-
big_box_list = ["big", "box", "code"]
for i, item in enumerate(big_box_list):
print(i, item)
PythonOutput:
0 big
1 box
2 code
PlaintextExample #2: enumerate() With Custom Start
The counting starts from Zero(0) by default, but we can pass the “start” parameter value to start from any number we want-
big_box_list = ["big", "box", "code"]
# Pass the "start" param value
for i, item in enumerate(big_box_list, start=1):
print(i, item)
PythonOutput:
1 big
2 box
3 code
PlaintextExample #3: enumerate() Returns “enumerate” Object
Let’s check the returned value when we call enumerate().
big_box_list = ["big", "box", "code"]
print(enumerate(big_box_list))
print(type(enumerate(big_box_list)))
PythonOutput:
<enumerate object at 0x7f9f16d81980>
<class 'enumerate'>
PlaintextExample #4: Use next() to Get Next Item
We can use the next() function to get the next item from an enumerate object-
big_box_list = ["big", "box", "code"]
enumerated_obj = enumerate(big_box_list)
next_item = next(enumerated_obj)
print(next_item)
next_item = next(enumerated_obj)
print(next_item)
PythonOutput:
(0, 'big')
(1, 'box')
PlaintextExample #5: Convert enumerate Object
We can convert the enumerate object to a list, dictionary, or set-
big_box_list = ["big", "box", "code"]
print(list(enumerate(big_box_list)))
print(dict(enumerate(big_box_list)))
print(set(enumerate(big_box_list)))
PythonOutput:
Here is what we get when an enumerate object is converted to other types-
[(0, 'big'), (1, 'box'), (2, 'code')]
{0: 'big', 1: 'box', 2: 'code'}
{(1, 'box'), (2, 'code'), (0, 'big')}
PlaintextExample #6: enumerate() Over a String
If we enumerate over a string, then we get the index/counter and single characters of the string-
big_box_str = "My test str"
for i, ch in enumerate(big_box_str):
print(i, ch)
PythonOutput:
0 M
1 y
2
3 t
4 e
5 s
6 t
7
8 s
9 t
10 r
PlaintextExample #7: enumerate() Over a Dictionary
If we enumerate over a dictionary, we get the index and a tuple of key/value pairs. We can print all the information like below-
big_box_dict = {"first": 100, "second": 200, "third": 300}
for i, (key, value) in enumerate(big_box_dict.items()):
print(f"counter: {i}, key: {key}, value: {value}")
PythonOutput:
counter: 0, key: first, value: 100
counter: 1, key: second, value: 200
counter: 2, key: third, value: 300
PlaintextExample #8: enumerate() Over the Lines of File
We can read a file, and enumerate over the lines we get after reading.
Here is a sample file. We have named it “sample.txt”-
d41d8cd98f00b204e9800998ecf8427e
098f6bcd4621d373cade4e832627b4f6
5d41402abc4b2a76b9719d911017c592
e99a18c428cb38d5f260853678922e03
9a1158154dfa42caddbd0694a4e9bdc8
098f6bcd4621d373cade4e832627b4f6
1a79a4d60de6718e8e5b326e338ae533
d3d9446802a44259755d38e6d163e820
72b302bf297a228a75730123efef7c41
098f6bcd4621d373cade4e832627b4f6
PlaintextAfter reading the file, we can use enumerate() over the file object, and get the serial(line) numbers-
with open("sample.txt", "r") as file:
print("Type of file is: ", type(file))
print(f"Here are the lines from {file.name}-")
for line_number, line in enumerate(file, start=1):
print(f"Line {line_number}: {line.strip()}")
PythonOutput:
Type of file is: <class '_io.TextIOWrapper'>
Here are the lines from sample.txt-
Line 1: d41d8cd98f00b204e9800998ecf8427e
Line 2: 098f6bcd4621d373cade4e832627b4f6
Line 3: 5d41402abc4b2a76b9719d911017c592
Line 4: e99a18c428cb38d5f260853678922e03
Line 5: 9a1158154dfa42caddbd0694a4e9bdc8
Line 6: 098f6bcd4621d373cade4e832627b4f6
Line 7: 1a79a4d60de6718e8e5b326e338ae533
Line 8: d3d9446802a44259755d38e6d163e820
Line 9: 72b302bf297a228a75730123efef7c41
Line 10: 098f6bcd4621d373cade4e832627b4f6
PlaintextNOTES
The source code of the implementation can be found in the following file, CPython source code-
Objects/enumobject.c