How to Manually Iterate Through a List in Python



Python


In this article, we show how to manually iterate through a list in Python.

Usually when you are iterating through a list or any other data object in Python, you would use a for loop, which is the most common way to iterate through a list.

However, you can also do this manually.

Python has a built-in iterator that allows us to iterate through items without a for loop. Using the next() function, we can iterate, one by one, manually, through a list.

This is shown in the following code below.



So you can see that we have a list, items, which contains 3 items: 10,20,30.

We create a variable, it, which we set equal to, iter(items)

This gets and sets up the iterator to have the items in the variable items.

We are now set to iterate through the items manually using the next() function.

When we initially use the next() function, 10 is returned, the first item in the list.

Using the next() function again returns the second item, which is 20.

Using the next() function again returns the third item, which is 30.

Using the next() function again returns an error, since there are no more items in the list to iterate through.

StopIteration is used to signal the end of iteration.

And this is how you can manually iterate through a list in Python.


Related Resources

How to Randomly Select From or Shuffle a List in Python



HTML Comment Box is loading comments...