Tutorial – for Loop in Python

Tutorial – for Loop in Python

9 mins read1.6K Views Comment
Updated on May 1, 2023 12:36 IST

Let’s read about for Loop in Python in the below tutorial.

2022_02_for-loop-in-Python.jpg

Loops are used in programming to repeat a specific part of the code. We have already covered the while loop in our previous article and today, we will focus on how to execute a set of statements using different variations of the For loop in Python.

Must Check: For Loops in Python (Practice Problem)

Must Read: What is Python?

What is for loop?

In Python, the for loop is used to iterate over a sequence or an iterable object (such as a list, tuple, or string). The process of iterating over a sequence is also known as traversing the sequence.

Recommended online courses

Best-suited Python courses for you

Learn Python with these high-rated online courses

– / –
40 hours
– / –
5 days
– / –
3 days
3 K
3 weeks
– / –
4 days
– / –
20 hours
– / –
2 months
Free
6 weeks

How Does a for loop Work in Other Programming Languages?

The for loop in python is different from the traditional for a keyword in other programming languages like C++ and Java that operate somewhat like for(i=0; i<n; i++).  The for loop in python works in conjunction with the in keyword to act as a method for sequential traversal, which is equivalent to for each keyword in other programming languages.

Must Check: Python Online Course and Certifications

for loop Syntax in Python

The python for loop follows the below syntax:

Syntax

 
\n \n <pre class="python" style="font-family:monospace">\n \n <span style="color: #ff7700;font-weight:bold">\n \n for iterator \n \n <span style="color: #ff7700;font-weight:bold">\n \n in iterable:\n \n
statements\n \n <span style="color: black">\n \n (s\n \n <span style="color: black">\n ) \n </span style="color: black">\n \n </span style="color: black">\n \n </span style="color: #ff7700;font-weight:bold">\n \n </span style="color: #ff7700;font-weight:bold">\n \n </pre class="python" style="font-family:monospace">
Copy code

Here,

  • iterator is a variable that is used to store elements of the iterable in each iteration.
  • iterable is a sequential structure like list, string, dictionaries, set or tuples etc, that is to be iterated over by the for loop.

The for loop can be used with the range() function in python to work with a number range. The range() function takes in the upper bound(excluded) of the range as an argument and the lower bound is by default 0.

Below, we have illustrated the Python for loop flowchart –

2022_07_image-144.jpg

Python For Loop Implementation Examples

Example 1:

 
fruits = ["apple", "banana", "grapes",
"mango", "cherry", "melon",
"peach", "guava", "jujube"]
for x in fruits:
print(x)
Copy code

Output 1:

2022_07_image-146.jpg

Also Read: Tutorial: for loop in Python

In the above code, we initialize a list of fruits with string elements denoting fruit names.

Then, we use the for loop to iterate over each element of the given list and print that element. The loop will run till it has traversed the entire list from beginning to the end, that is, 9 times in this case.

Example 2:

 
num = [2, 4, 6, 8, 10, 12, 14]
sum = 0
#Iterate over the list
for val in num:
sum += val
print("The sum of elements in the list is ", sum)
Copy code

Output 2:

2022_07_image-145.jpg

Also Read: Understanding Python for loop with example

How to use a for loop for a range of numbers?

The range() function in Python is used to generate a sequence of numbers. The syntax for the function is given as follows:

range(start, stop, step)

Let’s talk about the three arguments passed to the function as you can see in the syntax above:

  • start: (Optional) This argument specifies the integer value to start the range with. The default value is 0.
  • stop: (Mandatory) This argument takes an integer value that specified which position to stop at.
  • step: (Optional) This argument takes an integer that specifies the increment value – the number of steps to skip in the range. The default value is 1.

The range object is called “lazy” because it does not generate every number it contains when created. We can use the function list() to output all elements of the range() function.

Also Read: Python While Loop with Example

Consider the following example to understand this:

Example 1:

 
print(range(10))
print(list(range(10)))
print(list(range(1, 11)))
print(list(range(2, 20, 3)))
Copy code

Output:

2022_07_image-147.jpg

Take a look at the below examples.

Also Read: Pattern Program in Python

Example 2: Python program to print numbers in the range 5.

 
\n \n <pre class="python" style="font-family:monospace">\n \n <span style="color: #ff7700;font-weight:bold">\n \n for i \n \n <span style="color: #ff7700;font-weight:bold">\n \n in \n \n <span style="color: #008000">\n \n range\n \n <span style="color: black">\n ( \n <span style="color: #ff4500">\n 5 \n <span style="color: black">\n ): \n
\n <span style="color: #ff7700;font-weight:bold">\n print \n <span style="color: black">\n (i \n <span style="color: black">\n ) \n </span style="color: black"> \n </span style="color: black"> \n </span style="color: #ff7700;font-weight:bold"> \n </span style="color: black"> \n </span style="color: #ff4500"> \n </span style="color: black">\n \n </span style="color: #008000">\n \n </span style="color: #ff7700;font-weight:bold">\n \n </span style="color: #ff7700;font-weight:bold">\n \n </pre class="python" style="font-family:monospace">
Copy code

Output:

 
0
1
2
3
4
Copy code

Notice the upper bound in the range() function(ie, 5) is excluded from the for loop which is the standard behavior of python. If you want the upper bound to be included in the loop, you need to increment the upper bound value by 1.

Also Read: Flow Control in Python

Example 2: Python program to print numbers between 10 to 15.

 
for i in range(10,15):
print(i)
Copy code

Output:

 
10
11
12
13
14
Copy code

The Range Function in For Loops

The range() function can be used in for loops to iterate through a sequence of numbers. Also, we can combine it with the len() method to iterate through a sequence using indexing.

Look at the following example:

genre = [‘comedy’, ‘horror’, ‘drama’, ‘thriller’, ‘action’]

#Iterate over the list using index

for movie in range(len(genre)):

    print(“I like”, genre[movie])

Output:

The Range Function in For Loops

The range() function can be used in for loops to iterate through a sequence of numbers. Also, we can combine it with the len() method to iterate through a sequence using indexing.

Look at the following example:

 
genre = ['comedy', 'horror', 'drama', 'thriller', 'action']
#Iterate over the list using index
for movie in range(len(genre)):
print("I like", genre[movie])
Copy code

Output:

2022_07_image-148.jpg

Also Read: How to use Pass statement in Python

For Loop with Else Statement

Similar to the while loop, the for loop also supports an optional else block as well. The else part is executed if the elements in the sequence within the for loop get exhausted.

Here’s the syntax for a for…else loop in Python:

for iterator_var in sequence:

     loop body

else:

    body of else

Below, we have illustrated the Python for…else loop flowchart –

2022_07_image-152.jpg

Also Read: Iterators in iterators in Python

For… Else Loop Implementation Example

Example:

 
num = [0, 1, 2, 3, 4, 5, 6]
for i in num:
if i%2 == 0:
print(i)
else:
print("No more elements to traverse.")
Copy code

Output:

2022_07_image-151.jpg

What have we done here?

  • In the above code, the for loop starts from the first element of the list num.
  • The loop runs and each time, it prints only the even-numbered elements from the list.
  • Once the loop has traversed all elements of the given list, it exhausts and moves on to the else part.
  • The body of else gets executed.

Also Read: Difference between while and do while loop 

For… Else Loop with Break Statement

  • If the for loop is executed with a break keyword and the loop break abruptly, the else block will be skipped. 
  • The statements below the for…else loop will be executed with or without the break statement.

Below, we have illustrated the Python for…else loop with a break statement through a flowchart –

2022_07_image-150.jpg

Also Read: Getting started with Python String

Example:

 
name = 'Sam'
marks = {'Jimmy': 91, 'Julia': 54, 'James': 67}
for student in marks:
if student == name:
print(marks[student])
break
else:
print('No entry with that name was found.')
Copy code

Output:

2022_07_image-149.jpg

What have we done here?

  • In the above code, the for loop starts from the first element of the dictionary marks.
  • The loop executes an if statement inside it and there is a break statement inside the if part.
  • So, the if part terminates abruptly, we break out of it to move on to the else part of the for loop.

However, if there was a break statement outside the if statement inside the for loop, the else part would have been skipped entirely:

 
name = 'Sam'
marks = {'Jimmy': 91, 'Julia': 54, 'James': 67}
for student in marks:
if student == name:
print(marks[student])
break
break
else:
print('No entry with that name was found.')
Copy code

No Output.

How to run a for loop through a string in python?

We can also use the for loop to iterate over the characters of a string. Take a look at the below example.

Example: Python program to print the characters of a string.

 
# given string
string = "Naukri"
for i in string:
print(i)
Copy code

Output:

 
N
a
u
k
r
i
Copy code

Break in for loop

The break keyword is used to stop the for loop from iterating over an iterable. It is generally used to bring the control out of the for loop when a specific item is discovered while iterating through an iterable.

Example: Python program that stops iterating when the character “k” is found in the given string.

 
# given string
string = "naukri"
for i in range(len(string)):
if string[i] == "k":
print("k is PRESENT at the",i,"index of the given string")
break
else:
print("K is not present at the",i, "index of the given string")
Copy code

Output:

 
K is not present at the 0 index of the given string
K is not present at the 1 index of the given string
K is not present at the 2 index of the given string
k is PRESENT at the 3 index of the given string
Copy code

Now take a look at the below code that doesn’t have the break keyword after if condition. You will notice that even after the character “k” is discovered, the for loop still carries ahead and looks up for the “k” character in the rest of the string.

 
\n \n <pre class="python" style="font-family:monospace">\n \n <span style="color: #808080;font-style: italic">\n \n # given string\n \n
\n \n <span style="color: #dc143c">\n \n string \n \n <span style="color: #66cc66">\n \n = \n \n <span style="color: #483d8b">\n "naukri" \n
\n
\n <span style="color: #ff7700;font-weight:bold">\n for i \n <span style="color: #ff7700;font-weight:bold">\n in \n <span style="color: #008000">\n range \n <span style="color: black">\n ( \n <span style="color: #008000">\n len \n <span style="color: black">\n ( \n <span style="color: #dc143c">\n string \n <span style="color: black">\n ) \n <span style="color: black">\n ): \n
\n <span style="color: #ff7700;font-weight:bold">\n if \n <span style="color: #dc143c">\n string \n <span style="color: black">\n [i \n <span style="color: black">\n ] \n <span style="color: #66cc66">\n == \n <span style="color: #483d8b">\n "k": \n
\n <span style="color: #ff7700;font-weight:bold">\n print \n <span style="color: black">\n ( \n <span style="color: #483d8b">\n "k is PRESENT at the" \n <span style="color: #66cc66">\n ,i \n <span style="color: #66cc66">\n , \n <span style="color: #483d8b">\n "index of the given string" \n <span style="color: black">\n ) \n
\n
\n <span style="color: #ff7700;font-weight:bold">\n else: \n
\n <span style="color: #ff7700;font-weight:bold">\n print \n <span style="color: black">\n ( \n <span style="color: #483d8b">\n "K is not present at the" \n <span style="color: #66cc66">\n ,i \n <span style="color: #66cc66">\n , \n <span style="color: #483d8b">\n "index of the given string" \n <span style="color: black">\n ) \n </span style="color: black"> \n </span style="color: #483d8b"> \n </span style="color: #66cc66"> \n </span style="color: #66cc66"> \n </span style="color: #483d8b"> \n </span style="color: black"> \n </span style="color: #ff7700;font-weight:bold"> \n </span style="color: #ff7700;font-weight:bold"> \n </span style="color: black"> \n </span style="color: #483d8b"> \n </span style="color: #66cc66"> \n </span style="color: #66cc66"> \n </span style="color: #483d8b"> \n </span style="color: black"> \n </span style="color: #ff7700;font-weight:bold"> \n </span style="color: #483d8b"> \n </span style="color: #66cc66"> \n </span style="color: black"> \n </span style="color: black"> \n </span style="color: #dc143c"> \n </span style="color: #ff7700;font-weight:bold"> \n </span style="color: black"> \n </span style="color: black"> \n </span style="color: #dc143c"> \n </span style="color: black"> \n </span style="color: #008000"> \n </span style="color: black"> \n </span style="color: #008000"> \n </span style="color: #ff7700;font-weight:bold"> \n </span style="color: #ff7700;font-weight:bold"> \n </span style="color: #483d8b">\n \n </span style="color: #66cc66">\n \n </span style="color: #dc143c">\n \n </span style="color: #808080;font-style: italic">\n \n </pre class="python" style="font-family:monospace">
Copy code

