A list is an ordered combination of different types of elements. There are several ways through which we can iterate over a list. The methods we‘ll discuss are as follows:
- Using for Loop
- Using the range () method
- Using while loop
- Using List Comprehension
- Using enumerate () method
- Using the NumPy module function
Using for loop
By using for loop we can easily iterate elements of a list. Let’s consider this by an example given below.
nl= [10, 20, 30, 40, 50, 60] print("list items are as follows:") for i in nl: print(i)
list items are as follows:
In figure 1 we have used for loop to iterate list items containing numbers. The print function displays all elements of the list accessed by for loop as shown in figure 2.
Using range() method:
In this method, we use the range function in combination with for loop. Let’s consider this by the example given below.
nl= [10, 20, 30, 40, 50, 60] for i in range(len(nl)): print("list item",i, "is:",nl[i])
list item 0 is: 10
list item 1 is: 20
list item 2 is: 30
list item 3 is: 40
list item 4 is: 50
list item 5 is: 60
In figure 3 range function is used and the length of the list is given as a stop parameter for the range function. Figure 4 tells that every element is displayed with an index as output.
Using while Loop
While loop can also be used to iterate list elements. Let’s consider this by example given below.
wk_days = ["Monday", "Tuesday", "Wednesday", "Thursday","Friday"] i = 0 while i < len(wk_days): print(wk_days[i]) i = i + 1
In the above figure 5, we have a list of weekdays. While loop compares the length of the list with variable i and prints days name one by one as shown in figure 6.
Using List Comprehension
In this method, we‘ll use List comprehension. It is the shortest and most tricky way. Let’s consider this by the example given below.
ns_list = [10, "ten", 20, "twenty", 30, "thirty", 40, "forty"] [print(n) for n in ns_list]
In figure 7 we have a list containing string integers and strings. We can iterate the list items as shown in figure 8.
Using enumerate() method
alist = [1, 'number', 1.0, 'float', 'a', 'string'] for index, value in enumerate(alist): print(index, ":", value)
0 : 1
1 : number
2 : 1.0
3 : float
4 : a
5 : string
In figure 9 we have used enumerate function which displays the index number and value. We get output as shown in figure 10.
Using the numpy module function
import numpy as np new_list = np.array([1, 'number', 1.0, 'float', 'a', 'string']) for x in np.nditer(new_list): print(x)
To use the NumPy functions first thing we do is import the NumPy module. NumPy module has nditer() function that iterates the elements of the list.
Karim Buzdar holds a degree in telecommunication engineering and holds several sysadmin certifications including CCNA RS, SCP, and ACE. As an IT engineer and technical author, he writes for various websites.