Printing list index using a "for" loop | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Printing list index using a "for" loop

cities=["city_0","city_1","city_2","city_3","city_4","city_5"] for i in cities: print(cities[i]" ") #prints the names of the destinations print(cities.index(cities[i])) #prints the index So I created a list of cities and I want to print the names of the cities and the index next to the name of each city. Is this the right way?? :/

2nd Jun 2017, 8:19 AM
Στέλλα Πασχάλη
Στέλλα Πασχάλη - avatar
2 Answers
+ 10
cities=["city_0","city_1","city_2","city_3","city_4","city_5"] for i in range(0,len(cities)): print(cities[i]) print(cities.index(cities[i])) #you want to do it with range of 0 to length of cities, as in the old one the i in cities[i] would be "city_0" instead of just the number 0. The " " was also unneeded.
2nd Jun 2017, 8:47 AM
Ahri Fox
Ahri Fox - avatar
+ 1
didn't think of using 'range()' thank you 😉
2nd Jun 2017, 11:08 AM
Στέλλα Πασχάλη
Στέλλα Πασχάλη - avatar