11 Powerful Methods to Iterate Through List in Python

Hello fellow programmers in today’s article we will learn how to iterate through the list in Python. We will discuss around 11 powerful ways to iterate or loop through the list using Python. You can choose the best method according to your need or efficiency of the process. So Let’s directly come to the point and begin the journey.

If you are new to the programming you might don’t know about the terms like iteration and lists. So for you let me explain these terms too in a very simple layman language.

Iteration: Frequently in an algorithm, a set of statements has to be executed over and over until a specific condition is met; this is where we find the need for iteration. The repeated execution of several groups of code statements within a program is known as iteration.

List: In Python programming, a list is produced by putting all of the items (components ) within square brackets [], separated by commas. It may have any number of things, and they might be of different types (integer, float, string, etc.). A list may also have a different list as a thing. This is referred to as a nested list.

Hope you understand what is a list and iteration in python. Let’s glance at 11 ways to Iterate Through List in Python which we are learning today.

Ways to Iterate Through List in Python

In this tutorial we will discuss in detail all the 11 ways to iterate through list in python which are as follows:

1. Iterate Through List in Python Using For Loop
2. Iterate Through List in Python Using While Loop
3. Iterate Through List in Python Using Numpy Module
4. Iterate Through List in Python Using Enumerate Method
5. Iterate Through List in Python Using List Comprehension
6. Iterate Through List in Python Using Loop and Range
7. Iterate Through List in Python Using Map and Lambda
8. Iterate Through List in Python Using Iter() and Next()
9. Iterate Through List in Python Using zip()
10. Iterate Through List in Python Using Itertool.Cycle
11. Iterate Through List in Python Using Itertools Grouper

1. Iterate Through List in Python Using For Loop

Doing iteration in a list using a for loop is the easiest and the most basic wat to achieve our goal. As you might discover this article using some search engine while finding the way to iterate through a list in Python. So I am assuming you already have basic knowledge of loops. So I am not demonstrating about for loops here.

Syntax

for variableName in listName:

Example

# Program to iterate through list using for loop 
list = [9, 11, 13, 15, 17, 19] 

# For Loop to iterate through list
for i in list: 
	print(i) 

Output

9
11
13
15
17
19

Explanation

In the above example program, we have first initialised and created a list with the name list itself. The list contains six elements in it which are [9, 11, 13, 15, 17, 19] respectively. And then we initialized a simple for loop in the list which will iterate through the end of the list and eventually print all the elements one by one. For printing in python, we simply use the print() function as you already know.

2. Iterate Through List in Python Using While Loop

The second method to iterate through the list in python is using the while loop. In while loop way of iterating the list, we will follow a similar approach as we observed in our first way, i.e., for-loop method. We have to just find the length of the list as an extra step.

Syntax

while(condition_to_be_checked) :
    Statement
        UpdationExpression

Example

# Program to loop through the list using while loop
list = [9, 11, 13, 15, 17, 19] 

# Finding length of the list
length = len(list) 
i = 0

# While Loop to iterate through list
while i < length: 
	print(list[i]) 
	i += 1

Output

9
11
13
15
17
19

Explanation

In the above example program, we have first initialised and created a list with the name list itself. The list contains six elements in it which are [9, 11, 13, 15, 17, 19] respectively. After that, we have to find the length of the list, finding the length of the list in while loop is important because we have to check the conditions. As you may already know while loop only loops through if the conditions are true. So that’s why we need to find the length of the list, in this case, the length is six so while loop will iterate six times. And we also have declared and initialized a variable ‘i’ with initial value ‘0’.

Coming to the while loop we have checked the condition which is true for the first time. As initially, the value of ‘i’ is ‘0’ and the length of the list is ‘6’. So it’s checking ‘0 < 6′ which is true so it will go inside the while loop and perform the statement. Here the statement to be performed is to print the first element of the list. After performing the statement it will move to the updation expression and follow the required step of incrementing by ‘1′.

The while loop will iterate until the condition become false. And we will finally achieve the iteration of the list in python.

3. Iterate Through List in Python Using Numpy Module

The third method to iterate through a list in Python is using the Numpy Module. For achieving our goal using this method we need two numpy methods which are mentioned below:

  1. numpy.nditer()
  2. numpy.arrange()

The iterator object nditer provides many flexible ways to iterate through the entire list using the numpy module. The function nditer() is a helper function that can be used from very basic to very advanced iterations. It simplifies some fundamental problems which we face in an iteration.

We also need another function to iterate through a list in Python using numpy which is numpy.arrange().
numpy.arange return evenly spaced values within a given interval. Values are generated within the half-open interval [start, stop) (in other words, the interval including start but excluding stop).

Syntax:

Syntax of numpy.nditer()

for val in np.nditer(numpy_array):
	Statemnet

Syntax of numpy.arrange()

([start, ]stop, [step, ]dtype=None)
  • start: The start parameter is used to provide the starting value of the array.
  • stop: This parameter is used to provide the ending value of the array.
  • step: It provides the difference between each array integer from the sequence to be generated.

Examples

Let’s see various ways to iterate through list using numpy module.

Example 1:

import numpy as np
 
x = np.arange(10)
 
  
for n in np.nditer(x): 
    print(n) 

Output

0
1
2
3
4
5
6
7
8
9

Explanation

In the above example 1 program the  np.arange(10) creates a sequence of integers from 0 to 9 and stores it in variable x. After that we have to run a for loop, and using this for loop and np.nditer(x) we will iterate through each element of the list one by one.

Example 2:

In this example we will iterate a 2d array using numpy module. To achieve our goal we need three functions here.

  1. numpy.arrange()
  2. numpy.reshape()
  3. numpy.nditer()
import numpy as np

a = np.arange(16) 
a = a.reshape(4, 4) 
for x in np.nditer(a): 
	print(x) 

Output:

0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

Explanation:

Most of the part of this example is similar to our first example except we added an extra function which is numpy.reshape(). The numpy.reshape() function is generally used to give shape to our array or list. Basically in layman language, it converts the dimensions of the array-like in this example we have used the reshape() function to make out numpy array a 2D array.

4. Iterate Through List in Python Using Enumerate Method

The fourth way in our list is iteration using the enumerate method. If you don’t know what enumerate exactly do in python, then let me explain to you.
The enumerate() method adds counter to an iterable and returns it. And whatever the enumerate method returns, it will be a enumerate object.

The main advantage of using the enumerate method is you can convert enumerate objects to list and tuple using the list() and tuple() method, respectively.

Syntax

enumerate(iterable, start=0)

enumerate() method takes two parameters:

  • iterable – a sequence, an iterator, or an object.
  • start (optional) – starts counting from this number. If start is omitted, 0 is taken as start.

Example

list = [10, 20, 30, 40, 50, 60, 70]
 
for i, res in enumerate(list): 
    print (i,":",res)

Output

0 : 10
1 : 20
2 : 30
3 : 40
4 : 50
5 : 60
6 : 70

Explanation

Here in this way to iterate list we have used the enumerate method. First we have initialized and created a list. The list contains seven elements in it. After creating the list we are using the for loop here to loop through each element of the list. The ‘i’ variable here is used for counting the number of times for loop gets executed. The enumerate(list) function here will iterate through each element in the list and also print the number including the index of each element.

5. Iterate Through List in Python Using List Comprehension

In this method of iteration, we will use the list comprehension way. List comprehension is used to create powerful functionality within a single line of code.

Syntax

[expression for item in list]

The List comprehension generally consists of three parameters.

  • expression:  It is the member itself, a call to a method, or any other valid expression that returns a value.
  • item: It is the object or value in the list or iterable.
  • list / iterable: It is a list, set, sequence, generator, or any other object that can return its elements one at a time

Example

list = [10, 20, 30, 40, 50, 60, 70] 
[print(i) for i in list] 

Output

10
20
30
40
50
60
70

Explanation

