Popular Searches
Popular Course Categories
Popular Courses

Working with for Loops

Working with for Loops

Loops and Iteration in Python

Working with for Loops in Python

Course: Python Programming

Topic: Working with for Loops

Course Link: Python Training Course – JustAcademy

Demo Link: Register for a Course Demo

Website: JustAcademy Official Website


1. Introduction to for Loops in Python

A loop is a programming structure that repeatedly executes a block of code. In Python, the for loop is used to iterate over items in a sequence or other iterable object. It is commonly used to process strings, lists, tuples, dictionaries, sets, ranges, and data returned by other operations.

Instead of writing the same statement several times, a programmer can use a loop to perform the task efficiently. For example, a for loop can print a list of names, calculate the total of several numbers, process product records, or display a multiplication table.

1.1 Why Are for Loops Important?

  • They reduce repetitive code.
  • They make it easy to process each item in a collection.
  • They support calculations involving multiple values.
  • They are useful for reading and processing text.
  • They help automate tasks such as report generation and data analysis.
  • They can be combined with conditions to filter or classify data.

1.2 A Simple Example

for number in range(1, 6):
    print(number)

Output:

1
2
3
4
5

The loop obtains each number from the range and assigns it to the variable number. The indented statement runs once for each value.

2. Syntax of a for Loop

The basic syntax of a Python for loop is:

for variable in iterable:
    # Statements to execute for each item
    statement
Component Meaning
for Keyword that starts the loop.
variable Name that receives the current item on each iteration.
in Keyword that separates the loop variable from the iterable.
iterable An object that provides items one at a time, such as a list, string, tuple, or range.
Colon (:) Marks the beginning of the loop body.
Indented block Contains the statements executed during each iteration.

2.1 Example

fruits = ["Apple", "Banana", "Mango"]

for fruit in fruits:
    print(fruit)

Output:

Apple
Banana
Mango

During the first iteration, fruit contains "Apple". During the second iteration, it contains "Banana". During the third iteration, it contains "Mango".

3. Understanding Iteration

Iteration means accessing items one at a time. A for loop requests an item from an iterable, assigns that item to the loop variable, and executes the loop body. It repeats this process until the iterable has no more items.

3.1 Step-by-Step Example

colors = ["Red", "Green", "Blue"]

for color in colors:
    print("Color:", color)

Output:

Color: Red
Color: Green
Color: Blue
Iteration Value of color Action
1 "Red" Prints Color: Red
2 "Green" Prints Color: Green
3 "Blue" Prints Color: Blue
End No next item The loop finishes.

3.2 Important Points

  • The loop body executes once for each item produced by the iterable.
  • The order of iteration depends on the iterable.
  • A list preserves its element order, while a set does not guarantee a meaningful iteration order.
  • If the iterable is empty, the loop body executes zero times.
  • Each iteration assigns the next item to the loop variable.

4. Using range() with for Loops

The built-in range() function generates a sequence of integers. It is often used when a loop needs to repeat a known number of times or when numeric values are required.

4.1 range(stop)

When one argument is provided, range(stop) starts at zero and stops before the specified value.

for number in range(5):
    print(number)

Output:

0
1
2
3
4

The stop value is excluded. Therefore, range(5) produces five values: 0 through 4.

4.2 range(start, stop)

When two arguments are provided, the first argument defines the starting value and the second defines the exclusive stopping value.

for number in range(2, 7):
    print(number)

Output:

2
3
4
5
6

4.3 range(start, stop, step)

The third argument specifies the increment or decrement between generated values.

for number in range(2, 11, 2):
    print(number)

Output:

2
4
6
8
10

A negative step can generate values in descending order.

for number in range(5, 0, -1):
    print(number)

Output:

5
4
3
2
1

4.4 range() Reference Table

