For Loop in Python (with 20 Examples) (2024)

❮ PrevNext ❯

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
    1. for loop syntax
    2. Iteration over numbers
  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:

  • For loop
  • While loop
  • Do while loop

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 (with 20 Examples) (1)

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

For Loop in Python (with 20 Examples) (2)

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

# Example 1: Looping list

# Using for loop on listfruits = ['orange', 'apple', 'pear', 'banana', 'kiwi']# Using for loop# loop will run the code for each item in the listfor fruit in fruits: print(fruit)

Output:

orangeapplepearbananakiwi

# 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 tuplesitems = ('one', 'two', 'three')for item in items: print(item)

Output:

# 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 stringitems = 'looping'for item in items: print(item)

Output:

looping

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 numbersfor i in range(5): print(i)

Output:

01234

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 10for 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 920 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 2for i in range(0, 10, 2): print(i, end=' ')print()# jumping by 3for i in range(0, 10, 3): print(i, end=' ')print()# negative stepfor i in range(10, 0, -2): print(i, end=' ')print()

Output:

0 2 4 6 80 3 6 910 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 indexfruits = ['orange', 'apple', 'pear', 'banana', 'kiwi']for i in range(len(fruits)): print(i, fruits[i])

Output:

0 orange1 apple2 pear3 banana4 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 indexfruits = ['orange', 'apple', 'pear', 'banana', 'kiwi']for i, fruit in enumerate(fruits): print(i, fruit)

Output:

0 orange1 apple2 pear3 banana4 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 with if statement 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 == 5for i in range(10): if i == 5: break print(i, end=' ')print()# break loop when sum is greater than 100sum = 0for i in range(10): sum += i * 1 if sum > 100: breakprint("Sum = ", sum)

Output:

0 1 2 3 4Sum = 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 == 7for 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 = 0for i in numbers: if i % 2 != 0: continue sum += iprint("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 loopsize = 5for 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 elsefor i in range(3): print(i)else: print("Loop Finished")

Output:

012Loop 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 statementfor i in range(3): if i == 2: break print(i)else: print("Loop Finished")print()# else executed with break statementfor i in range(3): if i == 5: break print(i)else: print("Loop Finished")

Output:

01012Loop 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 # ...

❮ PrevNext ❯

For Loop in Python (with 20 Examples) (2024)

References

Top Articles
Latest Posts
Article information

Author: Carmelo Roob

Last Updated:

Views: 6210

Rating: 4.4 / 5 (65 voted)

Reviews: 80% of readers found this page helpful

Author information

Name: Carmelo Roob

Birthday: 1995-01-09

Address: Apt. 915 481 Sipes Cliff, New Gonzalobury, CO 80176

Phone: +6773780339780

Job: Sales Executive

Hobby: Gaming, Jogging, Rugby, Video gaming, Handball, Ice skating, Web surfing

Introduction: My name is Carmelo Roob, I am a modern, handsome, delightful, comfortable, attractive, vast, good person who loves writing and wants to share my knowledge and understanding with you.