1、enumerate
Add a subscript to a traversable object , Combine into a new sequence
enumerate(sequence , [start = 0])
for example :
seasons = ['Spring', 'Summer', 'Fall', 'Winter']
for i,j in enumerate(seasons,start = 1):
print(i,j)
Output :
1 Spring
2 Summer
3 Fall
4 Winter
Is to add a subscript to each item of a traversable sequence , Then form a tuple , And form a new sequence .
2、 iterator iter()
Iteration is a way to access collection elements , Can remember the traversal location of the object , Access... From the first element of the collection , Until all elements are accessed . Iterators can only move forward and not backward .
There are two basic ways to iterator :iter() and next().
character string , List or tuple objects can be used to create iterators .
iter(object[, sentinel])
Parameter Introduction :
object: A collection of objects that support iteration .
sentinel -- If the second argument is passed , The parameter object Must be a callable object ( Such as , function ).
here ,iter An iterator object is created , Each time this iterator object is called __next__() When the method is used , Will be called object.
for example :
lst = [1,2,3,4]
for i in iter(lst):
print(i)
Output :
1
2
3
4
Use next Method
x = iter(lst)
print(next(x))# Output 1
print(next(x))# Output 2
print(next(x))# Output 3
# In fact, the execution process of the iterator can be regarded as the traversal of a single linked list .