Loops in Python – The Ultimate Tutorial for Beginners

In this article, I will show you how to work with loops in Python. Loops allow us to execute a single line of code more than once.

This process of executing a line or multiple lines of code more than once is called iteration. Iteration is one of the most crucial concepts of coding.

Python has two types of loops – while and for. The basic concept is the same, but the way of working is different.

If you need a little refresher on Python, check out this cheat sheet for reference:

I will discuss both concepts thoroughly with examples to make sure you are comfortable with loops in Python.

Video tutorials on loops in Python are also availableCheck out the following course:

For Loop

In the first part, let’s talk about for loops.

The for loop is one of the two most popular and commonly used loops in programming.

It iterates over a sequence or any iterable object. The concept of for loops in Python are similar to the for loops in other popular programming languages such as Java and JavaScript but have minor syntax differences.

Observe the following syntax:

for I in sequence:
	statements

We iterate through the items of the sequence and store them inside the I during each iteration.

We can use such loops on sequences such as a list, tuple, and any other iterable object.

There are two ways of using the for loop:

  1. Iterating over the sequence
  2. By using the range() function

We will discuss both these ways in this article.

For Loops With Lists

The most common use of for loops in Python is to iterate over lists.

 Let’s start with a simple example:

myList = [1, 2, 3, 4, 5]

for i in myList:
	print("The value of i is: ", i)

Output:

The value of i is:  1
The value of i is:  2
The value of i is:  3
The value of i is:  4
The value of i is:  5

In the above code, we are iterating over the list myList using a for loop and printing out each item on the list. 

The execution of the for loop will end when all the items on the list are covered.

Let’s talk about the range() function.

The range() function generates a sequence. It has a starting point and an ending point.

Observe the following code:

for i in range(0,10):
	print("The value of i is: ", i)

Output:

The value of i is:  0
The value of i is:  1
The value of i is:  2
The value of i is:  3
The value of i is:  4
The value of i is:  5
The value of i is:  6
The value of i is:  7
The value of i is:  8
The value of i is:  9

Our loop iterated over a range of values from 0 & 10 and printed them out.

Besides, we can manually set the range to any number we like.

Here’s another example:

for i in range(1, 4):
	print(i)

Output:

1
2
3

Instead of passing 0 & 10, we passed 1 & 4 to our range()function. As a result, our iteration starts from 1 and ends at the index position before the value 4.

Let’s say we have a list where we don’t know its length. Our task is to calculate the length of our list. So how are we supposed to do that?

Well, we can use the len() function.

For example:

myList = [29,87,32,45,7,5,12,64,344,64,13,53]
print(len(myList))

Output:

12 

What if we want our iteration to continue till the second item from the last on our list?

That’s where the len() function comes in.

Going back to the myList, we want to iterate and print everything till the value 13 using a for loop. And here’s how we can do it:

for i in range(0,len(myList)- 1):
  print(myList[i])

Output:

29
87
32
45
7
5
12
64
344
64
13

Here, the range() function sets our range between 0 and the second-last item on our list.

To select the second-last item, we have to define the ending parameter of the range() function to be len(myList) - 1.

For example, the length of the myList is 12.

If we wanted all the values, our function would look like range(0,len(myList)).

But we don’t want that. Instead, we want the second-last item. As a result, we have range(0,len(myList) -1).

And then storing a value from our range() function as indexes during each iteration. After that, for each index value, we print out the values from myList

Now, I am assuming you know how indexing and slicing work in Python. If not, you may want to brush up on those first before working with loops in Python.

For Loops With Tuples

We can directly iterate over a tuple using a for loop. Not only that, but we can also use the range() function.

First, let’s start with a simple example:

myTuple = (1, 2, 3, 4, 5)

for i in myTuple:
	print("The value of i is: ", i)

Output:

The value of i is:  1
The value of i is:  2
The value of i is:  3
The value of i is:  4
The value of i is:  5

Let’s try with the range() function:

for i in range(1, len(myTuple)):
	print(myTuple[i])

Output:

2
3
4
5

For Loops With Dictionaries

Dictionaries in Python are different from other collections. Instead of storing data linearly, it uses the key-value pairs.

The following are the ways to iterate over a dictionary using the for loop:

  • We can iterate over the keys.
  • Iterate over the values.
  • Also, iterate over both keys and values.

Let’s discuss each of the above one by one.

Iterating Over Keys

By default, a for loop will automatically iterate over keys of a dictionary.

For example:

myDict = { 'a' : 1, 'b' : 2, 'c' : 3}

for key in myDict:
	print("Key: ", key)

Output:

Key:  a
Key:  b
Key:  c

Iterating Over Values

To iterate over the values, we need to use the method values() with our for loop.

For example:

myDict = { 'a' : 1, 'b' : 2, 'c' : 3}

for value in myDict.values():
	print("Value: ", value)

Output:

Value:  1
Value:  2
Value:  3

Iterating Over Keys & Values

We can also iterate over both keys and values using the items() method.

For example:

myDict = { 'a' : 1, 'b' : 2, 'c' : 3}

for key, value in myDict.items():
  print("Key: ", key)
  print("Value: ", value)

