How to iterate over a List in Python

python-how-to-iterate-over-list-tutorial-feature-image

In this tutorial, we’re gonna look at some ways to iterate over a List in Python.

Related Post: Python List functions

Iterate over Python List with for loop

for-in

This is the usual way to iterate over a List when we don’t care about item index:

for & range()

This way creates a range of our list, then we will iterate over list with index in the range. To get the actual item, we use list[index].

Iterate over Python List with while loop

With this way, first we get the size-of-list, then iterate using while loop from index 0 to size-of-list - 1.

Iterate over Python List with enumerate() built-in function

Using Python enumerate(list) built-in function, we can loop over a list with index & item value:

If we want to start counting at 1, just use start=1 option:

Iterate over multiple Python List with zip() built-in function

zip(list_1, list_2, ...) function takes multiple lists and returns an corresponding iterable:

If we use zip() function for multiple lists with different size, it will stop after running out of item of the shortest list.

Iterate over Python List with List Comprehension

The basic syntax is: [ expression for item in list if conditional ].



By grokonez | December 21, 2018.


Related Posts


Got Something To Say:

Your email address will not be published. Required fields are marked *

*