Expression Generated Values Purpose
range(4) 0, 1, 2, 3 Four iterations starting from zero.
range(1, 5) 1, 2, 3, 4 Starts at 1 and stops before 5.
range(0, 10, 3) 0, 3, 6, 9 Increases by 3.
range(5, 0, -1) 5, 4, 3, 2, 1 Counts down to 1.
range(3, 3) No values Start and stop are equal.

5. Iterating Through Strings

A string is a sequence of characters. A for loop can process each character individually, making it useful for text analysis, character counting, validation, and formatting.

5.1 Example

word = "Python"

for character in word:
    print(character)

Output:

P
y
t
h
o
n

5.2 Counting Vowels in a String

text = "Learning Python"
vowels = "aeiouAEIOU"
count = 0

for character in text:
    if character in vowels:
        count += 1

print("Number of vowels:", count)

Output:

Number of vowels: 5

The loop examines each character. When a character appears in the vowel string, the counter increases by one.

6. Iterating Through Lists

A list stores an ordered collection of items. A for loop is a straightforward way to process each list element without manually accessing every position.

6.1 Example

students = ["Aarav", "Riya", "Kabir", "Meera"]

for student in students:
    print("Student:", student)

Output:

Student: Aarav
Student: Riya
Student: Kabir
Student: Meera

6.2 Calculating the Sum of List Values

numbers = [10, 20, 30, 40]
total = 0

for number in numbers:
    total += number

print("Total:", total)

Output:

Total: 100

The variable total is initialized to zero. Each number is added to it during the loop. This pattern is known as an accumulator.

6.3 Finding the Largest Value

numbers = [18, 42, 7, 95, 31]

if numbers:
    largest = numbers[0]

    for number in numbers[1:]:
        if number > largest:
            largest = number

    print("Largest value:", largest)
else:
    print("The list is empty")

Output:

Largest value: 95

The program begins with the first value as the current largest value. It compares the remaining values and updates largest whenever it finds a greater number. The empty-list check prevents an indexing error.

7. Iterating Through Tuples and Sets

Tuples and sets are also iterable, so they can be processed using for loops.

7.1 Iterating Through a Tuple

coordinates = (10, 20, 30)

for coordinate in coordinates:
    print(coordinate)

Output:

10
20
30

7.2 Iterating Through a Set

languages = {"Python", "Java", "JavaScript"}

for language in languages:
    print(language)

The loop prints each language, but the output order is not guaranteed because sets are unordered collections. Do not depend on a particular ordering when iterating through a set.

8. Iterating Through Dictionaries

A dictionary stores key-value pairs. By default, iterating directly over a dictionary produces its keys. Python also provides the keys(), values(), and items() methods for accessing keys, values, and key-value pairs.

8.1 Iterating Through Dictionary Keys

student = {
    "name": "Riya",
    "age": 21,
    "course": "Python"
}

for key in student:
    print(key)

Output:

name
age
course

8.2 Iterating Through Dictionary Values

student = {
    "name": "Riya",
    "age": 21,
    "course": "Python"
}

for value in student.values():
    print(value)

Output:

Riya
21
Python

8.3 Iterating Through Keys and Values

student = {
    "name": "Riya",
    "age": 21,
    "course": "Python"
}

for key, value in student.items():
    print(key, ":", value)

Output:

name : Riya
age : 21
course : Python

The items() method returns key-value pairs, which can be unpacked into two loop variables.

9. Using enumerate() to Access Index and Value

The built-in enumerate() function lets you access both the index and the value while iterating over an iterable. It is often cleaner than manually maintaining a counter.

9.1 Syntax

for index, value in enumerate(iterable, start=0):
    statement

The optional start argument determines the initial index. By default, it is zero.

9.2 Example

fruits = ["Apple", "Banana", "Mango"]

for index, fruit in enumerate(fruits):
    print(index, fruit)

Output:

0 Apple
1 Banana
2 Mango

9.3 Starting the Index at One

fruits = ["Apple", "Banana", "Mango"]

for index, fruit in enumerate(fruits, start=1):
    print(index, fruit)

Output:

1 Apple
2 Banana
3 Mango

This is useful when displaying numbered lists to users.

10. Using zip() to Iterate Through Multiple Sequences

The zip() function combines corresponding items from two or more iterables. It is useful when related data is stored in separate lists.

10.1 Example

names = ["Aarav", "Riya", "Kabir"]
scores = [85, 92, 78]

for name, score in zip(names, scores):
    print(name, "scored", score)

Output:

Aarav scored 85
Riya scored 92
Kabir scored 78

By default, zip() stops when the shortest iterable is exhausted. If the sequences have different lengths, extra items in the longer sequence are not processed by a normal zip() loop.

11. Using if Statements Inside for Loops

A for loop can contain an if statement to perform an action only when an item meets a condition. This is useful for filtering, classification, and validation.

11.1 Printing Even Numbers

numbers = [1, 2, 3, 4, 5, 6, 7, 8]

for number in numbers:
    if number % 2 == 0:
        print(number)

Output:

2
4
6
8

11.2 Separating Passing and Failing Scores

marks = [85, 32, 67, 90, 28, 74]

for mark in marks:
    if mark >= 40:
        print(mark, "Pass")
    else:
        print(mark, "Fail")

Output:

85 Pass
32 Fail
67 Pass
90 Pass
28 Fail
74 Pass

12. Using break in a for Loop

The break statement immediately terminates the nearest enclosing loop. It is useful when the desired item has been found or when continuing the loop is unnecessary.

12.1 Example

numbers = [10, 20, 30, 40, 50]

for number in numbers:
    if number == 30:
        print("Target found")
        break
    print(number)

Output:

10
20
Target found

Once the loop reaches 30, it prints the message and exits. The values 40 and 50 are not processed.

13. Using continue in a for Loop

The continue statement skips the remaining statements in the current iteration and proceeds to the next item.

13.1 Example

for number in range(1, 6):
    if number == 3:
        continue
    print(number)

Output:

1
2
4
5

When the loop variable equals 3, the continue statement skips the print statement for that iteration.

14. Using the else Clause with a for Loop

Python allows a loop to have an optional else clause. The loop's else block executes when the loop finishes normally, including when the iterable is empty. It does not execute if the loop is terminated by a break statement.

14.1 Example: Loop Completes Normally

for number in range(3):
    print(number)
else:
    print("Loop completed")

Output:

0
1
2
Loop completed

14.2 Example: Loop Ends with break

for number in range(5):
    if number == 2:
        break
    print(number)
else:
    print("Loop completed")

Output:

0
1

The else block does not execute because the loop terminates through break.

14.3 When Is for-else Useful?

  • Searching for an item and reporting when it is not found.
  • Checking whether any number in a sequence satisfies a condition.
  • Implementing simple prime-number checks.
  • Distinguishing normal completion from early termination.

15. Nested for Loops

A nested loop is a loop inside another loop. For each iteration of the outer loop, the inner loop runs through its own iterable.

15.1 Example

for row in range(1, 4):
    for column in range(1, 3):
        print("Row:", row, "Column:", column)

Output:

Row: 1 Column: 1
Row: 1 Column: 2
Row: 2 Column: 1
Row: 2 Column: 2
Row: 3 Column: 1
Row: 3 Column: 2

The outer loop runs three times. During each outer iteration, the inner loop runs twice, giving six total executions of the inner loop body.

15.2 Creating a Multiplication Table

number = 5

for multiplier in range(1, 11):
    print(number, "x", multiplier, "=", number * multiplier)

Output:

5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50

16. List Comprehensions and for Loops

A list comprehension provides a compact way to create a new list from an iterable. It is especially useful when transforming or filtering values with a simple expression.

16.1 Creating a List with a Traditional Loop

squares = []

for number in range(1, 6):
    squares.append(number ** 2)

print(squares)

Output:

[1, 4, 9, 16, 25]

16.2 The Equivalent List Comprehension

squares = [number ** 2 for number in range(1, 6)]
print(squares)

Output:

[1, 4, 9, 16, 25]

16.3 Filtering with a List Comprehension

even_numbers = [
    number for number in range(1, 11)
    if number % 2 == 0
]

print(even_numbers)

Output:

[2, 4, 6, 8, 10]

Use a traditional loop when it makes complex logic easier to read. A list comprehension is most suitable when the transformation or filtering operation is straightforward.

17. Iterables and Iterators

A iterable is an object from which Python can obtain items one at a time, such as a list, string, tuple, set, dictionary, or range. An iterator is an object that produces the next item when requested.

When a for loop runs, Python obtains an iterator from the iterable and repeatedly requests items until the iterator is exhausted. You usually do not need to manage this process manually.

17.1 Example with iter() and next()

fruits = ["Apple", "Banana", "Mango"]

fruit_iterator = iter(fruits)

print(next(fruit_iterator))
print(next(fruit_iterator))
print(next(fruit_iterator))

Output:

Apple
Banana
Mango

After all three items have been retrieved, another call to next() raises StopIteration unless a default value is supplied. A normal for loop handles the end of iteration automatically.

18. Common Mistakes When Working with for Loops

18.1 Forgetting the Colon

Incorrect:

for number in range(5)
    print(number)

Correct:

for number in range(5):
    print(number)

18.2 Incorrect Indentation

Incorrect:

for number in range(3):
print(number)

Correct:

for number in range(3):
    print(number)

18.3 Expecting range() to Include the Stop Value

for number in range(1, 5):
    print(number)

This prints 1 through 4, not 1 through 5. To include 5, use range(1, 6).

18.4 Using a Step of Zero

A range step cannot be zero.

# Incorrect: range(1, 10, 0)
for number in range(1, 10, 2):
    print(number)

Use a positive or negative non-zero step according to the intended direction.

18.5 Modifying a List While Iterating Over It

Removing items from a list while iterating directly over that same list can cause elements to be skipped or produce unexpected behavior.

Safer approach using a new list:

numbers = [1, 2, 3, 4, 5]
even_numbers = []

for number in numbers:
    if number % 2 == 0:
        even_numbers.append(number)

print(even_numbers)

Output:

[2, 4]

18.6 Confusing the Loop Variable with an Index

When iterating directly over a list, the loop variable receives each item, not its index.

fruits = ["Apple", "Banana", "Mango"]

for fruit in fruits:
    print(fruit)

If both the position and item are needed, use enumerate().

19. Best Practices for Using for Loops

  • Iterate directly over items when you do not need their indexes.
  • Use range() when numeric sequences or a known number of repetitions are required.
  • Use enumerate() when both the index and value are needed.
  • Use zip() to process related sequences together.
  • Choose meaningful loop variable names such as student, price, or product.
  • Keep loop bodies focused and readable.
  • Use break to exit early and continue to skip the current iteration when appropriate.
  • Avoid modifying a collection directly while iterating over it unless the behavior is carefully controlled.
  • Check for empty collections before accessing elements by index.
  • Prefer built-in functions such as sum(), min(), and max() when they express the task more clearly.
  • Use list comprehensions for simple transformations and filters, not for overly complicated logic.
  • Test empty input, one-item collections, boundary values, and larger datasets.

20. Mini Project: Student Marks Report

This project uses a for loop to process student marks, calculate a total and average, and count how many students passed.

marks = [85, 72, 39, 91, 56, 28]

total = 0
passed = 0
failed = 0

for mark in marks:
    total += mark

    if mark >= 40:
        passed += 1
    else:
        failed += 1

if marks:
    average = total / len(marks)
    print("Total marks:", total)
    print("Average marks:", round(average, 2))
    print("Students passed:", passed)
    print("Students failed:", failed)
else:
    print("No marks available")

Output:

Total marks: 371
Average marks: 61.83
Students passed: 4
Students failed: 2

