Tutorials Tonight
Follow Us

for Loop In Python - Complete Guide


In this tutorial, we are going to learn about for loop in Python. We will see how to use it in different ways, iteration over numbers, list, dictionary, tuple, string, range, set, file, etc with multiple examples. We will also see the nesting of loops and how to use a break and continue keywords in for loop.

    Table of Contents

  1. What is loop in Python
  2. for Loop
  3. For loop with index
  4. Break loop
  5. Continue loop
  6. Nested loop
  7. Loop with else

What is loop in Python?

A loop in python is a sequence of statements that are used to execute a block of code for a specific number of times.

You can imagine a loop as a tool that repeats a task multiple times and stops when the task is completed (a condition satisfies).

A loop in Python is used to iterate over a sequence (list, tuple, string, etc.)

There are different types of loops in Python. They are:

Let's see what is a for loop, how to use it, and everything else you need to know.


Python for Loop

A for loop most commonly used loop in Python. It is used to iterate over a sequence (list, tuple, string, etc.)

Note: The for loop in Python does not work like C, C++, or Java. It is a bit different.

for loop in python

Python for loop is not a loop that executes a block of code for a specified number of times. It is a loop that executes a block of code for each element in a sequence.

It means that you can't define an iterator and iterate over increasing or decreasing values like in C.

for Loop Syntax In Python

Use for keyword to define for loop and the iterator is defined using in the keyword.

The iterator is the variable that is used to iterate over the sequence. It is used to access each element in the sequence.

The for loop in Python is defined using the following syntax:

for iterator_variable in sequence:
  # loop body
  # ...

# Flowchart

python for loop flowchart

If you have any sequence of values, you can use for loop to iterate over it.

# Example 1: Looping list

# Using for loop on list
fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi']

# Using for loop
# loop will run the code for each item in the list
for fruit in fruits:
    print(fruit)

Output:

orange
apple
pear
banana
kiwi

# Example 2: Looping tuple

A tuple is also a sequence of values just like a list. It is immutable and enclosed in parentheses instead of square brackets.

# looping over tuples
items = ('one', 'two', 'three')
for item in items:
    print(item)

Output:

one
two
three

# Example 3: Looping string

A string is also a sequence of values just like a list. It is immutable and enclosed in double quotes instead of square brackets.

# looping over string
items = 'looping'
for item in items:
    print(item)

Output:

l
o
o
p
i
n
g

Looping a range of number

You have learned above that for loop in python does not iterate between 2 numbers but over a sequence of items.

So how can we loop over a range of numbers?💭🤔

💡 Simply by creating a sequence of numbers and using the range() function.

range() is a built-in function in Python that creates a sequence of numbers and is used to iterate over a sequence of numbers.

In the for loop, you can replace the sequence with the range() function.

# Example 4: Looping numbers

# looping first 5 numbers
for i in range(5):
    print(i)

Output:

0
1
2
3
4

You can see that the range() function creates a sequence of numbers from 0 to 4. The number 5 is not included in the sequence.

To loop between a given range of numbers m and n you can use range(m, n) (where n is not included). To include n you can use range(m, n+1).

# Example 5: Looping between a range of number

# looping between a range of numbers

# looping from 5 to 10
for i in range(5, 10): # 10 not included
    print(i, end=' ')
print()

# looping 20 to 30 (30 included)
for i in range(20, 31):
    print(i, end=' ')

Output:

5 6 7 8 9
20 21 22 23 24 25 26 27 28 29 30

The range() function has a default increment of 1. You can change the increment by passing your own step as the 3rd argument.

Note: The steps can only be integers either positive or negative. Decimals are not allowed.

# Example 6: Looping with step

# looping with step

# jumping by 2
for i in range(0, 10, 2):
    print(i, end=' ')
print()

# jumping by 3
for i in range(0, 10, 3):
    print(i, end=' ')
print()

# negative step
for i in range(10, 0, -2):
    print(i, end=' ')
print()

Output:

0 2 4 6 8
0 3 6 9
10 7 4 1

