One of the most powerful and useful features of Python is Iterators. Python Iterator is an object type that contains countable numbers or values with different types. An Iterator can be iterated forward and backward easily by using iterator methods.
Iterable Object Types (List, tuples, dictionaries, and sets)
Before starting Python iterators we should learn the basics about iterable objects. Python provides different object types which are iterable which means they can be iterated easily by using loops. These objects are list, tuple, dictionary, and sets. For example, just by using the for loop, a list can be iterated without extra effort by default.
names = ["ismail","ahmet","ali"]
for name in names:
print(name)
Iterating Methods and Keywords
Technically Python provides __iter()__
and __next()__
methods in order to implement iterators. As stated previously the list, tuple, dictionary, and set object types to provide these methods. Also, these objects have the iter()
method in order to get an iterator. The next()
method is used to jump the next value in the iterator and return it.
names = ["ismail","ahmet","ali"]
my_iterator = iter(names)
print(next(my_iterator))
print(next(my_iterator))
print(next(my_iterator))