The most straightforward answer to this is to use an enumerate class. A built-in class called enumerate accepts an iterable object as input and outputs an object that may be typecast into a list of tuples.
The syntax for the enumerate is as follows:
enumerate([“Apple”, “Orange”, “Mango”]) Output: [(0,”Apple”), (1,”Orange”), (2, “Mango”)]
So enumerate will give us a two dimensional (index, element) list and as we already know, using a for loop in Python, we can iterate through multidimensional lists as seen below.
fruits = [“Apple”, “Orange”, “Mango”] for index, fruit in enumerate(fruits): print(index, fruit)
Note: A further input argument called ‘start’ can be passed to enumerate. Start allows us to choose from where the index value should begin.
Example:
enumerate([“Apple”, “Orange”, “Mango”], start=5) Output: [(5,”Apple”), (6,”Orange”), (7, “Mango”)]