
Iterate a Python list and get the index and value
You can get indices and values of a list in for loop using Python built-in enumerate()
.
a = ['sun', 'earth', 'moon']
for index, value in enumerate(a):
print(index)
print(value)
# 0
# sun
# 1
# earth
# 2
# moon
If not using enumerate
, only items are printed in order.
a = ['sun', 'earth', 'moon']
for i in a:
print(i)
# sun
# earth
# moon
Items of an enumerate object
a = ['sun', 'earth', 'moon']
b = enumerate(a)
print(b) # <enumerate object at 0x117736140>
for i in b:
print(i)
print(type(i))
# (0, 'sun')
# <class 'tuple'>
# (1, 'earth')
# <class 'tuple'>
# (2, 'moon')
# <class 'tuple'>
The enumerate()
returns a enumerate object that can be iterated. Each item of it is a tuple of index and value.
Comments
Powered by Markdown