enumerate() method in Python

enumerate() method adds a counter to an iterable and returns it in a form of enumerating object. This enumerated object can then be used directly in for loops.

A below working example is based on this example which finds the first occurence of a number in a list using while loop. In this case we use for loop with enumerate() function:

from random import randint
l1 = [randint(1, 100) for num in range(1000)]
num_to_search = 65
for index, value in enumerate(l1):
  if value == num_to_search:
    print(f"{num_to_search} found at index {index}")
    break
Output:
65 found at index 81