Python For loop with index

As you know that python for loop iterates over a sequence of values. But what if you want to access the index of the value in the sequence?🤔

You can access the index of the value in the sequence by using the length of the sequence in loop range function and accessing element in the sequence using an index.

# Example 7: Looping with index

# looping with index
fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi']
for i in range(len(fruits)):
    print(i, fruits[i])

Output:

0 orange
1 apple
2 pear
3 banana
4 kiwi

# Alternate way to get the index

In Python, you can use the enumerate() function to get the index of the value in the sequence.

enumerate() is a built-in function in Python that returns an enumerated object. This object can be used to loop over the sequence and get the index of the value.

# Example 8: Enumerate

# looping with index

fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi']
for i, fruit in enumerate(fruits):
    print(i, fruit)

Output:

0 orange
1 apple
2 pear
3 banana
4 kiwi

Python break for loop

There are situations when you want the loop to stop when a condition is met. Like in a sum of numbers, you want to stop when the sum is greater than 100.

To do this you can use the break keyword to stop and exit the loop. The break is a keyword in Python which is used to exit the loop.

# Example 9: Breaking a loop

# breaking a loop

# break loop when i == 5
for i in range(10):
    if i == 5:
        break
    print(i, end=' ')
print()

# break loop when sum is greater than 100
sum = 0
for i in range(10):
    sum += i * 1
    if sum > 100:
        break
print("Sum = ", sum)

Output:

0 1 2 3 4
Sum =  45

continue for loop python

Just like breaking a loop, you can also continue the loop. Continuing loop means skipping the current iteration and continuing with the next iteration.

To do this you can use the continue keyword to skip the current iteration and continue with the next iteration.

This is helpful when you want to include some specific item from the sequence.

# Example 10: Continuing a loop

# continuing a loop

# continue loop when i == 5 or i == 7
for i in range(10):
    if i == 5 or i == 7:
        continue
    print(i, end=' ')
print()

Output:

0 1 2 3 4 6 8 9

Adding all even numbers from a list of numbers.

# Example 11: Adding evens

# adding evens
  
numbers = [5, 12, 8, 9, 10, 11, 13, 14, 15]
sum = 0
for i in numbers:
    if i % 2 != 0:
        continue
    sum += i
print("Sum = ", sum)

Output:

Sum =  44

Nested for loop python

You can also nest for loops. A nesting loop means to loop over a sequence of sequences.

This is useful when you want to loop over a sequence of items and then loop over the items in that sequence (loop inside the loop).

We will use a nested loop in creating pattern programs in python.

# Example 12: Nested for loop

# nested for loop
size = 5

for i in range(1, size+1):
    # nested loop
    for j in range(1, i+1):
        print("*", end="")
    print()

Output:

*
**
***
****
*****

for loop with else

You can also use else keyword in python for loop. This is useful when you want to execute some code when the loop is finished.

The else block is executed when the loop is finished.

# Example 13: for loop with else

# for loop with else
for i in range(3):
    print(i)
else:
    print("Loop Finished")

Output:

0
1
2
Loop Finished

When there is a break statement in the loop, the else block is not executed.

The else block with break statement is only executed when the break statement is itself not executed. i.e the condition for the break statement is not met.

# Example 15

# for loop with else and break

# else not executed with break statement
for i in range(3):
    if i == 2:
        break
    print(i)
else:
    print("Loop Finished")
print()

# else executed with break statement
for i in range(3):
    if i == 5:
        break
    print(i)
else:
    print("Loop Finished")

Output:

0
1

0
1
2
Loop Finished

Conclusions

We have covered everything that you need to know about for loop in python. You can use for loop to iterate over a sequence of items and start writing your own program.

To practice for loop, you can create start patterns, alphabet patterns, and number patterns in python.

Frequently Asked Questions

  1. How do you repeat a code in Python?

    You can use for loop to repeat a code.

  2. How do you write a for loop?

    You can use for keyword to write a for loop. Example:
    for iterator_variable in sequence:
      # loop body
      # ...