Lazy Programming Series – For Loop
A for loop is used to iterate over a sequence (such as a list, tuple, string, or range) or any iterable object in Python. The basic syntax of a for loop in Python is as follows:
Here’s how it works:
- The for keyword is used to start a for loop.
- item is a variable that represents each element in the iterable as the loop iterates through it. You can name this variable whatever you want.
- iterable is the sequence or collection over which the loop iterates. It can be a list, tuple, string, range, or any other iterable object.
- The colon : at the end of the for statement indicates the beginning of the indented block of code that will be executed for each iteration of the loop.
- Inside the indented block, you write the code that you want to execute for each item in the iterable.
Here’s a simple example that demonstrates the usage of a for loop to iterate over a list:
In this example:
- fruits is a list containing three elements.
- The for loop iterates over each element in the list.
- For each iteration, the variable fruit takes on the value of the current element, and the print() function prints it.
You can also use the range() function to generate a sequence of numbers and iterate over it using a for loop. For example:
In this example:
- range(5) generates a sequence of numbers from 0 to 4 (inclusive).
- The for loop iterates over each number in the sequence, and i takes on the value of the current number in each iteration.