Python enumerate() Built in Function

Python enumerate() is a built-in function that returns an enumerate object. It allows you to loop over a collection (such as a list, tuple, string, etc.) and keep track of the index and value of each element. You can use it in for loops or convert it to a list or dictionary.

Here are some examples of how to use Python enumerate():

To print the index and value of each element in a list:

Iterate over a list and print the index and value of each item:

fruits = ['apple', 'banana', 'cherry']

for index, fruit in enumerate(fruits):
    print(index, fruit)

Output:
0 apple
1 banana
2 cherry
0 apple
1 banana
2 cherry

In this example, enumerate(fruits) returns an iterator that produces tuples containing the index and value of each item in the list. We use a for loop to iterate over this iterator and print the index and value of each item.

Create a dictionary that maps the index of each word in a list to the word itself:

words = ['foo', 'bar', 'baz']

word_dict = {index: word for index, word in enumerate(words)}

print(word_dict)

Output: {0: 'foo', 1: 'bar', 2: 'baz'}

In this example, we use a dictionary comprehension to create a new dictionary that maps the index of each word in the list to the word itself. We use enumerate(words) to get an iterator that produces tuples containing the index and value of each item in the list, and then use a comprehension to construct the dictionary.

Find the index of the first occurrence of a value in a list:

fruits = ['apple', 'banana', 'cherry']

index = next(i for i, fruit in enumerate(fruits) if fruit == 'banana')

print(index)

Output: 1

In this example, we use a generator expression inside the next() function to find the index of the first occurrence of the value 'banana' in the list. The enumerate(fruits) function produces an iterator that yields tuples containing the index and value of each item in the list. We use a generator expression to iterate over this iterator and filter out tuples where the value is not 'banana', and then use next() to get the first remaining tuple (which contains the index we're looking for).

grocery = ['bread', 'milk', 'butter']
for index, item in enumerate(grocery):
    print(index, item)

Output:
0 bread
1 milk
2 butter

To change the default starting index of 0 to 10:

grocery = ['bread', 'milk', 'butter']
for index, item in enumerate(grocery, 10):
    print(index, item)

Output:
10 bread
11 milk
12 butter

To create a dictionary from a list using enumerate():

grocery = ['bread', 'milk', 'butter']
grocery_dict = dict(enumerate(grocery))
print(grocery_dict)

Output: {0: 'bread', 1: 'milk', 2: 'butter'}

If you have any questions about this code, you can drop a line in comment.

Comments

Popular posts from this blog

Python chr() Built in Function

Stock Market Predictions with LSTM in Python

Collections In Python

Python Count Occurrence Of Elements

Python One Liner Functions