To enumerate a list in Python, we can use the built-in enumerate()
function, which returns an iterator that yields pairs of elements and their index in the list. Here's an example:
main.py94 chars4 lines
Output:
main.py26 chars4 lines
In the above example, we first create a list my_list
with three elements. We then use a for
loop to iterate over the list using enumerate(my_list)
as the iterable. In each iteration, we unpack the pair of the current index i
and the current element item
using i, item = ...
. Finally, we print both the index and the element on a separate line inside the loop body.
gistlibby LogSnag