for loop and range

 for loop is used for iterating over number of elements in specified iterable whereas while is condition-based iteration.

Iterables are datatypes which can be iterated such as str,range,list,set,tuple,dict. Iterable type are classes which object have collection of objects and to access those values one by one provides concept of iterator. Iterator is a programming feature by which we can access elements of iterable one by one without knowledge of inner arrangement of that iterable container. 

Non iterable - primitive datatypes such as int,float,complex,bool

Iterable are the data structures on which we can apply concept of iterator. for loop only works on iterable *

s1 = "Elements"

for e in s1:
    print(e)


#count occurences of o
s1 = "This is only done once "
count = 0
for e in s1:
    if(e == 'o'):
        count+=1
print("Number of occurences:",count)


Similar to while loop, all the transfer control statements like break,continue,pass can be used in for statement. we can also use else block to indicate normal execution without break.

range

About range:- 
  • range is a class
  • range is a datatype
  • range is iterable
  • range is a sequence (because position of elements is ensured)
creating a range object

range (beg,end,steps) - step is by default 1. 

x = range ( 1, 10, 1) 

for e in x:
    print(e,end = ' ')

# 1 , 2 , 3 ,4 ,5, 6, 7 , 8,9 (**10 is not inclusive here) 

range can work in reverse direction as well

x = range(10,5,-1) 

# if we iterate the range datatype, we will get below

10,9,8,7,6

so, we can say elements in range object follows arithmetic progression. 

  • range elements are always of type int. NO other datatype. 

Single argument in range is always end value

Example 

  • x = range (5) ==> this implies 0,1,2,3,4 (starting from 0)
Additionally, we can use concept of indexing to access elements in range like array. 

Example - 

x = (2,20,2)

x[0] -> result 2
x[1] -> result 4
...
...
x[8] --> result 18

Indexing can work both ways. So accessing any index is easy.

Elements
2  4  6  8  10  12  14  16  18

-9 -8 -7 -6 -5 -4    -3  -2    -1  (indexing negative)

0  1  2  3   4    5     6   7     8 (indexing positive)

Since this also works as array, we can use while loop as well to iterate elements. 

x = range(2,20,2)
i=0
while  i < 8 :
    print(x[i])
    i= i+1


Comments