For loop
For Loop in Python
The for loop in Python is used to iterate over a sequence such as a list, tuple, string, set, or a range of numbers. It allows you to execute a block of code repeatedly for each item in the sequence.
Basic Syntax
-
variable: takes each value from theiterableone by one. -
iterable: a collection (like list, string, tuple, etc.) you want to loop through.
Types of Iterables You Can Loop Through
You can use a for loop to iterate over:
-
Lists – ordered and mutable collections
-
Tuples – ordered and immutable collections
-
Strings – sequences of characters
-
Sets – unordered collections of unique elements
-
Ranges – sequences of numbers
1. Iterating Through a List
Output:
2. Iterating Through a String
Output:
3. Iterating Through a Range
Output:
Using for Loop with if Condition
You can combine a for loop with an if statement to filter values. Example: Print multiples of 6 within a range.
Output:
Using Index While Iterating
To access both index and value from a list, use range(len(list)):
Output:
👀Note: Direct iteration over the list is preferred when index isn't needed:
Accessing Both Index and Element
Output: