For Loop in Python
The for loop in Python is a control flow statement used to iterate over a sequence (like lists, tuples, dictionaries, sets, or strings) or any other iterable object. It is versatile and allows efficient traversal through elements in a sequence.
Key Points on For Loop:
- The for loop is typically used when the number of iterations is known or the structure is iterable.
- It automatically ends when it reaches the end of the sequence or iterable.
- Commonly used with the
range()
function to generate sequences of numbers. - Nested for loops allow more complex data structures to be handled.
- Control statements like break and continue can be used to manage the flow.
Syntax of For Loop:
Syntax Example
for element in iterable:
# Code to execute for each element
Example of For Loop in Python:
This example demonstrates a basic for loop that iterates over a list of numbers and prints each number.
Code Example
numbers = [1, 2, 3, 4, 5]
for number in numbers:
print(number)
Output
1
2
3
4
5
2
3
4
5
Detailed Explanation:
- Iterable: The sequence or object to loop over, such as a list or a range of numbers.
- Loop Variable: The variable (like
number
above) that represents each element in the iteration. - Range: The
range()
function is often used to generate a sequence of numbers, especially in loops. - Nested For Loops: Useful for multi-dimensional data structures, such as lists of lists.
Using the for loop effectively enables efficient data handling and iteration in Python programs.