- Ways to Iterate Through List in Python
- Upskill 2x faster with Educative
- 1. Iterate through list in Python using range() method
- 2. Iterate through list in Python using a for Loop
- 3. List Comprehension to iterate through a list in Python
- 4. Iterate through list in Python with a while loop
- 5. Python NumPy to iterate through List in Python
- 6. Python enumerate() method to iterate a Python list
- 7. Iterating a Python list using lambda function
- Conclusion
- References
- Using Step in a Slice
- To learn more in Python programming language click on the button below
- How to use Step in Slice?
- Advantages of using Step argument in Slice function
- Python Code to use Step argument in Slicing
Ways to Iterate Through List in Python
In this tutorial, we’ll go over how to iterate through list in Python. Python List is basically an ordered data structure which enables us to store and manipulate the data in it.
Either of the following ways can be referred to iterate over a list in Python:
Upskill 2x faster with Educative
Supercharge your skillset with Educative Python courses → use code: ASK15 to save 15%
1. Iterate through list in Python using range() method
Python’s range() method can be used in combination with a for loop to traverse and iterate over a list in Python.
The range() method basically returns a sequence of integers i.e. it builds/generates a sequence of integers from the provided start index up to the end index as specified in the argument list.
- start (upper limit): This parameter is used to provide the starting value/index for the sequence of integers to be generated.
- stop (lower limit): This parameter is used to provide the end value/index for the sequence of integers to be generated.
- step (optional): It provides the difference between each integer from the sequence to be generated.
The range() function generates the sequence of integers from the start value till the end/stop value, but it doesn’t include the end value in the sequence i.e. it doesn’t include the stop number/value in the resultant sequence.
lst = [10, 50, 75, 83, 98, 84, 32] for x in range(len(lst)): print(lst[x])
In the above snippet of code, the list is iterated using range() function which traverses through 0(zero) to the length of the list defined.
2. Iterate through list in Python using a for Loop
Python for loop can be used to iterate through the list directly.
for var_name in input_list_name:
lst = [10, 50, 75, 83, 98, 84, 32] for x in lst: print(x)
3. List Comprehension to iterate through a list in Python
Python List Comprehension is an indifferent way of generating a list of elements that possess a specific property or specification i.e. it can identify whether the input is a list, string, tuple, etc.
[expression/statement for item in input_list]
lst = [10, 50, 75, 83, 98, 84, 32] [print(x) for x in lst]
4. Iterate through list in Python with a while loop
Python while loop can also be used to iterate the list in a similar fashion as that of for loops.
while(condition) : Statement update_expression
lst = [10, 50, 75, 83, 98, 84, 32] x = 0 # Iterating using while loop while x < len(lst): print(lst[x]) x = x+1
5. Python NumPy to iterate through List in Python
Python NumPy Arrays can also be used to iterate a list efficiently.
Python numpy.arange() function creates a uniform sequence of integers.
Syntax for numpy.arange() function:
numpy.arange(start, stop, step)
- start : This parameter is used to provide the starting value/index for the sequence of integers to be generated.
- stop : This parameter is used to provide the end value/index for the sequence of integers to be generated.
- step : It provides the difference between each integer from the sequence to be generated.
The numpy.nditer(numpy_array) is a function that provides us with an iterator to traverse through the NumPy array.
import numpy as np n = np.arange(16) for x in np.nditer(n): print(x)
In the above snippet of code, np.arange(16) creates a sequence of integers from 0 to 15.
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
6. Python enumerate() method to iterate a Python list
Python enumerate() function can be used to iterate the list in an optimized manner.
The enumerate() function adds a counter to the list or any other iterable and returns it as an enumerate object by the function.
Thus, it reduces the overhead of keeping a count of the elements while the iteration operation.
enumerate(iterable, start_index)
- start_index : It is the index of the element from which the counter has to be recorded for the iterating iterable.
lst = [10, 50, 75, 83, 98, 84, 32] for x, res in enumerate(lst): print (x,":",res)
0 : 10 1 : 50 2 : 75 3 : 83 4 : 98 5 : 84 6 : 32
7. Iterating a Python list using lambda function
Python’s lambda functions are basically anonymous functions.
lambda parameters: expression
The lambda function along with a Python map() function can be used to iterate a list easily.
Python map() method accepts a function as a parameter and returns a list.
The input function to the map() method gets called with every element of the iterable and it returns a new list with all the elements returned from the function, respectively.
lst = [10, 50, 75, 83, 98, 84, 32] res = list(map(lambda x:x, lst)) print(res)
In the above snippet of code, lambda x:x function is provided as input to the map() function. The lambda x:x will accept every element of the iterable and return it.
The input_list (lst) is provided as the second argument to the map() function. So, the map() function will pass every element of lst to the lambda x:x function and return the elements.
Conclusion
In this article. we have unveiled the various techniques to iterate a Python List.
References
Using Step in a Slice
We can perform many operations on a list object Using Step in a Slice function in Python. Slice function is operable on list structures and it takes exactly 3 arguments where the 3rd argument is the step perimeter. Slicing on the string can be performed with or without using this argument.
To learn more in Python programming language click on the button below
How to use Step in Slice?
Slice function is no something like a built-in function it is just an operation performed on list structures or on the structures which are iterable. Some basic operations like printing a substring from a known starting point to an ending point, or printing the whole string starting after the specific index etc. It exactly takes Three arguments as follows:
- Start:- It is the first argument that we pass when we use the slice function. It takes the index from where you want to start printing or iterating the list or an iterable structure.
- Stop:- It is the second argument that we need to pass when we use the slice function over any list or iterable structure. It takes the ending point or the point up to where you want to access the element.
- Step:- It is the third argument that we pass while iterating through any list or iterable structure, which is also an optional argument. We will be understanding more about the argument in detail below.
Advantages of using Step argument in Slice function
Every operation we perform on some structure has some advantages Lets have a look at Some of the advantages of using step function in Python programming language.
- Easy to iterate over iterable structures.
- Reduces the complexity to perform some complex operations like reverse the list or string.
- Makes it easy to perform operations on elements in any sequence without using looping statements.
- It is an optional argument, so compiler never throws an error if we forget to pass the value.
Python Code to use Step argument in Slicing
#initialize a string arr = 'PrepInsta' #using step argument without start and stop #this will print the string as it is print(arr[::1]) #This will print the string in reverse order print(arr[::-1]) #This will print the string elements with even index print(arr[::2]) #This will print the string with odd indexes print(arr[::3]) #This will print the array element in reverse order with even indexes print(arr[::-2])
Output: PrepInsta atsnIperP PeIsa Pps asIeP
In the above code snippet, we have seen the usage of step argument without the rest two start and stop perimeter, Now let’s use step argument with all the perimeter.
#initialize a string arr = 'PrepInsta' #using step argument without start and stop #this will print the string as it is print(arr[0:9:1]) #This will print the string in reverse order #startring from the index 2 to ending point 6 ar = arr[2:7] print(ar[::-1]) #This will print the string elements with even index #Starting from 2 to 7 print(arr[2:8:2]) #This will print the string with odd indexes #Starting from index 1 to 6 print(arr[1:7:3]) #This will print the array element in reverse order with even indexes ar = arr[0:9] print(ar[::-2])
Output: PrepInsta snIpe eIs rI asIeP