Enumeration

Sometimes, you want to keep the record of the iteration you're at while using an iterable. A naive approach would be to get the length of the iterable, use the range function, and then use each number to get values from the iterable—indeed, that is how loops work in other languages, such as Java and JavaScript. But don't do that! Indeed, this construct requires two function calls in its basic case, and more if we need to numerate iterations, starting from a number other than zero. In Python, there is a better solution! Just use enumerate—this will create a generator that will return an index and a corresponding value from the original iterable, as a tuple. This can be used even if you had tuples already—just use parentheses for the unpacking. Here is an illustration using the person data structure. All we need is to run the enumerator over our iterable. In this case, the iterable contains a number of key-value pairs as tuples. In order to name them, we unpack values, describing the entire composition after the for keyword; here, i is the index generated by the enumerate function, while k and v are the key-value pair. Number 1 in the enumerator indicates the beginning of the enumeration:

>>> person = { 'name':'Jim', 'surname':'Hockins'}
>>> for i, (k, v) in enumerate(person.items(), 1):
>>> print(f'{i}. {k}: {v}')

1. name : Jim
2. surname L Hockins

With that, we can use each element by its name within the loop—in our case, we use this to format each line properly.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset