How to iterate over the content of a list in Python

Let’s say that you need to iterate over the content of a list. In order to do that you need to use the iter function that allows you to get access to the associated iterator.

>>> list_one = [1, 2, 3, 4]
>>> iterator_one = iter(list_one)
>>> iterator_one

Now, you can use this new iterator object using the classic iterator technique.

>>> next(iterator_one)
1
>>> next(iterator_one)
2
>>> next(iterator_one)
3
>>> next(iterator_one)
4

Of course, once you empty the iterator you will get an exception raised.

>>> next(iterator_one)
Traceback (most recent call last):
  File "C:\Program Files (x86)\gedit\lib\gedit-2\plugins\pythonconsole\console.py", line 332, in __run
    r = eval(command, self.namespace, self.namespace)
  File "", line 1, in 
StopIteration

Leave a Reply