Output:

Key:  a
Value:  1
Key:  b
Value:  2
Key:  c
Value:  3

For Loops With Strings

Strings in Python are also iterable. Let’s see how it works using a for loop.

myString = "Hello World!"

for ch in myString:
	print(ch)

Output:

H
e
l
l
o
 
W
o
r
l
d
!

Similarly, we can use the for loop with range() function to iterate over a String.

myString = "Hello World!"

for index in range(0,len(myString)):
	print(myString[index])

Output:

H
e
l
l
o
 
W
o
r
l
d
!

Similar to the previous example. But this example was to show you that we can use the range() function with Strings as well. And also, use the index to access the character of a String. 

Read: Python Modules & Packages for Absolute Beginners

For Loops With Else Block

We may face situations in which the execution never enters the iteration.

Observe the following code:

l = []

for i in l:
    print(i)

If we execute this code, the execution will not enter the iteration because the list l is empty. Thus, you can use the else block to run a different code if the for loop does not execute.

l = []

for i in l:
    print(i)
else:
	print("Inside else block..")

Output

Inside else block..

So, if there are no conditions for iteration, then else block comes into play. 

Break and Continue

Often you may need to break away or alter a for loop during the middle of its iterations. And that’s where the keywords break and continue come into play.

Break

Whenever a loop encounters a break statement, the loop terminates.

For example:

l = [1, 2, 3, 4, 5]

for i in l:
	if i == 3:
		break
	print("The value of i is: ", i)

Output:

The value of i is:  1
The value of i is:  2

Understand how the loop breaks when i == 3. The break statement is present inside the if block.

So, when the value of i is 3, the break statement is executed.

The break statement will terminate the execution of the loop at the very point it is present. No further iteration takes place, and it ignores all the code that comes after.

Continue

You can use the continue keyword whenever you may need to skip a single iteration.

Let’s say we have the following list:

l = [1, 2, 3, 4, 5]

Here, we want to skip 3 and continue with the next iteration. 

And to do that, we can type:

l = [1, 2, 3, 4, 5]

for i in l:
	if i == 3:
		continue
	print("The value of i is: ", i)

Output:

The value of i is:  1
The value of i is:  2
The value of i is:  4
The value of i is:  5

Similar to the previous example, we have the continue statement inside an if block. When i == 3, the continue statement will execute and skip a single iteration. As a result, it skips executing the rest of the code during this iteration.

Nested For Loops

Nested for loops are common in programming. Let’s understand how they work through an example:

l1 = [1, 2, 3]
l2 = [100, 200, 300]

for i in l1:
    print("The value of i is: ", i)
	
    for j in l2:
        print("The value of j is: ", j)

The inner loop will run entirely for every iteration of the outer one. The execution is a bit complicated. Let’s try to understand step by step:

First iteration:

i = 1. “The value of i is: 1” is printed.

j = 1. The inner while loop will execute three times.

Second iteration:

i = 2. “The value of i is: 2” is printed.

j = 1. The inner while loop will execute three times.

Third iteration:

i = 3. “The value of i is : 3” is printed.

j = 1. The inner while loop will execute three times.

And here’s the output:

The value of i is:  1
The value of j is:  100
The value of j is:  200
The value of j is:  300
The value of i is:  2
The value of j is:  100
The value of j is:  200
The value of j is:  300
The value of i is:  3
The value of j is:  100
The value of j is:  200
The value of j is:  300

This example brings us to the end of the for loop section. Next, we will discuss while loops, which is another looping technique you can use to simplify your code.

Read: Data Structures & Algorithms in Python – Recursion

While Loops in Python

A while loop becomes handy if you don’t know how many times a loop should run. In other words, when you are not dealing with lists or arrays.

The while loops in Python are easy to create. We use the keyword while.

Here’s the syntax:

while condition:
	
	statement

A condition is necessary.

Without a condition, the loop will never break. So let’s start with a simple example:

x = 0

while x < 5:
	print("The value of x is: ", x)

Observe the above code.

Initially, the value of x is 0, and the condition is x less than 5. It means the while loop should run till the value is less than 5. But there is one problem. The value of x is 0, and it will always remain less than 5.

As a result, this loop will run infinite times since there is no way to break away from the condition.

There should be something, which will alter the value of x so that the condition can meet.

Let’s change it up a bit:

x = 0

while x < 5:
	print("The value of x is: ", x)
	x = x + 1

Now, observe the above code again. There is one more statement:

x = x + 1

The value of x will increase with every iteration, and eventually when it becomes 5, the loop breaks.

And the end result is:

The value of x is:  0
The value of x is:  1
The value of x is:  2
The value of x is:  3
The value of x is:  4

So. the loop executes the print statement 5 times. Let’ try to understand the execution of the while loop step by step:

First iteration:

x = 0, and 0 is less than 5. “The value of x is: 0” is printed.

Second iteration:

x = 1, and 1 is less than 5. “The value of x is: 1” is printed.

Third iteration:

x = 2, and 2 is less than 5. “The value of x is: 2” is printed.

Fourth iteration:

x = 3, and 3 is less than 5. “The value of x is: 3” is printed.

