What is enumerate() function in python
The enumerate() function returns the length of an iterable and loops through its items simultaneously. Thus, while printing each item in an iterable data type, it simultaneously outputs its index.
Assume that you want a user to see the list of items available in your database. You can pass them into a list and use the enumerate() function to return this as a numbered list.
Here's how you can achieve this using the enumerate() method:
Whereas, you might've wasted valuable time using the following method to achieve this:
In addition to being faster, enumerating the list lets you customize how your numbered items come through.
In essence, you can decide to start numbering from one instead of zero, by including a start parameter:
Output:
The enumerate() function returns the length of an iterable and loops through its items simultaneously. Thus, while printing each item in an iterable data type, it simultaneously outputs its index.
Assume that you want a user to see the list of items available in your database. You can pass them into a list and use the enumerate() function to return this as a numbered list.
Here's how you can achieve this using the enumerate() method:
fruits = ["grape", "apple", "mango"]
for i, j in enumerate(fruits):
print(i, j)
Output:
0 grape
1 apple
2 mango
Whereas, you might've wasted valuable time using the following method to achieve this:
fruits = ["grape", "apple", "mango"]
for i in range(len(fruits)):
print(i, fruits[i])
In addition to being faster, enumerating the list lets you customize how your numbered items come through.
In essence, you can decide to start numbering from one instead of zero, by including a start parameter:
for i, j in enumerate(fruits, start=1):
print(i, j)
Output:
1 grape
2 apple
3 mango
👍16