20.1 Project Explanation

  • The list stores the marks to be processed.
  • The loop visits each mark once.
  • The accumulator variable total stores the sum.
  • An if-else statement classifies each mark as a pass or fail.
  • The program calculates the average only when the list is not empty.
  • The round() function formats the average to two decimal places.

20.2 Suggested Enhancements

  • Accept marks from the user instead of using a fixed list.
  • Validate that each mark is between 0 and 100.
  • Find the highest and lowest marks.
  • Assign grades using an if-elif-else chain.
  • Display the percentage of students who passed.

21. Practice Exercises

  1. Print numbers from 1 to 20 using a for loop.
  2. Print all even numbers between 1 and 50.
  3. Calculate the sum of integers from 1 to 100.
  4. Print each character of a user-provided string.
  5. Count the vowels in a sentence.
  6. Find the largest number in a list without using max().
  7. Display a multiplication table for a number entered by the user.
  8. Use enumerate() to display numbered items in a shopping list.
  9. Use zip() to display student names alongside their marks.
  10. Use break to stop searching when a target number is found.
  11. Use continue to skip negative values in a list.
  12. Build a student marks report that calculates totals, averages, and pass counts.

22. Interview Questions and Answers

Q1. What is a for loop in Python?

A for loop iterates over items in an iterable and executes a block of code for each item.

Q2. What is an iterable?

An iterable is an object that can provide its items one at a time, such as a list, tuple, string, set, dictionary, or range.

Q3. What is the purpose of range()?

The range() function generates a sequence of integers. It is commonly used to control how many times a loop runs.

Q4. Does range() include its stop value?

No. The stop value is excluded. For example, range(1, 5) produces 1, 2, 3, and 4.

Q5. What is the difference between break and continue?

break terminates the nearest enclosing loop. continue skips the remaining statements in the current iteration and proceeds to the next iteration.

Q6. What is a nested for loop?

A nested for loop is a loop placed inside another loop. The inner loop runs for each iteration of the outer loop.

Q7. How can you get both an index and a value during iteration?

Use enumerate(), which yields pairs containing an index and its corresponding item.

Q8. How do you iterate through a dictionary's keys and values?

Use dictionary.items() and unpack each pair into two variables.

Q9. What does the else clause of a for loop do?

The loop's else clause executes when the loop finishes normally. It is skipped if the loop terminates through break.

Q10. What happens when a for loop iterates over an empty list?

The loop body executes zero times because the list provides no items.

Q11. What is the difference between a for loop and a while loop?

A for loop is commonly used to iterate over an iterable. A while loop repeats as long as a condition remains true.

Q12. What is a list comprehension?

A list comprehension is a compact syntax for creating a list by transforming or filtering values from an iterable.

23. Quick Revision Checklist

  • A for loop processes items from an iterable.
  • The loop syntax requires a colon and an indented body.
  • range(stop) starts at zero and excludes the stop value.
  • range(start, stop, step) controls the start, end, and increment.
  • Strings, lists, tuples, sets, dictionaries, and ranges can be iterated over.
  • Use enumerate() to get indexes and values.
  • Use zip() to process multiple iterables together.
  • Use break to exit a loop and continue to skip an iteration.
  • A loop's else clause runs after normal completion, but not after break.
  • Nested loops are useful for working with rows, columns, and combinations.
  • Use clear variable names, proper indentation, and appropriate boundary checks.

24. Conclusion

The for loop is one of the most important tools in Python programming. It allows developers to repeat operations over sequences and collections without writing repetitive statements. By combining loops with conditions, functions, and built-in tools such as range(), enumerate(), and zip(), you can build programs that process data efficiently and clearly.

Practice iterating over different data types, calculating totals, filtering values, and using loop-control statements. Understanding these concepts provides a strong foundation for more advanced Python topics, including file processing, data analysis, automation, and working with APIs.

Continue learning Python: Explore the Python Training Course, register for a course demo, or visit the JustAcademy website.

whatsapp