Output:

 
K is not present at the 0 index of the given string
K is not present at the 1 index of the given string
K is not present at the 2 index of the given string
k is PRESENT at the 3 index of the given string
K is not present at the 4 index of the given string
K is not present at the 5 index of the given string
Copy code

continue statement in for loop

The continue statement in python works exactly opposite to that of the break statement. It is used to terminate the current iteration of the for loop, and continue with the next iteration.

Take a look at the below examples for a better understanding.

Example: Python program to print all the letters of a given string except the letter “K”.

 
\n \n <pre class="python" style="font-family:monospace">\n \n <span style="color: #808080;font-style: italic">\n \n # given string\n \n
\n \n <span style="color: #dc143c">\n \n string \n \n <span style="color: #66cc66">\n \n = \n \n <span style="color: #483d8b">\n "naukri" \n
\n
\n <span style="color: #ff7700;font-weight:bold">\n for i \n <span style="color: #ff7700;font-weight:bold">\n in \n <span style="color: #dc143c">\n string: \n
\n <span style="color: #ff7700;font-weight:bold">\n if i \n <span style="color: #66cc66">\n == \n <span style="color: #483d8b">\n "k": \n
\n <span style="color: #ff7700;font-weight:bold">\n continue \n
\n <span style="color: #ff7700;font-weight:bold">\n print \n <span style="color: black">\n (i \n <span style="color: black">\n ) \n </span style="color: black"> \n </span style="color: black"> \n </span style="color: #ff7700;font-weight:bold"> \n </span style="color: #ff7700;font-weight:bold"> \n </span style="color: #483d8b"> \n </span style="color: #66cc66"> \n </span style="color: #ff7700;font-weight:bold"> \n </span style="color: #dc143c"> \n </span style="color: #ff7700;font-weight:bold"> \n </span style="color: #ff7700;font-weight:bold"> \n </span style="color: #483d8b">\n \n </span style="color: #66cc66">\n \n </span style="color: #dc143c">\n \n </span style="color: #808080;font-style: italic">\n \n </pre class="python" style="font-family:monospace">
Copy code

Output:

 
n
a
u
r
i
Copy code

if-else in for loop

The if and else keyword can be used to execute a block of code within these keywords when the for loop finishes its iteration.

Take a loop at the below example for reference.

Example: Python program to check if the sum of given numbers is odd or even.

 
# given list of numbers
list = [2,3,4,6,9]
# variable to store the sum
# of the given numbers
sum = 0
for i in list:
# logic to sum the
# numbers in the given list
sum+=i
# this print statemt gets executed
# once the for loop is finished
print("loop has finished!")
# logic to check if
# the sum is even
if sum%2==0:
print("The sum of given numbers is an even number:",sum)
# if sum is not even
# then it's odd
else:
print("The sum of given numbers is an odd number:",sum)
Copy code

Output:

 
loop has finished!
The sum of given numbers is an even number: 24
Copy code

pass statement in for loop

The pass statement is used for writing empty loops. The pass keyword can also be used for implementing empty control statements, classes, or functions.

