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

for variable in iterable: # code block
  • variable: takes each value from the iterable one 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

# Loop through a list and print items numbers = [10, 20, 30, 40] for num in numbers: print(num)

Output:

10 20 30 40

2. Iterating Through a String

# Loop through a string and print characters word = "gfg" for char in word: print(char)

Output:

c s k

3. Iterating Through a Range

# Loop through numbers 0 to 4 for i in range(5): print(i)

Output:

0 1 2 3 4

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.

for i in range(20): if i % 6 == 0: print(i)

Output:

0 6 12 18

Using Index While Iterating

To access both index and value from a list, use range(len(list)):

numbers = [10, 20, 30, 40] for i in range(len(numbers)): print(numbers[i])

Output:

10 20 30 40

👀Note: Direct iteration over the list is preferred when index isn't needed:

for num in numbers: print(num)

Accessing Both Index and Element

# Print index and item numbers = [10, 20, 30, 40] for i in range(len(numbers)): print(i, numbers[i])

Output:

0 10 1 20 2 30 3 40

Popular Posts