How to Use Iterators in Python


In this example we will show how to use iterators in Python.

2. Tips

  • 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)

Output:

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)

Output:

1
2
3
4
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments