In the following article, let's look at what is an iterator in Python. Find out
What isPython
iterators, and what the Python iterator can do in Python programming.
What is a Python iterator
Iteration is one of the most powerful features of Python and is a way to access the elements of a collection.
An iterator is an object that remembers where to traverse.
The iterator object is accessed from the first element of the collection until all of the elements have been accessed and finished. Iterators can only move forward without backing back.
Iterators have two basic methods: ITER () and next ().
A string, list, or tuple object can be used to create an iterator:
>>>list=[1,2,3,4]>>> it = iter (list) # Create iterator object >>> print (next (it)) # Output iterator next element 1 >>> Print (Next (IT)) 2>>>
An iterator object can be traversed using a regular for statement:
#!/usr/bin/python3 list=[1,2,3,4]it = iter (list) # Create iterator object for x in it: print (x, end= "")
Execute the above procedure, the output result is as follows:
1 2 3 4
You can also use the next () function:
#!/usr/bin/python3 Import SYS # introduces the SYS module LIST=[1,2,3,4]IT = iter (list) # creates an iterator object while True: try: print ( Next (IT)) except stopiteration: sys.exit ()
Execute the above procedure, the output result is as follows:
1234