Home > Article > Backend Development > Introduction to the usage of python function enumerate
The enumerate function is used to traverse the elements in the sequence and their subscripts.
Function prototype: enumerate(sequence, [start=0])
Function: List the sequence data separately starting the loopable sequence sequence with start and data subscript
That is, for a traversable data object (such as a list, tuple, or string), enumerate will combine the data object into an index sequence and list the data and data subscript at the same time.
There is a sequence, and using enumerate on it will get the following results:
start sequence[0]
start+1 sequence [1]
start+2 sequence[2]......
Python2.3+
Python2.x
Note: The start parameter has been added after python2.6
Return an enumerate object. sequence must be a sequence, an iterator, or some other object which supports iteration. The next() method of the iterator returned by enumerate() returns a tuple containing a count (from start which defaults to 0) and the values obtained from iterating over sequence.
The enumerate parameters are traversable variables, such as strings, lists, etc.; the return value is the enumerate class.
import string s = string.ascii_lowercase e = enumerate(s) print s print list(e)
The output is:
abcdefghij [(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'), (4, 'e'), (5, 'f'), (6, 'g'), (7, 'h'), (8, 'i'), (9, 'j')]
You can use enumerate when you need both index and value values.
In this example, line is a string containing 0 and 1. Find all 1s:
def xread_line(line): return((idx,int(val)) for idx, val in enumerate(line) if val != '0') print read_line('0001110101') print list(xread_line('0001110101'))
The above is the detailed content of Introduction to the usage of python function enumerate. For more information, please follow other related articles on the PHP Chinese website!