Detailed explanation of using enumerate() function in python

1. Introduction to enumerate() function

enumerate() is python's built-in function, which converts a traversableiterable data object (such as list list, tuple tuple or str character String) is combined into an index sequence, listing data and data subscripts at the same time, generally used in for loops.
The function returns an enumerate object, which is an iterable object. Specific element values ​​can be retrieved through traversal.
The function syntax is:

Syntax: enumerate(sequence, [start=0])

Parameters
sequence -- A sequence, iterator, or other object that supports iteration.
start -- the starting position of the subscript.
Return value
Returns an enumerate object.

Function parameters are:

  • sequence is an iterable object
  • start is an optional parameter, indicating the index from which to start counting.

2. Use the enumerate() function

(1) Use for loop

1

2

3

4

1、迭代列表时如何访问列表下标索引

ll=[22, 36, 54, 41, 19, 62, 14, 92, 17, 67]

for i in range(len(ll)):

    print(i, "=", ll[i])

(2) Use enumerate()

1

2

3

# 优雅版:

for index,item in enumerate(ll):

    print(index, "=",item)

In addition, the enumerate() function has a second parameter that specifies the starting value of the index.

1

2

3

# 优雅版:

for index,item in enumerate(ll,10):

    print(index, "=",item)

Guess you like

Origin blog.csdn.net/jh035/article/details/128077895