Python For loop

Python For loop is used to iterate over a sequence like strings, lists, tuples, etc. A for loop is used to execute a set of statements for each item in a sequence.

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.

for i in l:

We can loop through the string in the same way.

for i in "hello world":


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):

We can also provide start and step parameters in the format:

range(start, stop, step)

for i in range(1,10,2):

Using range() with sequence:

With Python for loop, there is another method to access the items of the sequence using their index.

for i in range(length):

pass, break, continue:

We can also use the pass, break, and continue statements inside for loop.

for i in range(5):
# break
for i in range(10):
  if i==5:
# continue
for i in range(1,10):
  if i%2==1:

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.

for i in range(length):
  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):
  • 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.

Array Interview Questions
Graph Interview Questions
LinkedList Interview Questions
String Interview Questions
Tree Interview Questions
Core Java Interview Questions