Printing element of list using while and for loop

In this blog, we will use while and for loop to display every elements of a list. For while loop, we need to make use of len() function.

Below is the example of while loop for displaying every elements of a list.

Creating numbers list.

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

Finding number of elements in a list and displaying it.

length = len(numbers)
print('Number of elements in list:%s'%length)

Assigning 0 value to variable index

index= 0

Now using while loop to check whether value of index variable is less than value of length variable. In first loop, value of index is 0 and value of length variable is 7. This is a true condition so statements within while loop will be executed. There are two statements in while loop, printing element of numbers list using value of index variable as a reference to index position. At last, incrementing index variable by 1. Condition becomes false when index value reaches 7.

while index<length:
    print(numbers[index])
    index=index+1

OUPUT

Number of elements in list:7
10
20
30
40
50
60
70

Complete Code

numbers = [10,20,30,40,50,60,70]
length = len(numbers)
print('Number of elements in list:%s'%length)
index = 0
while index<length:
    print(numbers[index])
    index=index+1

Below is the code for displaying every elements of a list using for loop.

sports = ['Cricket','Football','Tennis','Golf','Table Tennis','Rugby']
for s in sports:
    print(s)

OUTPUT

Cricket
Football
Tennis
Golf
Table Tennis
Rugby

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s