Traversing the Elements

Traversing the Elements

In this tutorial, we’ll go over how to iterate through list (Traversing the Elements) in Python. The sequential access of each element in the list is called traversal.

1. By using while Loop
n = [0,1,2,3,4,5,6,7,8,9,10] 
i = 0 
while i < len(n):
    print(n[i]) 
    i=i+1

Output

ashok@ashok:~$ py test.py
0
1
2
3
4
5
6
7
8
9
10
2. By using for Loop
n=[0,1,2,3,4,5,6,7,8,9,10] 
for num in n: 
    print(num)

Output

ashok@ashok:~$ py test.py
0
1
2
3
4
5
6
7
8
9
10

E.g 2 Display only Even Numbers

n=[0,1,2,3,4,5,6,7,8,9,10] 
for num in n: 
   if num%2==0:
     print(num)

Output

ashok@ashok:~$ py test.py
0
2
4
6
8
10
3. 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.
lst = [10, 20, 30, 40, 50, 60, 70]
 
for x in range(len(lst)): 
    print(lst[x]) 

Output

ashok@ashok:~$ py test.py
10
20
30
40
50
60
70
4. Using the enumerate type

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

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

for x, res in enumerate(lst): 
    print (x,":",res) 

Output

0 : 10
1 : 20
2 : 30
3 : 40
4 : 50
5 : 60
6 : 70
5. Using lambda function

Python’s lambda functions are basically anonymous functions.

Syntax

lambda parameters: expression

Where expression is the iterable which is to be evaluated.

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, 20, 30, 40, 50, 60, 70]
 
res = list(map(lambda x:x, lst))
 
print(res) 

Output

ashok@ashok:~$ py test.py
10
20
30
40
50
60
70
Traversing the Elements
Scroll to top