Table of Contents
show
List using For Loop
- The for loop in python is used to iterate over a sequence (list, tuple, string) or other iterable objects
- Iterating over a sequence is called traversal
- Loop continues until we reach the last item in the sequence
- The body of the for loop is separated from the rest of the code using indentation
Syntax
for val in sequence
for val in range(start,stop,step)
Example
Accessing the values in the list
list1 = [10,20,40,30,50,60]
for val in list1:
print(val)
Output,
10
20
40
30
50
60
Accessing index and values using range( )
list1 = [10,20,40,30,50,60]
for i in range(len(list1)):
print("value at {0} is {1}".format(i,list1[i]))
Output,
value at 0 is 10
value at 1 is 20
value at 2 is 40
value at 3 is 30
value at 4 is 50
value at 5 is 60
Accessing index and values using range( )
list1 = [10,20,40,30,50,60]
for i in range(1,len(list1),2):
print("value at {0} is {1}".format(i,list1[i]))
Output
value at 1 is 20
value at 3 is 30
value at 5 is 60
Accessing element using index
subject=["python","maths","chemistry"]
for i in range(len(subject)):
print(subject[i])
Output
python
maths
chemistry
List using While Loop
While loop in python is used to iterate over a block of code as long as the test expression (condition) is true
When the condition is tested and the result is false, the loop body will be skipped and the first statement after the while loop will be executed
Syntax
while(condition):
body of while
Example
Sum of Elements in the list
list1=[10,20,30,40,50]
sum =0
i=0
while(i<len(list1)):
sum=sum+list1[i]
i=i+1
print("Sum of Elements in list:",sum)
Output
Sum of Elements in list: 150
Views: 0