What is Python For Loop?

The for loop in Python is one of the means to instruct the computer to perform a task multiple times. Using the for loop prevents repetitive lines of code while programming.

The for loop is also used to iterate over a sequence, either a list, set, tuple, dictionary, or string. You can use the value of every item in the sequence as variables within the statement you want to execute.

What is The For Loop?

Loops are an essential part of every programming language; they are a means of instructing the computer to perform a task repeatedly. Loops are a useful means of decluttering code and removing repetitions; they automate code and make it cleaner.

The for loop is available in programming languages such as Java, JavaScript, Go, Ruby, and several others. However, the for loop in Python is different from other languages because it works more like an iterator method does in other object-oriented languages.

Basic For Loop Syntax

If you want to execute a print statement five times, you would usually need to do this:

print("Hello world")
print("Hello world")
print("Hello world")
print("Hello world")
print("Hello world")

However, using a for loop, that repetitive code will look like this:

for item in range(5):
  print("Hello world")

The result in both instances will be the same despite the for loop shortening the code dramatically.

The item is a variable of type integer; the value of item increases in each iteration– from 0 to 4 since there are five iterations of the loop and the default value of item is zero-based. Below is an illustration of the increment of the item variable:

for item in range(3):
  print("Hello world", item)

The result of that loop will be:

Hello world 0
Hello world 1
Hello world 2

The range is a built-in function that returns a sequence of numbers that will be the values of the item variable above. When you pass a single number as the range argument, the function will return a sequence of incrementing numbers from 0 to the number just before the argument. For instance, in our example above, we set the argument as 3, and the loop returned three numbers (0, 1, 2).

You can be more specific with the range by passing in two arguments; the first is the starting value, and the second is the number before the sequence will stop. For instance, if we pass (2, 5) as arguments, the value of item will start from 2 and stop at 4:

for item in range(2, 5):
  print("Hello world", item)

The result will be:

Hello world 2
Hello world 3
Hello world 4

There is also room for a third argument in the range function, and it is to define the step. The step is the difference between numbers returned in the sequence; the default step is 1. Below is an illustration of how to use the three arguments:

for item in range(1, 6, 2):
  print("Hello world", item)

The result will be:

Hello world 1
Hello world 3
Hello world 5

Nested For Loops

A nested loop is a loop within a loop and is a common feature of various programming languages. The outer loop runs its first iteration, which contains the inner loop; when the inner loop has finished running, the outer loop is triggered again for its next iteration, which triggers the inner loop again. The nested loop stops when the outer loop has completed its sequence; the inner loop will therefore run multiple times. Below is an illustration of a nested for loop:

for x in range(3):
  for y in range(2):
    print(f"({x}, {y})")

The result of this nested loop will be:

(0, 0)
(0, 1)
(1, 0)
(1, 1)
(2, 0)
(2, 1)

Using The For Loop On Iterables

An iterable in Python is an object that you can iterate or loop over; examples are strings, lists, dictionaries, sets, etc. You can use a for loop to iterate over all iterable object types; for example:

for x in "Python":
  print(x)
    
names = ["Adam", "John", "Stephen"]
for x in names:
  print(x)

The result of looping over these lists will be:

P
y
t
h
o
n
Adam
John
Stephen

Break And Continue Statements

You can use the break statement to stop the for loop before it iterates over all the items; for example:

names = ["Adam", "John", "Stephen"]
for x in names:
  if x == "John":
    break
  print(x)

The result of the above illustration will be Adam; however, if you put the break statement after the print, your result will include Adam because the loop ran completely until the break statement.

On the other hand, you can use the continue statement to skip the current iteration and continue with the next. For example, if you don’t want to print John from the names list, you will do the following:

for x in names:
  if x == "John":
    continue
  print(x)

Read More: What Is While Loop In Python?

Leave a Comment