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.
Enumerate () function in Python Picture 1
Enumerate () function syntax in Python
enumerate(iterable, start=0)
Parameters of the enumerate () function
- iterable: string, list, tuple, iterator or any object that supports iteration.
- 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 should read it
- The oct () function in Python
- The map () function in Python
- The function set () in Python
- Zip () function in Python
- The next () function in Python
- Max () function in Python
- The reversed () function in Python
- Help () function in Python
- The ord () function in Python
- All () function in Python
- The float () function in Python
- The function id () in Python