Example: Python program to print the last letter of a given string.

 
\n \n <pre class="python" style="font-family:monospace">\n \n <span style="color: #808080;font-style: italic">\n \n # given string\n \n
\n \n <span style="color: #dc143c">\n \n string \n \n <span style="color: #66cc66">\n \n = \n \n <span style="color: #483d8b">\n "naukri" \n
\n
\n <span style="color: #808080;font-style: italic">\n # An empty for loop \n
\n <span style="color: #ff7700;font-weight:bold">\n for j \n <span style="color: #ff7700;font-weight:bold">\n in \n <span style="color: #dc143c">\n string: \n
\n <span style="color: #ff7700;font-weight:bold">\n pass \n
\n
\n <span style="color: #ff7700;font-weight:bold">\n print \n <span style="color: black">\n ( \n <span style="color: #483d8b">\n 'The last letter of the given string is:' \n <span style="color: #66cc66">\n , j \n <span style="color: black">\n ) \n </span style="color: black"> \n </span style="color: #66cc66"> \n </span style="color: #483d8b"> \n </span style="color: black"> \n </span style="color: #ff7700;font-weight:bold"> \n </span style="color: #ff7700;font-weight:bold"> \n </span style="color: #dc143c"> \n </span style="color: #ff7700;font-weight:bold"> \n </span style="color: #ff7700;font-weight:bold"> \n </span style="color: #808080;font-style: italic"> \n </span style="color: #483d8b">\n \n </span style="color: #66cc66">\n \n </span style="color: #dc143c">\n \n </span style="color: #808080;font-style: italic">\n \n </pre class="python" style="font-family:monospace">
Copy code

Output:

 
The last letter of the given string is: i
Copy code

Nested for loop

A nested for loop is just a for loop that has one or multiple for loops within it. The “inner loops” in a nested for loop gets executed once for each iteration of the “outer loop”.

Take a look at the below example for reference.

Example: Python program to find fruit names with the letter “e” in a given list of fruit names.

 
55\n \n <pre class="python" style="font-family:monospace">\n \n <span style="color: #808080;font-style: italic">\n \n # given list of fruit names\n \n
fruits \n \n <span style="color: #66cc66">\n \n = \n \n <span style="color: black">\n \n [\n \n <span style="color: #483d8b">\n "apple" \n <span style="color: #66cc66">\n , \n <span style="color: #483d8b">\n "mango" \n <span style="color: #66cc66">\n , \n <span style="color: #483d8b">\n "peach" \n <span style="color: #66cc66">\n , \n <span style="color: #483d8b">\n "banana" \n <span style="color: black">\n ] \n
\n
\n <span style="color: #808080;font-style: italic">\n # outer loop to iterate through \n
\n <span style="color: #808080;font-style: italic">\n # the list of items in fruits variable \n
\n <span style="color: #ff7700;font-weight:bold">\n for i \n <span style="color: #ff7700;font-weight:bold">\n in fruits: \n
\n
\n <span style="color: #808080;font-style: italic">\n # inner loop to iterate through \n
\n <span style="color: #808080;font-style: italic">\n # the the letters of each fruit \n
\n <span style="color: #808080;font-style: italic">\n # and check if it has the letter \n
\n <span style="color: #808080;font-style: italic">\n # "e" in it \n
\n <span style="color: #ff7700;font-weight:bold">\n for j \n <span style="color: #ff7700;font-weight:bold">\n in i: \n
\n
\n <span style="color: #808080;font-style: italic">\n # condition to check if \n
\n <span style="color: #808080;font-style: italic">\n # letter "e" exits in \n
\n <span style="color: #808080;font-style: italic">\n # the current fruit name \n
\n <span style="color: #ff7700;font-weight:bold">\n if j \n <span style="color: #66cc66">\n == \n <span style="color: #483d8b">\n "e": \n
\n <span style="color: #ff7700;font-weight:bold">\n print \n <span style="color: black">\n (i \n <span style="color: #66cc66">\n , \n <span style="color: #483d8b">\n "has the letter e in it." \n <span style="color: black">\n ) \n </span style="color: black"> \n </span style="color: #483d8b"> \n </span style="color: #66cc66"> \n </span style="color: black"> \n </span style="color: #ff7700;font-weight:bold"> \n </span style="color: #483d8b"> \n </span style="color: #66cc66"> \n </span style="color: #ff7700;font-weight:bold"> \n </span style="color: #808080;font-style: italic"> \n </span style="color: #808080;font-style: italic"> \n </span style="color: #808080;font-style: italic"> \n </span style="color: #ff7700;font-weight:bold"> \n </span style="color: #ff7700;font-weight:bold"> \n </span style="color: #808080;font-style: italic"> \n </span style="color: #808080;font-style: italic"> \n </span style="color: #808080;font-style: italic"> \n </span style="color: #808080;font-style: italic"> \n </span style="color: #ff7700;font-weight:bold"> \n </span style="color: #ff7700;font-weight:bold"> \n </span style="color: #808080;font-style: italic"> \n </span style="color: #808080;font-style: italic"> \n </span style="color: black"> \n </span style="color: #483d8b"> \n </span style="color: #66cc66"> \n </span style="color: #483d8b"> \n </span style="color: #66cc66"> \n </span style="color: #483d8b"> \n </span style="color: #66cc66"> \n </span style="color: #483d8b">\n \n </span style="color: black">\n \n </span style="color: #66cc66">\n \n </span style="color: #808080;font-style: italic">\n \n </pre class="python" style="font-family:monospace">
Copy code

