In previous tutorials, we have seen how to access the individual elements of lists, tuples, sets, and dictionaries using Python For loop.
Examples of Python For Loop
Let’s see one more example, which prints the square value of list elements using python for loop.
l=[1,2,3] for i in l: print(i*i)
We can loop through the string in the same way.
for i in "hello world": print(i)
To loop through a set of code for a specific number of times, we can use range() function. range() function generates a sequence of numbers that starts from 0 by default, increments by 1 by default, and ends at the specified number.
for i in range(10): print(i)
We can also provide start and step parameters in the format:
range(start, stop, step)
for i in range(1,10,2): print(i)
Using range() with sequence:
With Python for loop, there is another method to access the items of the sequence using their index.
l=[1,2,3,'a','b','c'] length=len(l) for i in range(length): print(l[i])
pass, break, continue:
We can also use the pass, break, and continue statements inside for loop.
for i in range(5): pass # break for i in range(10): if i==5: break print(i) # continue for i in range(1,10): if i%2==1: continue print(i)
In the above examples,
- pass statement does nothing
- break statement breaks the loop when the iterator becomes 5.
- with the continue statement, we are printing even numbers.
We can use else statement after a for loop, to execute a set of statements, when the for loop is ended.
l=[1,2,3,'a','b','c'] length=len(l) for i in range(length): print(l[i]) else: print("for loop has ended")
Nested for loop:
For loop inside a for loop is called nested for loop. The inner loop will be executed for each iteration of the outer loop. For example, the outer loop has ‘m’ iterations and the inner loop has ‘n’ iterations. The code inside the inner for loop will be executed for ‘m*n’ times. We have to be careful with the performance when using nested for loops.
We can try printing multiples of 2 and 3 using nested for loop.
for i in range(2,4): print("Multiples of "+str(i)) for j in range(1,11): print(i*j)
- The outer loop will be executed twice.
- For each iteration of the outer loop, the inner loop is executed exactly 10 times.
- So the total number of iterations is 2*10 times.
We discussed on Python For loop in this article. Please visit the next articles for more topics on Python.