In this example, we will learn how to use iterators in Python.
- The iterator object visits from the first element of the collection until all elements have been visited.
- Iterators can only go forward from the beginning (it can not go backward).
- Iterators have two basic methods: iter() and next().
- Strings, lists, or tuple objects can be used to create an iterator.
2. Iter() Method
#! /usr/bin/env python3 # -*- coding: utf-8 -*- list = ['Jack', 'Male', 'Student', '23'] it = iter(list) for x in it: print(x)
Jack Male Student 23
3. Next() Method
#! /usr/bin/env python3 # -*- coding: utf-8 -*- list = [1, 2, 3, 4] it = iter(list) while True: try: print(next(it)) except StopIteration: exit(0)
1 2 3 4