This is the most pythonic way to iterate through the list, as Python embraces simple, powerful tools that you can use in a wide variety of situations. Here in this example, print(i) is the expression. The second ‘i’ is the item, which is the value of iterable. And finally, the iterable, in the above example, the iterable is the list.

6. Iterate Through List in Python Using Loop and Range

The sixth method to iterate over a list is using the Range and any loop in Python. The range method can be used as a combination with for loop to traverse and iterate through a list. The range() function returns a sequence of numerals, starting from 0 (default), and by default increment by 1, and stops before a specified number.

Syntax

range(start, stop, step)
start(Optional). The specific number from which to start. Default is 0
stop(Mandatory). A number specifying at which position to stop (not included).
step(Optional). step is used to specify the incrementation. Default is 1.

Note: The range method doesn’t include the stop number in the resultant sequence.

Example

list = [10, 20, 30, 40, 50, 60, 70] 
length = len(list) 
for x in range(length): 
	print(list[x]) 

Output

10
20
30
40
50
60
70

Explanation

Here in the above example first we have initialized and created a list with elements [10, 20, 30, 40, 50, 60, 70]. After that we have finded the length of the list using the len function. The list of the length is 7, so now the value of the length variable is 7.

Now, the looping part comes here we are using the for loop in combination with the range function. In the above example, the length argument in the range function is the stop parameter. The value of length here is 7, so the loop will run from 0-6, as we already know the stop value is excluded while using the range function.

7. Iterate Through List in Python Using Map and Lambda

A lambda function is an anonymous function in Python. With the help of the lambda function, we can take n number of arguments, but there will be only one expression. The power of lambda is better shown when you use them as an anonymous function inside another function.

The map() function executes the specified function in an iterable.

Syntax

Syntax of Lambda

lambda arguments : expression

Here the expression will execute and the result will be returned.
arguments: there can be n number arguments.

Syntax of map() Function

map(function, iterables)
functionRequired.
iterableRequired. A sequence of a list, collection, or an iterator object.

Example

n = [10, 20, 30, 40, 50, 60, 70] 
ans = list(map(lambda y:y, n))
print(ans)  

Output

[10, 20, 30, 40, 50, 60, 70]

Explanation

In the above example, we have used the combination of lambda and map function to iterate the list. Here lambda y:y is provided as input function and ‘n’ is the second argument to the map() function. So, the map() function will pass every element of n to the lambda y:y function and return the elements.

8. Iterate Through List in Python Using zip()

If you want to iterate through two lists simultaneously you can use the zip() method in Python. So what the zip() function does is it creates an iterator that will aggregate elements from two or more iterables. 

The zip() function in Python generates a zip object, which is an iterator of tuples.

Syntax

zip(iterator1, iterator2, iterator3 ...)
iterator1, iterator2, iterator3 …Iterator objects that will be joined together

Example

num = [1, 2, 3, 4] 
daypart = ['moring', 'afternoon', 'evening', 'night'] 
for (a, b) in zip(num, daypart): 
	print (a, b) 

Output

1 moring
2 afternoon
3 evening
4 night

Explanation

In the above example, we iterate through the series of tuples returned by zip() and unpack the elements into a and b. The parameters of zipping () function, in this case, are (num, daypart) and they will be aggregated together.

When you combine zip()for Loops, and tuple unpacking, you can traverse two or more iterables at once.

9. Iterate Through List in Python Using Iterators – Iter() and Next()

To iterate a list using iterators in python we will use __iter()__ and __next()__ methods. In Python the __iter__() and __next__() are collectively knows as iterator protocol.

Iterators are generally implemented within loops, comprehensions, generators, etc. They are simply an object that can be iterated upon (one element at a time). Internally, the for loop creates an iterator object, iter_obj by calling iter() on the iterable.

Syntax

Syntax of __iter()__ function

iter(iterable)

Here the iterable can be a list, tuple, string, etc. The iter() function (which calls the __iter__() method) returns an iterator.

Syntax of __next()__ function

next(iter_obj)

