To demonstrate how to iterate through a list in Python, we’ll look at an example. In its most basic form, a Python List is an ordered data structure that allows us to store and manipulate the data contained within it.
As shown in the following table, there are seven different ways to iterate through each element of a Python List.
- Using the range() function in Python.
- With the help of a for Loop.
- Using While Loop.
- Using List Comprehension Method.
- Using enumerate() method in Python
- Using the NumPy module in Python.
1. Using The range() To Iterate Through A List In Python
To traverse and iterate over a list in Python, the range() method, in conjunction with a for loop, can be used to accomplish this.
With the range() method, you can get a sequence of integers back, which means that it builds/generates a sequence of integers from the start index you provide up to the end index you specify in the parameter list.
range(start, stop, step) where: start = When this parameter is specified, it is used to specify the starting value/index for the sequence of integers that will be generated. stop = For the sequence of integers to be generated, this parameter is used to provide the end value/index for the sequence of integers. step = This is the optional parameter, It contains information about the difference between each integer in the sequence that is to be generated.
Integers are generated from the start value to the end/stop value using the range() function. The end value, however, is not included in the sequence, i.e. it does not include the stop number/value in the resultant sequence.
#Initializing List with Values numList = [1,2,3,4,5,6] for idx in range(len(numList)): print(numList[idx])
1 2 3 4 5 6
The list is iterated in the above snippet of code by using the range() function, which traverses through 0(zero) to the length of the list that has been defined previously.
2. Iterate Through A List In Python Using For Loop
In Python, you can simply use a for loop to iterate over any type of list. Let us see in the below code example usage of For Loop to traverse through a list.
#Initializing List with Values inputList = ["A", "B", "C", "D"] for item in inputList: print(item, end=' ')
A B C D
As shown in the preceding code, Python does not require an explicit add index to retrieve an item from a list. You can simply use the for loop to iterate through all of the elements in the list.
3. Using While Loop To Traverse Through A List
Similar to for loops, the Python while loop can be used to iterate through a list like that of for loops. Let us see the below example code for usage of while loop to iterate a list in Python.
#Initializing List with Values inputList = [5,6,7,8,9,20] #Initializing The Index idx = 0 #Making Sure that Index is less than #Length Of The List while idx < len(inputList): print(inputList[idx], end=' ') idx += 1
5 6 7 8 9 20
4. Using List Comprehension Method
A list comprehension function in Python is an indifferent way of generating a list of elements that possess a specific property or specification, i.e. it can determine whether the input is a list, string, tuple, or another type of data.
#Initializing List with Values inputList = [12,13,14,15,16] #Using list Comprehension Method [print(num, end=' ') for num in inputList]
12 13 14 15 16
5. Using enumerate() Method
The enumerate() function in Python can be used to iterate through a list more efficiently. By calling the enumerate() function, you can add an item to a list or any other iterable and have that item returned as an enumerate object by the function.
As a result, it reduces the overhead associated with maintaining a count of the elements during the iteration operation. Let us see in the below example code the usage of enumerate() function to traverse through the list.
#Initializing List with Values inputList = [21,22,23,24,25] #Using enumerate Function for idx, num in enumerate(inputList): print(idx, " -> ", num)
0 -> 21 1 -> 22 2 -> 23 3 -> 24 4 -> 25
6. Using NumPy To Iterate Through A List In Python
NumPy Arrays in Python can also be used to efficiently iterate through a list of items. The numpy.arange() function in Python creates a sequence of integers that are all the same size.
numpy.arange(start, stop, step) where: start = When using this parameter, you can specify the starting value/index for the sequence of integers that will be generated. stop = This parameter is used to specify the end value/index for the sequence of integers that will be generated. step = This is optional Parameter, It contains information about the difference between each integer in the sequence that is to be generated.
When we call
numpy.nditer(numpy array), we are provided with an iterator that can be used to traverse through the NumPy collection of elements.
#importing NumPy Library import numpy as np #Initializing List with Values inputList = np.arange(2,20,2) #Iterating Through Input List for num in np.nditer(inputList): print(num, end=' ')
2 4 6 8 10 12 14 16 18
I hope you were able to grasp the various approaches to traversing through a list that Python provides you with. I’ve compiled a list of nearly six methods that you can incorporate into your code.
Please let me know in the comments section if you believe there are any additional methods that should be included, and I will be happy to include them.