How to traverse a list in python
Traversing is an act of processing each element in a list. We can traverse (Iterate) a list following ways.
#1 Method
We can traverse a list in python using for loop
list = [ ‘a’, ‘b’, ‘c’, ‘d’ ]
for i in list:
print( i )
Output
a
b
c
d
#2 Method
We can traverse a list in python using a while loop
list = [ 10, 20, 30, 40 ]
i = 0
n = len( list )
while ( i < n ):
print( list[ i ] )
i+=1
Output
10
20
30
40
#3 Method
We can traverse a list using enumerate function
list1 = [ 1, 2, 3, 4 ]
for i,j in enumerate(list1):
print(“list1[{0}] = {1}”.format(i,j))
Output
list1[0] = 1
list1[1] = 2
list1[2] = 3
list1[3] = 4
Important Links
What is Python List
Characteristics of Python List
How to Create Python List
How to Manipulate list in Python
How to Modify multiple elements in Python list
Slicing in Python List
Built in function of Python List