This article shows how to use enumerate() function.
Contents
- What is enumerate function?
- Basic usage of enumerate function
- Start index from 1 (non-zero)
sponsored link
What is enumerate function?
In the beginning, I explain briefly enumerate( ) function.
The enumerate() function is built-in function in Python.
So, We can use enumerate( ) function without "import".
By using the enumerate( ) function, the elements and indices of iterable objects (such as list, tuple, etc.) are got simultaneously.
The enumerate( ) function is often used with the "for loop".
Basic usage of enumerate function
I show basic usage of enumerate( ) function.
The enumerate( ) function takes iterables (such as list, tuple, etc.) as the arguments.
If you want the beginning of the index to be non-zero, specify the argument "start".
The argument "start" is optional.
How to write
enumerate( iterator, start = "number" )
Here is an example code.
fruits = ['Apple', 'Banana', 'Orange', 'Grape', 'Lemon']
fruits_enumerate = enumerate(fruits)
print(fruits_enumerate)
# <enumerate object at 0x0000023459307708>
print(list(fruits_enumerate))
# [(0, 'Apple'), (1, 'Banana'), (2, 'Orange'), (3, 'Grape'), (4, 'Lemon')]
> print(fruits_enumerate)
> # <enumerate object at 0x0000023459307708>
An enumerate object is generated.
> print(list(fruits_enumerate))
Since the elements cannot be checked as an enumerate object, they are converted to list type with the list( ) function.
The indices and elements are stored in the tuples.
sponsored link
Use the enumerate( ) function with "for loop"
The enumerate( ) function is often used with "for loop".
Here is an example code.
fruits = ['Apple', 'Banana', 'Orange', 'Grape', 'Lemon']
for i, fruit in enumerate(fruits):
print(i, fruit)
# 0 Apple
# 1 Banana
# 2 Orange
# 3 Grape
# 4 Lemon
By using the enumerate( ) function, the indices and elements are passed to the variable i and fruit.
Start index from 1 (non-zero)
If you want the beginning of the index to be non-zero, specify the argument "start".
Here is an example code.
fruits = ['Apple', 'Banana', 'Orange', 'Grape', 'Lemon']
for i, fruit in enumerate(fruits, start=1):
print(i, fruit)
# 1 Apple
# 2 Banana
# 3 Orange
# 4 Grape
# 5 Lemon
sponsored link