OKPEDIA PYTHON LISTA EN

How to convert a list to an iterator in Python

To convert a list to an iterator in python, use the function iter()

iteratore=iter(lista)

The input argument is a list or an iterable object.

The iter() function transforms the list into an iterator.

Note. Once transformed into an iterator, the elements of the iterable can be read using the next() method.

Example

Given the following list consisting of four items

>>> list1=["A","B","C","D"]

Convert list to iterator using iter() function.

>>> list2=iter(list1)

Then, read the iterator elements one by one with the function next().

>>> next(list2)
A
>>> next(list2)
B
>>> next(list2)
C
>>> next(list2)
D

Items are read one at a time.

Each single instance returns an element in progressive order.

Note. After the last element in the list, a further next() instance causes a StopIteration error

https://how.okpedia.org/en/python/how-to-convert-a-list-to-an-iterator-in-python


Report an error or share a suggestion to enhance this page


Python List


FacebookTwitterLinkedinLinkedin