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
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
Number of elements in list:7 10 20 30 40 50 60 70
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)
Cricket Football Tennis Golf Table Tennis Rugby