Python

P
PythonHub
Progress 0%

Python

  • Home
  • History of Python
  • Applications of Python
  • Introduction To Python
    • What is Python
    • Character Set
    • Tokens in Python
    • Python Execution Mode
    • Variable And Identifiers
    • Data Types in Python
    • Operators And Expressions
    • Constants in Python
    • Assignment Statement
    • Input / Output in Python
    • Simple Python Scripts
    • Namespace in Python
    • šŸ“ Assignments
  • Operators in Python
    • Arithmetic Operators
    • Assignment Operators
    • Shorthand Assignment Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Special Operators
    • šŸ“ Assignments
  • Input Output in Python
    • Accept Input
    • Output Formatting
    • šŸ“ Assignments
  • Conditional Statement
    • Decision Making
    • if Statement
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • Short Hand IF-ELSE
    • šŸ“ Assignments
  • Loops
    • Introduction to Loops
    • While Loop
    • Nested While Loop
    • šŸ“ While Loop Assignments
    • For Loop
    • For Loop Examples
    • Nested For Loop
    • Nested For Loop Examples
    • Infinite While Loops
    • Infinite For Loops
    • Break, Continue and Else in Loops
    • Difference Between For and While Loop
    • For Each Loop
    • šŸ“ For Each Assignments
    • šŸ“ All Loops Assignments
  • List
    • List in Python
    • Access List Elements
    • List Functions
    • Iterate (Loop) List
    • List Comprehension
    • šŸ“ Assignments
  • Tuple
    • Tuple in Python
    • Access Tuple Elements
    • Tuple Functions
    • Iterate (Loop) Tuple
    • Unpack Tuple
    • Tuple Comprehension
    • šŸ“ Assignments
  • Set
    • Set in Python
    • Access Set Elements
    • Set Methods
    • Iterate (Loop) Set
    • Pack/Unpack Set
    • Set Comprehension
    • šŸ“ Assignments
  • Dictionary
    • Dictionary
    • Access Dictionary Items
    • Dictionary Methods
    • Iterate (Loop) Dictionary
    • Formatting Dictionaries
    • Nested Dictionaries
    • Dictionary Comprehension
    • šŸ“ Assignments
  • Diff List Tuple Set Dictionary
    • List vs Tuple
    • List vs Set
    • List vs Dictionary
    • Tuple vs Set
    • Tuple vs Dictionary
    • Dictionary vs Set
    • šŸ“ Assignments
  • Exception
    • Error vs Exception
    • Exception Handling
    • Types of Exception
    • User Defined Exception
    • Logging Exception
    • šŸ“ Assignments
  • Functions
    • Introduction to Functions
    • Modular Programming
    • Types of Functions
    • Inbuilt Functions
    • Need For User-Defined Function
    • Elements of User Defined Function
    • Function Arguments
    • Nesting of Functions
    • Recursion
    • Global Local and Non Local
    • Python Lambda Functions
    • šŸ“ Assignments
  • Python Module
    • Introduction to Module
    • Inbuilt Modules in Python
    • User Defined Module
    • šŸ“ Assignments
  • File Handling
    • Introduction to Files
    • Create File
    • Read Files
    • Write to File
    • Rename File
    • Copy File
    • Move File
    • List Files in Directory
    • Binary Files
    • Zipping and Unzipping Files
    • šŸ“ Assignments
  • Strings
    • Basics of Strings
    • String Special Operators
    • String Formatting Operators
    • String Methods
    • šŸ“ Assignments
  • Regular Expressions
  • Python OOPS
    • Basics of Object Oriented
    • What are Classes and Objects?
    • Creating Class and Object
    • OOP vs Procedural Programming
    • Difference Between Classes and Objects
    • Constructors
    • Destructor
    • Built Class Methods and Attributes
    • Class and Instance Variables
    • Inheritance in Python
    • Single Inheritance
    • Multiple Inheritance
    • Multilevel Inheritance
    • Hierarchical Inheritance
    • Hybrid Inheritance
    • Abstraction
    • Method Overriding
    • Abstract Method
    • Interfaces in Python
    • Abstract Class vs Interface
    • Public, Private and Protected
    • Overloading vs Overriding
    • Inheritance vs Composition
    • Encapsulation
    • Polymorphism
    • Inner Classes
    • šŸ“ Assignments
  • Advanced Python
    • Iterator in Python
    • Generator in Python
    • Decorator in Python
    • Type Hints in Python
    • Async/Await Programming
    • Dataclasses in Python
    • Context Managers in Python
    • Property Decorator in Python
    • __slots__ in Python
    • Enums in Python
    • Walrus Operator in Python
    • Match-Case in Python
    • šŸ“ Assignments
  • Python Standard Library
    • Collections Module
    • Itertools Module
    • Functools Module
    • Datetime Module
    • JSON Module
    • OS Module
    • Sys Module
    • Random Module
    • Math Module
    • šŸ“ Assignments
  • Python Testing
    • Unit Testing in Python
    • Pytest Framework
    • Mocking in Python
    • šŸ“ Assignments
  • Python Best Practices
    • PEP 8 Style Guide
    • Docstrings in Python
    • Logging in Python
    • Code Optimization Tips
    • Debugging Techniques
    • šŸ“ Assignments
  • MySQL Database in Python
    • Introduction to MySQL with Python
    • DBMS vs File System
    • Connecting to MySQL Database
    • Create Database in MySQL
    • Create Table in MySQL
    • Insert Data in MySQL
    • Insert Multiple Rows
    • Select Data from MySQL
    • WHERE Clause in MySQL
    • Update Data in MySQL
    • Delete Data from MySQL
    • Parameterized Queries
    • Transaction Management
    • Error Handling
    • Connection Pooling
    • MySQL Drivers Guide
    • Joins in MySQL
    • Aggregation Functions
    • Backup MySQL Database
    • Best Practices
    • šŸ“ Assignments
  • MySQL Database Operations
    • SELECT Statement
    • MySQL Operators
    • DDL Statements
    • DML Statements
    • Subqueries
    • JOIN Operations
    • Aggregation
    • Case Study
    • šŸ“ Assignments
  • Graphics in Python
  • Threads in Python
    • Introduction to Threads
    • Process vs Threads
    • Concurrent Programming & GIL
    • Uses of Threads
    • Creating Threads
    • Single Tasking
    • Multi Tasking
    • Thread Synchronization
    • šŸ“ Assignments
  • Interview Questions & Answers
  • Python Case Studies
  • Multiple Choice Questions
  • šŸ“ Practice Problems
