The enumerate() function is a built-in function in Python that allows you to iterate over a sequence and keep track of the index of the current item. Here are some tips for using enumerate() to write efficient code:
enumerate() with for loops: Instead of using a counter variable to keep track of the index in a for loop, use enumerate() to get both the index and the value of each item in the sequence.Example:
# Inefficient codemy_list = ['apple', 'banana', 'orange']for i in range(len(my_list)): print(i, my_list[i])# Efficient codemy_list = ['apple', 'banana', 'orange']for i, item in enumerate(my_list): print(i, item) |
enumerate() with list comprehensions: List comprehensions can also make use of enumerate() to create a list of tuples containing the index and value of each item.Example:
# Inefficient codemy_list = ['apple', 'banana', 'orange']new_list = []for i in range(len(my_list)): new_list.append((i, my_list[i]))# Efficient codemy_list = ['apple', 'banana', 'orange']new_list = [(i, item) for i, item in enumerate(my_list)] |
By using enumerate() efficiently in your code, you can make your code more readable and avoid unnecessary indexing operations.