If you want to get the index number at the same time as iterating, use the enumerate function.
names = ["kero", "Fire", "FLOG", "GECO"]
for i, name in enumerate(names):
print(i, name)
0 kero 1 Fire 2 FLOG 3 GECO
for i, name in enumerate(names, 1):
print(i, name)
1 kero 2 Fire 3 FLOG 4 GECO
for i, name in enumerate(names, 10):
print(i, name)
10 kero 11 Fire 12 FLOG 13 GECO
You can iterate over multiple lists at the same time using the zip function.
names = ["kero", "Fire", "FLOG", "GECO"]
ages = [39, 21, 32, 45]
for age, name in zip(ages, names):
print("Name: {0} Age: {1}".format(name, age))
Name: kero Age: 39 Name: Fire Age: 21 Name: FLOG Age: 32 Name: GECO Age: 45
If the number of elements of each sequence object is different, it can be adjusted to a smaller number of elements.
names = ["kero", "Fire", "FLOG", "GECO"]
ages = [39, 21, 32]
for age, name in zip(ages, names):
print("Name: {0} Age: {1}".format(name, age))
Name: kero Age: 39 Name: Fire Age: 21 Name: FLOG Age: 32
data = { 'Flog':41, 'Geco':28, 'KERO':32 }
#List keys and values at the same time
for key, value in data.items():
print(key, value)
Flog 41 KERO 32 Geco 28
#Enumerate keys
for key in data.keys():
print(key)
Flog KERO Geco
#Enumerate values
for value in data.values():
print(value)
41 32 28
Recommended Posts