Search code examples
pythonpython-3.xlistindices

How do indices work in a list with duplicates?


I'm trying to understand how lists and indices work in python.

So I tried this code to print every item in a list and its corresponding index in the list:

tokens = ["and", "of", "then", "and", "for", "and"]
for word in tokens:
    word_index = tokens.index(word)
    print(word_index, word)

It gives me this output:

0 and
1 of
2 then
0 and
4 for
0 and

So my question is why "and" here always have the same index of 0 instead of 0, 3, 5? (and how do I get the desired output).

0 and
1 of
2 then
3 and
4 for
5 and

Solution

  • My question is why "and" here have the same index of 0 instead of 0, 3, 5?

    Why

    It's because list.index() returns the index of the first occurrence, so since "and" first appears in index 0 in the list, that's what you'll always get.

    Solution

    If you want to follow the index as you go try enumerate()

    for i, token in enumerate(tokens):
        print(i, token)
    

    Which gives the output you want:

    0 and
    1 of
    2 then
    3 and
    4 for
    5 and