Enumerate () function in Python

In Python, the enumerate () function adds a counter before each iterable and returns the result as an enumerate object. The article will elaborate on the syntax, parameters and usage of the function. Invites you to read the track.

In Python, the enumerate () function adds a counter before each iterable and returns the result as an enumerate object. The article will elaborate on the syntax, parameters and usage of the function. Invites you to read the track.

Picture 1 of Enumerate () function in Python

Enumerate () function syntax in Python

 enumerate(iterable, start=0) 

Parameters of the enumerate () function

  1. iterable: string, list, tuple, iterator or any object that supports iteration.
  2. start: enumerate () starts the counter from this number. If the start parameter is omitted, 0 will be the default value assigned.

Value returned from enumerate ()

The enumerate () function adds a counter before each iterable and returns the result as a listed object. These enumerate objects can then be used directly in loops or converted into a list, a tuple by list () and tuple () methods .

Example 1: The enumerate () function works in Python

 cuahang = ['banhmi', 'sua', 'keo'] 
enumerateCuahang = enumerate(cuahang)

print(type(enumerateCuahang))

# chuyển đổi thành một danh sách
# viết bởi TipsMake.com
print(list(enumerateCuahang))

# bộ đếm chỉ định số bắt đầu
# viết bởi TipsMake.com
enumerateCuahang = enumerate(cuahang, 10)
print(list(enumerateCuahang))

Run the program, the result is:


[(0, 'banhmi'), (1, 'sua'), (2, 'keo')]
[(10, 'banhmi'), (11, 'sua'), (12, 'keo')]

Example 2: Loop on the enumerate object

 cuahang = ['banhmi', 'sua', 'keo'] 

for item in enumerate(cuahang):
print(item)

print('n')
for count, item in enumerate(cuahang):
print(count, item)

print('n')
# bộ đếm chỉ định số bắt đầu
# viết bởi TipsMake.com

for count, item in enumerate(cuahang, 100):
print(count, item)

Run the program, the result is:

 (0, 'banhmi') 
(1, 'sua')
(2, 'keo')


0 banhmi
1 sua
2 keo


100 banhmi
101 sua
102 keo

Previous lesson: divmod () function in Python

Next lesson: eval () function in Python

You've just finished reading the article "Enumerate () function in Python" edited by the TipsMake team. You can save enumerate-function-in-python.pdf to your computer here to read later or print it out. We hope this article has provided you with many useful tech tips and tricks. You can search for similar articles on tips and guides. Thank you for reading and for following us regularly.

« PREV The float () function in Python
NEXT » Iterator object in Python