Get in Touch
  • tech2dsm@gmail.com

© Sankalan Data Tech

Python Language Interactive Tutorial

šŸ”„ Python For Loop: Complete Guide

Python For Loop - Complete Guide with Examples

Master Python for loop with practical examples and real-world applications.

Created by Sankalan Data Tech Team Verified
Data Engineers, Analysts, Scientists & Trainers
Created by experienced Python developers, data engineers, and data scientists to make programming easy through practical examples, real-world experience, and clear explanations.
šŸ“‘ On this page:
  • What is a For Loop?
  • For Loop Syntax
  • The range() Function
  • Iterating Lists
  • Iterating Strings
  • Iterating Dictionaries
  • Real-World Examples
  • Best Practices & Pitfalls
  • Try It Yourself
  • Quick Quiz
  • FAQ
Share this tutorial:
Twitter LinkedIn Facebook WhatsApp Reddit Telegram Email Copy Link
šŸ“š What You'll Learn Here
  • What for loops are — iterating over sequences
  • Syntax and structure — writing for loops correctly
  • range() function — generating number sequences
  • Iterating lists, strings, dictionaries — working with data structures
  • Real-world applications — practical examples
  • Best practices — writing efficient for loops
  • Hands-on practice with the interactive editor

What is a For Loop?

A for loop in Python is used to iterate over a sequence of elements. Unlike a while loop that runs based on a condition, a for loop runs for a specified number of times or over each item in a collection. It's the most common and convenient way to process lists, strings, tuples, dictionaries, and other iterable objects.

šŸ’” Key insight: For loops in Python are designed to be clean and readable. They automatically handle the iteration mechanics, making your code simpler and less error-prone than manual index management.

The for loop is incredibly versatile. You can use it to process items in a list, characters in a string, keys in a dictionary, or generate number sequences with the range() function. This makes it one of the most frequently used constructs in Python programming.

For Loop Syntax

The syntax of a for loop in Python is simple and intuitive:

