For Loop in Python

Rahull Trehan
2 min readJul 27, 2021

In python, there are a lot of times when we have to iterate through the values we have in our iterable variable. I am purposely mentioning the word iterable before the variable to highlight that there are objects which are capable of returning values one at a time and for that reason, these objects are called iterable. In python there ate many objects which are iterable like lists, strings, file objects, etc.

The for loop can be used to iterate an iterable in python and is used very extensively and just requires an iterable object to work with.

Example — Iterating through a list

Input:
list = [1,2,3,4]
for
i in list:
print(i)
Output:
1
2
3
4

Example — Iterating through a tuple

Input:
tup = (a,b,c,d)
for
i in tup:
print(i)
Output:
a
b
c
d

Example — Iterating through a list of tuples

Input:
list = [(1,2),(3,4),(5,6)]
for
i in list:
print(i)
Output:
(1,2)
(3,4)
(5,6)

A string object is also iterable, lets take an example of a string object

Input:
text = "hello"
for
i in text:
print(i)
Output:
h
e
l
l
o

There are so many other combinations available to iterate through using a for loop. The idea behind the for loop is that it iterates through each element of the object on which it is run and it also supports conditional clauses like if, else, etc.

Input:
for
i in range(1,10):
if i%2 == 0:
print(i)
Output:
2
4
6
8

Using both if and else condition along with for loop:

Input:
for
i in range(1,10):
if i%2 == 13:
print(i, "The multiple of 13 found!")
else:
print("Multiple of 13 not found!")
Output:
Multiple of 13 not found!

We can also use continue and break statements in for loops. The basic difference between the continue and break statement is that the continue skips the element which satisfies the condition and continues with the loop whereas the break statement breaks the loop and comes out of it. Let's see an example that explains them both:

Input:
for
i in range(1,10):
if i%3 == 0:
continue
print
(i)
Output:
1
2
4
5
7
8

using the same code with break statement instead of continue

Input:
for
i in range(1,10):
if i%3 == 0:
break
print
(i)
Output:
1
2

we can see that the loop was broke as soon as it found the first value which was divisible by 3 in the range.

I hope this helped in getting hold of for loops in python to an extent. Thank you for reading.

--

--