The next(Iter_obj) is same as obj.next(). Here iter_obj can be any iterable object created by iter() function.

Example

iterable = [10, 20, 30, 40, 50, 60, 70]
iter_obj = iter(iterable)

while True:
    try:
        element = next(iter_obj)
        print(element)
    except StopIteration:
        break

Output

10
20
30
40
50
60
70

Explanation

In the above example first we have created an iterable (list) with elements [10, 20, 30, 40, 50, 60, 70]. Then we get an iterator using the iter() function and stored it in iter_obj variable. After that, we have initialized an infinite while loop and used the next() function to iterate through all the items of an iterator. When we reach the end, and there is no more data to be returned, it will raise the StopIteration exception.

Internally, the for loop creates an iterator object, iter_obj by calling iter() on the iterable. But in practice the for loop is actually an infinite while loop.

10. Iterate Through List in Python Using Itertools.Cycle

Itertools is a library that creates efficient iterators. These iterators work faster than the normal iteration. In this section, we’ll use itertools.cycle to perform an iteration through the list. This cycle function returns the infinite iterator which repeats the list over and over again. We’ll configure this to repeat only one time.

Syntax

import itertools

iter_obj = itertools.cycle(iterable)

Here the iterable can be a list, tuple, string, etc. The itertools.cycle() method returns an infinite iterator.

Example

import itertools

iterable = [1, 2, 3, 4, 5, 6, 7]
iter_obj = itertools.cycle(iterable)

count=0
while count < len(iterable):
    print(next(iter_obj))
    count += 1

Output

1
2
3
4
5
6
7

Explanation

In the above example, we first imported itertools. Then we used the itertools.cycle() method to create an infinite iterator. We then limit the number of times we loop through the iterator by using the count. After that using a while loop to loop through the iterator and increment the count at every loop. This will make sure our iterator doesn’t loop infinitely.

Itertools.cycle is mostly used to create an infinitely looping iterator. This is very useful in scenarios where you have to create an infinite loop without using a while.

11. Iterate Through List in Python Using Itertools Grouper

In this section, use itertools.zip_longest to create a grouper. Grouper is function which we can use to group the elements of list and iterate through them. This can be useful if you want to iterate 2-3 items per batch of your iterable.

Syntax

from itertools import zip_longest

def grouper(iterable_obj, count, fillvalue=None):
    args = [iter(iterable_obj)] * count
    return zip_longest(*args, fillvalue=fillvalue)
iterable_objRequired. A sequence of a list, collection, or an iterator object.
countRequired. The number of elements to group per batch.
fillvalueOptional. Fill value to fill the batch if the iterator finished before filling the batch.

Example

from itertools import zip_longest

def grouper(iterable_obj, count, fillvalue=None):
    args = [iter(iterable_obj)] * count
    return zip_longest(*args, fillvalue=fillvalue)

iterable = ["P", "Y", "T", "H", "O", "N"]

for x in grouper(iterable, 1, ""):
    print(*x)

Output

P
Y
T
H
O
N

Explanation

In this example, we first imported the zip_longest module from itertools. zip_longest is a method that aggregates the elements from each of the iterables. Then, we create a function called grouper. This function takes iterable as argument and number of elements to group together. In this case, since we want to iterate throughout the list, we’ll keep the value of count to 1. 3rd argument is fillvalue, this argument is used to fill the remaining values if the batch is smaller than the count.
Then, we’ll call the grouper function get iterable. We’ll iterate through this iterator to get individual elements from the list.

Note: Remember to unpack the element using * because zip_longest returns iterator of tuples.

Conclusion: Python Iterate Through List

So if you make it till the end, I am pretty sure you now be able to understand all the possible ways to iterate through the list in Python. The best possible way to Python iterate through the list depends on your need and the type of project you are doing. I think you might also want to know Ways in Python to Sort the List of Lists. If yes there is an awesome tutorial available in our library of tutorials do check it out.

Still have any doubts or questions do let me know in the comment section below. I will try to help you as soon as possible.

Happy Pythoning!

5 1 vote
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments