Python for Loop
In Python, for
loops are used to iterate over a sequence (such as a string, list, tuple, or dictionary) and perform a set of operations for each element in the sequence. The basic syntax of a for
loop in Python is:
for element in sequence: # execute this block of code for each element in the sequence
Here, element
is a variable that represents each element in the sequence, and sequence
is the sequence to be iterated over. The code inside the for
loop is indented and will be executed once for each element in the sequence.
For example, here's a simple for
loop that iterates over a list of numbers and prints each number:
numbers = [1, 2, 3, 4, 5] for num in numbers: print(num)
Output:
1 2 3 4 5
In this example, the for
loop iterates over the list of numbers
, and for each num
in the list, it prints the value of num
to the console.
You can also use the range()
function to create a sequence of numbers to iterate over. The range()
function generates a sequence of numbers from a starting point to an ending point (excluding the ending point), with an optional step size. Here's an example:
for i in range(1, 6): print(i)
Output:
1 2 3 4 5
In this example, the for
loop uses the range()
function to generate a sequence of numbers from 1 to 5, and for each number in the sequence, it prints the value of i
to the console.
You can also use the enumerate()
function to iterate over a sequence and access both the index and the value of each element in the sequence. Here's an example:
fruits = ['apple', 'banana', 'cherry'] for i, fruit in enumerate(fruits): print(i, fruit)
Output:
0 apple 1 banana 2 cherry
In this example, the for
loop uses the enumerate()
function to iterate over the list of fruits
, and for each i
and fruit
in the list, it prints the index (i
) and the value of the fruit (fruit
) to the console.