- When to use for loops?
- How do for loop works in Python?
- Nested for loops
- Early Exits (Break)
When to use for loop in python
It’s used when you have a block of statement/code that you want to repeat a certain number of times. Python for statements iterates over members of a sequence in order, executing a block each time.
For loop syntax:
for iterating_variable in sequence: statement(s)
How do for loop works in python
Basically in for loops we determine conditions (statement expression to identify condition is completed or not) then increase the expression as the per increment statement and proceed further. Actually any object in python with iterable method (It means data can be represented in list form) can be used for loop.
Nested for loop in python
We we have any block of code executed N number of times, then we have another block of code withing above block which execute M number of times then it is called as nested for loop in python.
for x in range(1, 11): for y in range(1, 11): print('%d * %d = %d' % (x, y, x*y))
Early Exit (break)
It is like when we want to break, or we have to come out of loop after meeting certain condition then we forcefully exit the loop.
for x in range(3): if x == 1: break
Let’s see some interesting for loop example of python:
for x in range(5): print(x) else: print('Final x = %d' % (x))
Strings as an iterable
string = "Online Tutorials" for x in string: print(x)
Lists as an iterable
collection = ['Online', 7, 'Tutorials'] for x in collection: print(x)
Loop over Lists of lists
list_of_array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] for eachList in list_of_array : for x in eachList : print(x)
Creating your own custom iterable
class Iterable(object): def __init__(self, values): self.values = values self.location = 0 def __iter__(self): return self def next(self): if self.location == len(self.values): raise StopIteration value = self.values[self.location] self.location += 1 return value
Custom range generator using yield
for x in my_custom_range(1, 20, 1): print(x)myCustomlist = ['a', 'b', 'c', 'd'] for i in range(len(myCustomlist )): # perform operation with myCustomlist[i]