Output:

 
apple has the letter e in it.
peach has the letter e in it.
Copy code

How to use enumerate() in Python?

The enumerate() function in python is used to keep a count of iterations while working with iterators.

The enumerate() function associates a counter to an iterable and returns the count object as a response. This enumerated object can then be used directly for loops or converted into a list of tuples using the list() method.

Syntax:

 
enumerate(iterable, start_value)
Copy code

Here,

  • iterable in the above syntax is a sequential structure like list, strings etc.
  • start_value is the index value from which the counter starts. If no value is passed, then it defaults to 0.

Take a look at the below example.

Example: Python program to illustrate the use of enumerate() function.

 
\n \n <pre class="python" style="font-family:monospace">\n \n <span style="color: #808080;font-style: italic">\n \n # given a list of fruits\n \n
l1 \n \n <span style="color: #66cc66">\n \n = \n \n <span style="color: black">\n \n [\n \n <span style="color: #483d8b">\n "apple" \n <span style="color: #66cc66">\n , \n <span style="color: #483d8b">\n "mango" \n <span style="color: #66cc66">\n , \n <span style="color: #483d8b">\n "peach" \n <span style="color: #66cc66">\n , \n <span style="color: #483d8b">\n "banana" \n <span style="color: black">\n ] \n
\n
\n <span style="color: #808080;font-style: italic">\n # printing the tuples (ie, count,element of given list) \n
\n <span style="color: #808080;font-style: italic">\n # in the response object directly \n
\n <span style="color: #ff7700;font-weight:bold">\n for i \n <span style="color: #ff7700;font-weight:bold">\n in \n <span style="color: #008000">\n enumerate \n <span style="color: black">\n (l1 \n <span style="color: black">\n ): \n
\n <span style="color: #ff7700;font-weight:bold">\n print \n <span style="color: black">\n (i \n <span style="color: black">\n ) \n </span style="color: black"> \n </span style="color: black"> \n </span style="color: #ff7700;font-weight:bold"> \n </span style="color: black"> \n </span style="color: black"> \n </span style="color: #008000"> \n </span style="color: #ff7700;font-weight:bold"> \n </span style="color: #ff7700;font-weight:bold"> \n </span style="color: #808080;font-style: italic"> \n </span style="color: #808080;font-style: italic"> \n </span style="color: black"> \n </span style="color: #483d8b"> \n </span style="color: #66cc66"> \n </span style="color: #483d8b"> \n </span style="color: #66cc66"> \n </span style="color: #483d8b"> \n </span style="color: #66cc66"> \n </span style="color: #483d8b">\n \n </span style="color: black">\n \n </span style="color: #66cc66">\n \n </span style="color: #808080;font-style: italic">\n \n </pre class="python" style="font-family:monospace">
Copy code

Output:

 
(0, 'apple')
(1, 'mango')
(2, 'peach')
(3, 'banana')
Copy code
About the Author

This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio