python a simple way to get list subscripts and their values

  • 2020-05-10 18:29:07
  • OfStack

When traversing a sequence in python, we usually use the following method:


for item in sequence:
    process(item)

If you want to get to an item location, you can write:


for index in range(len(sequence)):
    process(sequence[index])

Another good way is to use python's built-in enumerate function:


enumerate(sequence,start=0)

In the above functions, sequence is an iterable object, which can be a list, dictionary, file object, and so on. enumerate returns a tuple of subscripts and item:


>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons)) [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1)) [(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]

The first example of the article could then be written like this:


for index,item in enumerate(sequence):
    print index,item

Related articles: