DEV Community

Endurance Okpanachi
Endurance Okpanachi

Posted on • Edited on

Python for Loop - A Beginner’s Guide

The for loop in Python is used to iterate over a sequence, including list, tuple, string, or other iterable objects. Yet, its functionality differs from loops in languages like C++. It works similarly to the iterator methods in other object-oriented languages.

The syntax of the Python for loop is written as:

for variable in iterable:
     #statement
Enter fullscreen mode Exit fullscreen mode

In the code above, the for keyword indicates the start of the loop and instructs Python to perform the action in the statement block of code on each item of the sequence (or iterable).

Also, item serves as a placeholder in the code and can be replaced with any name or word. Examples of different ways you can use the for loop are contained in the sections below.

Looping Through a List

A list in Python can contain objects such as Boolean, strings, integers, and floats and you can as well loop through all of them using the for loop.

For example, the code below prints out all the items contained in the list on a new line:

myList = [23, "life", True , 24.0, "learn"]
for i in myList:
    print(i)
Enter fullscreen mode Exit fullscreen mode

The i in the code above is a variable representing all the items in the list. Also, the line for i in myList indicates that we want to access all the items contained in the variable myList.

So when you run the code above in your editor or IDE, as shown below, each of the items contained in the list will be printed on a new line.

23
life
True
24.0
learn
Enter fullscreen mode Exit fullscreen mode

Let’s take another example to get a better understanding of looping through a list with a little twist. This time, we want the output to printout horizontally. We can do this by adding the end parameter.

newList = [30, 40, 70, "learn", 90]
for items in newList:
    print(items, end= " ")
Enter fullscreen mode Exit fullscreen mode

This code creates a list called newList containing integers (30, 40, 70, 90) and a string ("learn"). Then, it iterates through each item in the list using a for loop. Within the loop, it prints each item followed by a space.

The end=" " parameter in the print function specifies that after printing each item, a space should be used as the separator instead of the default newline character. So, when you run this code, it will print each item in the list separated by a space, as shown below:

30 40 70 learn 90 
Enter fullscreen mode Exit fullscreen mode

Looping Through a Tuple

You can also loop through other sequences including Tuples, using the Python for Loop. The code below is used to print out each of the objects in the Tuple on a new line:

myTuple = ("life", 24, 75, False, 43.0, "why")
for i in myTuple:
   print(i)
Enter fullscreen mode Exit fullscreen mode

It is not compulsory you use the i in the statement - you can use any letter or word in there. So, if you run the code, the following output will be shown:

life
24
75
False
43.0
why
Enter fullscreen mode Exit fullscreen mode

Let us loop through a tuple with another example, without printing the output on a new line for each items (with the end parameter).

newTuple = (32, 56, "tuple", 40.2)
for items in newTuple:
    print(items, end= " ")
Enter fullscreen mode Exit fullscreen mode

Output:

32 56 tuple 40.2 
Enter fullscreen mode Exit fullscreen mode

Looping Through a String

You can also loop through a string the same way we looped through a list and tuple above using the same syntax. The following code loops through all the characters of the string and prints each of them on a new line:

myString = "Python"
for i in myString:
      print(i)
Enter fullscreen mode Exit fullscreen mode

If you run the code above, the following output will be executed:

P
y
t
h
o
n
Enter fullscreen mode Exit fullscreen mode

Now let’s loop through another string with another example:

newString = "I am learning Python"
for items in newString:
     print(items, end= "")
Enter fullscreen mode Exit fullscreen mode

Output:

I am learning Python
Enter fullscreen mode Exit fullscreen mode

Nested for Loop

Basically, a loop within a loop is termed a nested for Loop and is supported by most programming languages including Python. It’s usually indented under the main loop. The main loop is called the outer loop, while the nested loop is called the inner loop. The basic syntax for the nested for loop is as follows:

for outer_variable in outer_sequence:
  #outer loop statement

    for inner_variable in inner_sequence:
       #inner loop statement
Enter fullscreen mode Exit fullscreen mode

Nested for loops in Python allows iteration over multiple sequences within each other. The outer loop iterates through one sequence, while the inner loop iterates through another sequence for each iteration of the outer loop.

