python How to Get the Subscript Position of Each Element in a List

  • 2021-07-06 11:11:32
  • OfStack

Git is one of the basic skills in programming. Almost all Internet companies use Git for collaborative programming. Yesterday, a Zen friend specifically told me on WeChat that I was just asked about Git during the interview on Friday. Fortunately, I learned it once in the past few days. Git is not difficult, but knowing Git can at least show that a person's learning ability or sense of smell for technology can keep up with the mainstream. If the interview asks you that you don't know what GitHub is, the interviewer will ask you a big question mark.

Briefly comment on this question.

When iterating through a list using an for loop, sometimes we need to get the subscript position of each element in the list, for example, numbers = [10, 29, 30, 41], requiring output (0, 10), (1, 29), (2, 30), (3, 41)

There are two main ways to realize this problem. The first way is to iterate the list subscript by obtaining the list length


for i in range(len(numbers)):
print('({0}, {1})'.format(i, numbers[i]))

The second method is to use the enumerate function directly:


numbers = [10, 29, 30, 41]
for index, value in enumerate(numbers):
print(index, value)

The latter is the more authentic writing. There is a motto in Python Zen: There should be on, and preferably ES29one, obvious way to do it. That is to say, when we write code, we should choose one and preferably only 11 obvious ways to realize it.

The built-in function enumerate can also receive a default parameter start, which is used to specify which number index starts from, and the default is 0. I don't know how many Zen friends know this usage. If you don't know, it is recommended that you know the official documents in more detail when you encounter new knowledge, instead of just tasting them. Learning to check documents is also a very important learning method. Document

Most of the codes submitted by everyone answered correctly, but there are also some problem codes, such as naming at will:


numbers = [10, 29, 30, 41]
for i, j in enumerate(numbers):
print(i, j)

It seems amateur to use meaningless names like i and j. Some people say that this is just practice, but if the practice is all like this attitude, it is hard to say that you can take a reasonable name at work.

There are Zen friends who use list factory function to return a new list, which is a bit gilding the lily, and it will take up more memory when iterating over an oversized list, because you have created a new list.


numbers = [10,29,30,41]
for i in list(enumerate(numbers)):
print(i,end=' ')

The winner belongs to the one who persists to the end


Related articles: