-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!!!

1
  • 1
    Why do you think i is an index? It isn't. It is an item in the list. Commented Jun 10, 2022 at 4:14

1 Answer 1

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)
    ...
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.