Python iterator...LOGIN

Python iterators

The above briefly introduces iteration. Iteration is one of the most powerful functions of Python and is a way to access collection elements. Now officially enter the topic: iterator, iterator is an object that can remember the position of traversal.

The iterator object starts accessing from the first element of the collection until all elements have been accessed.

The iterator can only go forward and not backward.

Iterators have two basic methods: iter() and next(), and string, list or tuple objects can be used to create iterators. Iterator objects can be traversed using regular for statements. You can also use the next() function to traverse.

Specific example:

# 1、字符创创建迭代器对象
str1 = 'liangdianshui'
iter1 = iter ( str1 )
# 2、list对象创建迭代器
list1 = [1,2,3,4]
iter2 = iter ( list1 )
# 3、tuple(元祖) 对象创建迭代器
tuple1 = ( 1,2,3,4 )
iter3 = iter ( tuple1 )
# for 循环遍历迭代器对象
for x in iter1 :
    print ( x , end = ' ' )
print('\n------------------------')
 
# next() 函数遍历迭代器
while True :
    try :
        print ( next ( iter3 ) )
    except StopIteration :
        break

The final output result:

l i a n g d i a n s h u i 
------------------------
1
2
3
4
Next Section
submitReset Code
ChapterCourseware