-5

I'm trying to sort my confusions learning python.

>>> cities = ['London', "Toronto", 'Paris', 'Oslo']
>>> cities
['London', 'Toronto', 'Paris', 'Oslo']
>>> for i in cities:
...     print(i)
... 

London Toronto Paris Oslo

>>> for i in cities:
...     print(cities[i])
... 

Traceback (most recent call last): File "", line 2, in TypeError: list indices must be integers or slices, not str

>>> cities[0]
'London'

In the loop, it refuses the index, but outside of the loop, it seems to accept. Confused!!!

Master_Roshy
  • 1,245
  • 3
  • 12
  • 19

1 Answers1

0

When you normally loop over the list, the iterated item is the element of it. When you want to get index, then you need to use enumerate function.

for index, item in enumerate(cities):
    # here the `index` is the index, item is the element
    print(cities[index])
    print(item)
    ...
Metalgear
  • 3,391
  • 1
  • 7
  • 16