A list is a container for homogeneous elements in Python. It is a mutable data structure. The list is just like arrays, but it provides dynamic size. The elements are ordered in the list and have absolute count, unlike sets. Lists allow for manipulating the stored data.
There are various ways to iterate over a list item. Selecting one specific technique depends on the performance and personal preference.
This article will discuss how to iterate over a list in Python with the help of 7 different methods including built-in functions and much more. For better understanding, the methods will be explained with example code snippet and output.
The following methods can be used to iterate/traverse a list in Python.
Table of Contents
1. For Loop
We can iterate list items by using the traditional For-in loop. It is the easiest way of list iteration.
mylist = [ 2, 4, 6, 8, 10 ] for x in mylist: print(x)
2. While Loop
mylist = [ 2, 4, 6, 8, 10 ] length = len(mylist) x = 0 while x < length: print(mylist[x]) x += 1
3. List Comprehension
It is one single-line method to do the list iteration. List Comprehension generates a list of items that has a specific property or specification. It can identify the type of data structure as well. And it is one of the most concrete ways.
mylist = [ 2, 4, 6, 8, 10 ] [print(x) for x in mylist]
4. Range( ) Method
Range function is used with the for loop to iterate over a list in Python. It provides access to an index while iterating a list of elements with loop counter. The code example for range method is as follows.
mylist = [ 2, 4, 6, 8, 10 ] length = len(mylist) for x in range(length): print( mylist[x])
5. Lambda Function
Lambda functions are also known as anonymous function. We use the Python map() function and the lambda function to iterate over a list in Python.
mylist = [ 2, 4, 6, 8, 10 ] items = list(map(lambda x:x, mylist)) print(items)
Numpy is an external library used for Numpy Arrays. For huge lists containing n-dimensions, just like image array, we will better use the Numpy library. The basic syntax is given as follows to import Numpy module and use for list iteration.
import numpy myarray = numpy.arange(16) myarray = myarray.reshape(4, 4) for x in numpy.nditer(myarray): print(x)
7. Enumerate( ) Method
Enumerate( ) function is used to convert the list into an iterables list of tuples. It adds the counter to the list and reduces the overhead of remembering count during iteration. Enumerate object is an optimized solution.
mylist = [ 2, 4, 6, 8, 10 ] for x, index in enumerate(mylist): print (x, "," ,index)
The techniques discussed in the article are there to simplify the development process. In the article, we have covered the seven distinct ways to iterate over a list in Python. I hope the example codes are helpful for the proper understanding of each method.