Fifth iteration:

x = 4, and 4 is less than 5. “The value of x is: 4” is printed.

After the fifth iteration, the value of x becomes 5, which is equal to 5, thus breaking the condition.

When working with while loops in Python, remember that it needs a condition and a code to break that condition.

While Loop With Else Statement

We can have a situation in which our code never enters the while loop.

For example:

x = 10

while x < 5:
    print("The value of x is: ", x)
    x = x + 1

The value of x is 10, and the condition is x < 5. Our code will not enter the loop.

Now, suppose we want to execute something else when this happens.

In such cases, we can use the else statement or block.

So, for example, we can do this:

x = 10

while x < 5:
    print("The value of x is: ", x)
    x = x + 1
else:
	print("The while loop is not executed")

There is a print statement in the else block. Let’s run the code and see the result:

The while loop is not executed

While Loops With Break & Continue

Similar to what we saw with for loops, we can also use the keywords break and continue

They are useful for breaking away or altering a while loop during its iterations.

Break

If a loop encounters a break statement, the loop terminates.

For example:

x = 0

while x < 5:
  print("The value of x is: ", x)
  x = x + 1
  break

The break statement is present at the end of every iteration. Let’s see what happens.

The value of x is:  0

Continue

You can also use the continue statement with while loops if you need to skip a single iteration.

x = 0

while x < 5:
	x = x + 1
	if( x == 3):
		continue
	print("The value of x is: ", x)

As soon as the x is 3, the code executes an if statement and inside that we have the continue keyword.

In other words, our loop will skip a single iteration and move on to the next one when x is 3.

Here’s the output:

The value of x is:  1
The value of x is:  2
The value of x is:  4
The value of x is:  5

Notice that the print statement is missing when x is 3 because of the continue keyword.

It is also necessary to place x = x + 1 before the continue keyword. Otherwise, it will skip that statement as well. In which case, x will not increment from 3

While Loops With Python Collections

Loops in Python are frequently used with collections to iterate over them.

You can use while loops to access the elements one by one or manipulate mutable collections such as lists.

Let’s iterate over a Python list using a while loop.

l = [1,2,3,4,5]
x = 0
while x < len(l):
    print(l[x])
    x = x + 1

Here we have the len() method with the condition. The loop is using x to access the elements on our list. And the while loop will run until the value of x is less than the total length of the list. 

Output:

1
2
3
4
5

Moreover, we can modify a list using while loops.

For example:

l = [1,2,3,4,5]
x = 0
while x < len(l):
    
    if l[x] % 2 ==0:
        l[x] = l[x] * 2

    x = x + 1

print("list: ", l)

Output:

list:  [1, 4, 3, 8, 5]

During each iteration, the code checks if the element is an even number or not.

If the number is even, then its value is doubled.

As a result, we can see some of the values are updated.

On the other hand, we can also use the while loop with other collections such as tuple and dictionaries.

Nested While Loops

Often you may need to nest loops in Python to work out specific problems. Although I am not a big fan of nested loops, they may prove to be handy at some point.

So, let’s see how they work. Observe the following example:

x = 0

while x < 3:
    print("The value of x is: ", x)
    x = x + 1
    y = 0
    while y < 3:
        print("The value of y is: ", y)
        y = y + 1

Observe the code above. The outer while loop will run until the value of x is less than 3, and the inner will run until the value of y is less than 3.

The execution is a bit complicated. Let’s try to understand step by step.

First Iteration:

x = 0 and 0 is less than 3. "The value of x is : 0" is printed.

y = 0 and 0 is less than 3. The inner while loop will execute three times.

Second Iteration:

x = 1 and 1 is less than 3. "The value of x is: 1" is printed.

y = 0 and 0 is less than 3. The inner while loop will execute three times.

Third Iteration:

x = 2 and 2 is less than 3. "The value of x is: 2" is printed.

y = 0 and 0 is less than 3. The inner while loop will execute three times.

In the fourth iteration, the value of x becomes 3, thus breaking the execution of the outer while loop.

The whole execution depends on the outer loop because the value of y starts at 0 in every iteration.

The inner while loop will execute three times in each iteration of the outer one.

And here’s the output of our code:

The value of x is:  0
The value of y is:  0
The value of y is:  1
The value of y is:  2
The value of x is:  1
The value of y is:  0
The value of y is:  1
The value of y is:  2
The value of x is:  2
The value of y is:  0
The value of y is:  1
The value of y is:  2

Conclusion

Finally, we are here at the end of our loops in the Python tutorial. I know this article is quite long, but I wanted it to be as informative as possible.

Python tutorial you may want to read:

When dealing with loops in Python, here are few points that you should remember:

  • It is ideal to use for loops when dealing with sequences or collections.
  • while loop is best when you are unsure regarding how many times your loops should run.
  • The break and continue statements should exist within an if statement.
  • When dealing with while loops, always make sure there is a valid condition.
  • There should always be some logic when using while loops to alter the condition so the loop can break and not run indefinitely.

Also, I also like to recommend the following video courses on loops in Python from Linkedin Learning:

Can you differentiate the use cases between the two loops in Python?

Leave a Reply