How to traverse a list in python || New & easy way to learn Informatics Practices

How to traverse a list in python

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

If you like my post please share it with your friends by simply clicking the below social media button, and Don’t forget to comment so we will update ourselves.

Share in a Single Click

Leave a Reply

Your email address will not be published. Required fields are marked *