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.

Enumerate () function in Python Picture 1

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

4 ★ | 2 Vote | 👨 183 Views
« PREV POST
NEXT POST »