Python for Loop
In Python, for loops are used to iterate over a sequence of items such as lists, tuples, strings, and dictionaries. The basic syntax of a for loop is as follows:
1for variable in sequence: 2 # execute this block of code for each item in the sequence
The variable
is a placeholder that takes on the value of each item in the sequence
as the loop iterates. The code in the loop block is executed once for each item in the sequence.
For example, the following code will iterate over a list of numbers and print each number:
1numbers = [1, 2, 3, 4, 5] 2for num in numbers: 3 print(num)
Output:
11 22 33 44 55
You can also use the range()
function to create a range of numbers to iterate over. The range()
function takes one, two, or three arguments, the start, stop and step, respectively.
For example, the following code will iterate over the range of numbers from 0 to 9 and print each number:
1for num in range(5): 2 print(num)
Output:
10 21 32 43 54
You can also use the enumerate()
function to iterate over a sequence and keep track of the index of each item. The enumerate()
function takes an iterable and returns an object that contains the index and the value of each item.
For example, the following code will iterate over a list of numbers and print the index and the value of each number:
1numbers = [1, 2, 3, 4, 5] 2for index, num in enumerate(numbers): 3 print(index, num)
Output:
10 1 21 2 32 3 43 4 54 5
Python for loops are used to iterate over a sequence of items such as lists, tuples, strings, and dictionaries. The for loop allows you to execute a block of code for each item in the sequence. You can also use the range()
function to create a range of numbers to iterate over, and the enumerate()
function to keep track of the index of each item. Understanding how to use for loops and the different ways to iterate over sequences is an essential part of becoming proficient in Python programming.