Home Tutorials Python Tutorial For Loop
For Loop

For Loop


Definition: A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).

Why: The for loop is one of the most important loop types in Python. It is used when you want to execute a block of code a fixed number of times or once for every item in a collection.

Syntax

for variable in sequence:
    # code to execute

Example

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

Explanation

  • range(1, 6): This function generates a sequence of numbers starting from 1 up to (but not including) 6.
  • Iterating: The loop runs once for each value in that range. In the first round, i is 1; in the second, i is 2, and so on.
  • Versatility: While this example uses numbers, for loops are widely used to "loop through" lists of names, characters in a string, or keys in a dictionary.

Key Notes

  • Automatic Increment: Unlike a while loop, you do not need to manually increase the counter variable; Python does it for you.
  • The else Keyword: You can add an else block after a for loop to execute code once the loop has finished its iterations.
  • Nested Loops: You can place a for loop inside another for loop (useful for working with grids or lists within lists).
Example

🏋️ Test Yourself With Exercises

Take our quiz on For Loop to test your knowledge.

Exercise »