As per the syntax above, the code iterates through outer_sequence, then iterates through inner_sequence for each outer value, executing statements for the two loops.

Example: In the following code, we will use the Python nested for loop to multiply each content of the second variable y by every items in the x variable:

x = [4, 5]
y = [2, 3]
for i in x:
    for j in y:
        print(i*j)
Enter fullscreen mode Exit fullscreen mode

We used the variable i to access all the items contained in x as well as j to access all the content of y and we multiplied them using the * operator.

Also, notice that the inner for loop is indented below the outer loop. If it’s not properly indented, the code will give an indentation error when you print. If you run the code, the output will be:

8
12
10
15
Enter fullscreen mode Exit fullscreen mode

However, you can prevent the code from printing each outcome on different lines. You can do this by using the end parameter within the print() function.

By default, the print() function automatically adds a new line (\n) to the end of any output it prints. The end parameter allows you to stop that default behaviour.

So, if we use the end parameter on the initial nested for loop code, the code will look like this:

x = [4, 5]
y = [2, 3]
for i in x:
    for j in y:
        print(i*j, end= " ") 
Enter fullscreen mode Exit fullscreen mode

Output:

8 12 10 15 
Enter fullscreen mode Exit fullscreen mode

Notice that the output is printed out in form of a row instead of the initial column. You can also replace the spacing between the output to a comma (,) by writing it like print(i*j, end= ","). Running the code in this form will add commas between all the output.

Looping Through a Range

The for loop in Python can also be used to loop through a range of sequences with the range function (range()). It is used to generate a sequence of numbers and can take a maximum of 3 arguments (start, stop, and step size).

The default value of the first argument in the range function is (0). Meaning if not set to any number, the range will start printing from zero (0). Also, the second argument is the number where the sequence stops (usually n - 1).

Finally, the third optional argument (step size) is by default set to 1 and can be changed to any size, depending on what you want to achieve with the code. The following is the basic syntax of looping through a range of sequence:

for var_name in range(start, stop, stepsize):
        #statement
Enter fullscreen mode Exit fullscreen mode

With the help of the syntax above, let’s run a simple code that will loop through the sequence of a range below:

for var in range(0,16,2):
    print(var)
Enter fullscreen mode Exit fullscreen mode

The starting point of the sequence in this code is set at 0 and will iterate up to and not including 16, with a step size of 2.

However, it is not compulsory to set a step size or a starting point in your code. The default step and starting point are set at 1 and 0 respectively. So, If you run the code, the following output will be printed:

0
2
4
6
8
10
12
14

Enter fullscreen mode Exit fullscreen mode

Looping Through a Range with Else and If Statements

You can also make conditional statements in your Python codes while looping through a range with the else and if statements.

As you may have known, both statements works together with some conditions. The else statement will execute based on the outcome of the if statements (true or false).

Now, let’s loop through a range with these statements:

for i in range (2,16,2):
    if i == 8:
        pass
    print(i)
else:
    print("end of the loop")
Enter fullscreen mode Exit fullscreen mode

The above code is looping through a range with a starting number of 2, stopping number of 16, and 2 as the step size. If the code is without an if statement or condition, it will will run till the end down to the else block.

For a code with an if statement like the one above, the else block will on only execute based on the conditions that comes with the if block. For this code, the pass statement is a null operation; nothing happens if it is executed. It is usually used as a placeholder. Meaning, the code will run to the else block successfully.

So, if you run the code above, the following output will be executed:

2
4
6
8
10
12
14
end of the loop
Enter fullscreen mode Exit fullscreen mode

However, if the if block in the code has other conditions such as break and continue instead of the pass statements, the outcome of the code will change. Let’s include the break statement into the code above and see the outcome:

for i in range (2,16,2):
    if i == 8:
        break
    print(i)
else:
    print("end of the loop")
Enter fullscreen mode Exit fullscreen mode

Output:

2
4
6
Enter fullscreen mode Exit fullscreen mode

Notice that the code did not run down to the else block. This is because there is a break statement in the code. The break statement executed when i == 8. So the code exited the loop prematurely and didn't reach the else block. If the break statement had not been encountered, the loop would have continued iterating through all the numbers in the specified range, and then the else block would have executed, printing "end of the loop".

Top comments (0)