Friday, January 31, 2020

Python for loop

Python for loop


The "for" is an iteration loop in Python like other programming languages. The for loop is generally programmer's first choice when they want to iterate in their code, especially when the limit of the iteration is known and predefined. We can iterate elements in collection or sequence(iterable objects) in Python using for loop. For example, we can iterate over a list, tuple, set, or dictionary.

for loop python

Iterating a List,
for item in [14,17,20,11,25]:
  print(item)

Output:
14
17
20
11
25


Iterating in a range,
We can iterate over a provided range.

for item in range(1,5):
  print(item)

Output:
1
2
3
4


or,

for item in range(4):
  print(item)

Output:
0
1
2
3

for loop is iterated over any iterable object, which is an object defines a __getitem__ or a __iter__  function. The __ iter__ method returns an iterator, which is an object with a next function that is used to access the next element of the given iterable.

for item in ["Python","is","easy","yet","powerful","programming","language"]:
    print(item)

Output:
Python
is
easy
yet
powerful
programming
language  

If we want to iterate a list with an index of the item then we can use enumerate function. For example

for index, element in enumerate(["Python","is","easy","yet","powerful","programming","language"]):
    print(index,"->",element)

Output:
0 -> Python
1 -> is
2 -> easy
3 -> yet
4 -> powerful
5 -> programming
6 -> language  

The 'break' statement in a loop

The "break" statement forces control to come out the innermost loop, in an iteration.break are generally applied inside if statement nested inside an iteration statement like for, while and do-while.

for example,(linear search with for-loop)

def linearSearch(num):
  count=0  
  l=[7,12,25,0,11,36,41]
  length=len(l)
  for x in l:
    count=count+1    
    if num==x:
      print('found')
      break  
    #control will come out from the loop  
  if count>=length:
    print('not found')
linearSearch(11)
linearSearch(75)

Output:
found
not found

The 'continue' statement in a loop

The "continue" statement will jump to the next iteration, skipping all remaining code inside the current loop block but continuing the loop. Like break, continue can appear inside loops only.

for x in range(1,20):
  if x%2==0 or x%3==0:
    continue 
  print('2 and 3 are not a divisor of ',x)
    
Output:
2 and 3 are not a divisor of  1
2 and 3 are not a divisor of  5
2 and 3 are not a divisor of  7
2 and 3 are not a divisor of  11
2 and 3 are not a divisor of  13
2 and 3 are not a divisor of  17
2 and 3 are not a divisor of  19

The 'else' clause with for-loop

The "for-loop" optionally can have else clause, for example

for i in range(3):
  print(i)
else:
  print('range finished')

Output:
0
1
2
range finished

Iterating String with for loop

Strings are iterable objects and can be iterated over for loop easily.


for i in 'Python':
  print(i)

Output:
P
y
t
h
o
n