# Basic for loop syntax
for variable in iterable:
    # Code to execute for each item
    print(variable)

# Example: Iterating over a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(f"I like {fruit}")

# Output:
# I like apple
# I like banana
# I like cherry

Key components of a for loop:

  • for keyword — starts the loop
  • variable — takes the value of each item in the sequence
  • in keyword — connects the variable to the sequence
  • iterable — the sequence to iterate over (list, string, range, etc.)
  • colon — marks the beginning of the loop body
  • indented block — code to execute for each item

The range() Function

The range() function is commonly used with for loops to generate sequences of numbers:

# range(stop) - generates numbers from 0 to stop-1
for i in range(5):
    print(i, end=" ")
# Output: 0 1 2 3 4

# range(start, stop) - generates from start to stop-1
for i in range(2, 7):
    print(i, end=" ")
# Output: 2 3 4 5 6

# range(start, stop, step) - with step size
for i in range(1, 11, 2):
    print(i, end=" ")
# Output: 1 3 5 7 9

# range in reverse (using negative step)
for i in range(10, 0, -2):
    print(i, end=" ")
# Output: 10 8 6 4 2

šŸ“Œ Important: The range() function creates a sequence of numbers on-demand. It doesn't store all numbers in memory, making it efficient for large ranges.

Iterating Lists with For Loop

For loops are ideal for processing lists. Here are several ways to iterate lists:

# 1. Direct iteration over items
colors = ["red", "green", "blue"]
for color in colors:
    print(color)

# 2. Iterating with index using range()
for i in range(len(colors)):
    print(f"Index {i}: {colors[i]}")

# 3. Using enumerate() to get both index and value
for index, color in enumerate(colors):
    print(f"Position {index}: {color}")

# 4. Processing list elements
numbers = [10, 20, 30, 40, 50]
total = 0
for num in numbers:
    total += num
print(f"Sum: {total}")
# Output: Sum: 150

Iterating Strings with For Loop

Strings are sequences of characters, so for loops work naturally:

# Iterating characters
word = "Python"
for char in word:
    print(char, end=" ")
# Output: P y t h o n

# Counting vowels in a string
text = "Hello World"
vowels = 0
for char in text.lower():
    if char in 'aeiou':
        vowels += 1
print(f"Vowels: {vowels}")
# Output: Vowels: 3

# Reversing a string
word = "Python"
reversed_word = ""
for char in word:
    reversed_word = char + reversed_word
print(reversed_word)
# Output: nohtyP

Iterating Dictionaries with For Loop

Dictionaries allow iteration over keys, values, or both:

student = {"name": "Alice", "age": 25, "grade": "A"}

# Iterating keys (default)
for key in student:
    print(f"{key}: {student[key]}")

# Iterating keys explicitly
for key in student.keys():
    print(f"Key: {key}")

# Iterating values
for value in student.values():
    print(f"Value: {value}")

# Iterating key-value pairs
for key, value in student.items():
    print(f"{key} → {value}")

# Output:
# name → Alice
# age → 25
# grade → A

Real-World Examples

šŸ’” Use Case 1: Processing Student Grades

grades = [85, 92, 78, 90, 88, 76]
total = 0
highest = grades[0]
lowest = grades[0]

for grade in grades:
    total += grade
    if grade > highest:
        highest = grade
    if grade < lowest:
        lowest = grade

average = total / len(grades)
print(f"Average: {average:.2f}")
print(f"Highest: {highest}")
print(f"Lowest: {lowest}")
# Output:
# Average: 84.83
# Highest: 92
# Lowest: 76

šŸ’” Use Case 2: Product Inventory Check

inventory = {
    "laptop": 15,
    "mouse": 45,
    "keyboard": 22,
    "monitor": 8
}

low_stock_items = []
for item, quantity in inventory.items():
    if quantity < 10:
        low_stock_items.append(item)

print("Low stock items:", low_stock_items)
# Output: Low stock items: ['monitor']

šŸ’” Use Case 3: Employee Salary Report

employees = [
    {"name": "John", "salary": 75000},
    {"name": "Sarah", "salary": 82000},
    {"name": "Mike", "salary": 68000}
]

total_salary = 0
for emp in employees:
    total_salary += emp["salary"]
    print(f"{emp['name']}: ${emp['salary']}")

