5-1, iterator

Iterator

Iteration is one of the most commonly used features for accessing elements such as lists, dictionaries, strings, and tuples. Iterations access from the first element to the last element in sequence. (You can't run backwards) Iteration has two basic functions: iter () and next ().

>>> data=["a","b","c","d"]
>>> it = iter(data)
>>> print (next(it))  
1
>>> print (next(it))
2
>>>

How to use

Normally, the for statement is used.

data=["a","b","c","d"]
it = iter(data) 
for x in it:
    print (x)

Of course, you can also use the next () function.

import sys  
list=["a","b","c","d"]
it = iter(list)
while True:
    try:
        print (next(it))
    except StopIteration:
        sys.exit()

The output result is also the character strings a, b, c, d.

Table of contents: IT memos for non-IT industries

Recommended Posts

5-1, iterator
Iterator in MySQLdb
Iterator pattern in Java
What is an iterator?