For loops in Python (13/100 Days of Python)
A for loop is a type of control flow statement that allows you to iterate over a sequence of items, such as a list, a string, or a range. The basic syntax of a for loop includes a variable that represents the item of the sequence on each iteration, the sequence itself, and the code that needs to be executed for each item of the sequence:
for item in sequence:
# code to be executed on each iteration
The item
in the for loop is a temporary variable that takes on the value of each element in the sequence
on each iteration of the loop. The code block indented under the for loop is executed once for each element in the sequence. An example with a list of numbers can be written as:
numbers = [1, 2, 3, 4, 5]
for num in numbers:
print(num)
This code would print the numbers 1, 2, 3, 4, and 5 each on a separate line:
1
2
3
4
5
As you can see, on each iteration of the loop, the value of num
is set to the next element in the numbers
list. The loop continues until all elements in the list have been processed.
In addition to using for loops with lists, you can also use them with the built-in range()
function. The range()
function generates a sequence of numbers, starting from a starting value and ending at an ending value. You can also specify a step value, which determines the amount by which the value should be incremented on each iteration:
# Generate a sequence of numbers from 0 to 9
for i in range(10):
print(i)
# Generate a sequence of numbers from 2 to 8, in increments of 2
for i in range(2, 9, 2):
print(i)
# Generate a sequence of numbers from 10 to 1, in decrements of 2
for i in range(10, 0, -2):
print(i)
You can also use the range()
function with a for loop to iterate over a list using indices:
numbers = [1, 2, 3, 4, 5]
# Iterate over the list using the range() function
for i in range(len(numbers)):
print(numbers[i])
This would output the same result as the first example, but using the range()
function to generate the list of indices to iterate over.
Yet, there is a better way of iterating over indices of a list in Python using the enumerate
function which we will cover later.
What’s next?
- If you found this story valuable, please consider clapping multiple times (this really helps a lot!)
- Hands-on Practice: Free Python Course — for loops
- Full series: 100 Days of Python
- Previous topic: What is the range() function in Python?
- Next topic: While loops