print(f"Total: ${total_salary}")
print(f"Average: ${total_salary / len(employees):.2f}")
# Output:
# John: $75000
# Sarah: $82000
# Mike: $68000
# Total: $225000
# Average: $75000.00

Best Practices & Pitfalls

āš ļø Common Pitfalls

  • Modifying a list while iterating over it
  • Using range(len()) when direct iteration works
  • Forgetting to store values from iteration
  • Using for loops for simple arithmetic sequences

āœ… Best Practices

  • Use direct iteration when possible
  • Use enumerate() when you need indices
  • Use list comprehensions for transformations
  • Keep loop bodies simple and focused

šŸ’” Optimization Tips

  • Use break to exit early
  • Use continue to skip items
  • Consider generator expressions for large data
  • Use built-in functions like sum(), max(), min()

Try It Yourself!

Experiment with for loops directly in your browser. Modify the code and see the results in real time.

Loading Pyodide... 0%
Python Code Editor
========================================
FOR LOOP DEMONSTRATION
========================================

1. BASIC FOR LOOP (1 to 5)
1 2 3 4 5

2. ITERATING A LIST
- apple
- banana
- cherry
- mango

3. ITERATING A STRING
P y t h o n

4. ITERATING A DICTIONARY
name: Alice
age: 25
grade: A

5. SUM OF NUMBERS 1 TO 10
Total: 55

6. EVEN NUMBERS UP TO 20
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

āœ… Explore for loops!
šŸ†

šŸŽ‰ You've Learned Python For Loops!

You understand for loop syntax, range() function, iterating over lists, strings, and dictionaries. These are essential skills for Python programming!

Quick Quiz – Test Your Knowledge

Let's see what you've learned about for loops:

1. What does the range(5) function generate?
2. Which function gives both index and value when iterating?
3. How do you iterate over both keys and values in a dictionary?
4. What happens when you modify a list while iterating over it?
5. Which is the most efficient way to sum numbers in a list?

Frequently Asked Questions

šŸ¤” What's the difference between for and while loops? ā–¼

For loops are used when you know the number of iterations (e.g., iterating over a sequence). While loops are used when you don't know the number of iterations and rely on a condition. For loops are generally cleaner and more Pythonic for iterating over sequences.

šŸ“Š Can I use break and continue in for loops? ā–¼

Yes! break exits the loop immediately, and continue skips the rest of the current iteration and moves to the next item. Both are commonly used in for loops for conditional control flow.

šŸ“ What is the else clause in for loops? ā–¼

The else clause in a for loop executes when the loop completes without encountering a break statement. It's useful for checking if a loop completed all iterations or was interrupted. For example, searching for an item in a list.

šŸ“‚ How do I iterate over a file with for loop? ā–¼

You can iterate over a file object directly with a for loop. Each iteration returns one line from the file. This is memory-efficient because it doesn't load the entire file into memory at once. Example: for line in open('file.txt'): print(line)

šŸ“ˆ Can I create nested for loops? ā–¼

Yes! You can nest for loops inside other for loops. This is useful for working with multi-dimensional data, creating patterns, and performing operations that require multiple levels of iteration. Just be mindful of complexity — nested loops have O(n Ɨ m) complexity.

šŸ“¦ What is the difference between range and xrange? ā–¼

In Python 3, range() behaves like the old xrange() and is lazy — it generates numbers on demand. xrange() doesn't exist in Python 3. In Python 2, range() creates a list, while xrange() creates a generator. Use range() in Python 3 for all cases.

šŸ“š Where to Go From Here

Now that you've mastered for loops, here are the next topics to explore:

šŸ”„ For Loop Examples

Explore more advanced for loop examples.

Learn More →

šŸ“Š Nested For Loop

Learn about for loops inside other for loops.

Learn More →

⚔ Break, Continue, Else

Master loop control statements.

Learn More →
šŸ“– Interview & FAQ Resources
  • Python Syntax & Variables Interview Questions
  • SQL - Displaying Data from Multiple Tables FAQ
  • SQL Window Functions & Analytic Functions FAQ
  • Python Data Types Interview Questions
  • Python Tuples and Sets Interview Questions
  • Java Basic Input/Output Interview Questions
  • Java Advanced Threads and Concurrency Interview Questions
Previous: While Loop Assignments Next: For Loop Examples →