Python
Python Basics
- Introduction to Python and Its History
- Python Syntax and Indentation
- Python Variables and Data Types
- Dynamic and Strong Typing
- Comments and Docstrings
- Taking User Input (input())
- Printing Output (print())
- Python Operators (Arithmetic, Logical, Comparison)
- Type Conversion and Casting
- Escape Characters and Raw Strings
Data Structures in Python
- Lists
- Dictionaries
- Dictionary Comprehensions
- Strings and String Manipulation
- Tuples
- Python Sets: Unordered Collections
- List Comprehensions and Generator Expressions
- String Formatting
- Indexing and Slicing
- Set Comprehensions
Control Flow and Loops
- Conditional Statements: if, elif, and else
- Loops and Iteration
- While Loops
- Nested Loops
- Loop Control Statements
- Iterators and Iterables
- List, Dictionary, and Set Iterations
Functions and Scope
- Defining and Calling Functions (`def`)
- Function Arguments (`*args`, `**kwargs`)
- Default Arguments and Keyword Arguments
- Lambda Functions
- Global and Local Scope
- Function Return Values
- Recursion in Python
Python Core Concepts
Python Collections
- Python collections ChainMap
- Python collections
- Python collections ChainMap<
- Python counters
- Python deque
- Python dictionary
- Python Lists
Python Programs
- Array : Find median in an integer array
- Array : Find middle element in an integer array
- Array : Find out the duplicate in an array
- Array : Find print all subsets in an integer array
- Program : Array : Finding missing number between from 1 to n
- Array : Gap and Island problem
- Python Program stock max profit
- Reverse words in Python
- Python array duplicate program
- Coin change problem in python
- Python Write fibonacci series program
- Array : find all the pairs whose sum is equal to a given number
- Find smallest and largest number in array
- Iterate collections
- List comprehensions
- Program: Calculate Pi in Python
- String Formatting in Python
For Loops and Iteration in Python
One of the foundational skills in any programming language is the ability to repeat actions efficiently. In Python, iteration is handled primarily through for
loops, a simple yet powerful tool that lets you loop over sequences such as lists, strings, or ranges.
Whether you’re processing data, automating tasks, or just learning to program, understanding for
loops is crucial. In this article, we’ll explore everything you need to know about for
loops and iteration in Python—from basics to best practices—with plenty of examples along the way.
Why Learn About For Loops and Iteration?
Repetition is common in programming. We often need to:
- Process items in a list one by one
- Repeat a task a certain number of times
- Check each character in a string
- Apply logic to data structures like dictionaries
Instead of writing the same code multiple times, loops automate the repetition. The for
loop is Python’s primary tool for iterating over items in a sequence.
Prerequisites
Before you dive into for
loops, make sure you understand:
- Basic Python syntax
- Variables and data types
- Data structures like lists, tuples, dictionaries, and strings
- The concept of sequences and indexing
1. What is a for
Loop?
A for
loop in Python is used to iterate over a sequence of elements. Unlike some languages that use a counter to loop, Python’s for
loop reads each element from the sequence directly.
Example:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Output:
apple
banana
cherry
2. Syntax of for
Loops
Here’s the basic syntax:
for variable in sequence:
# Code block to execute
variable
is a name for each element in the sequence.- The indented block runs once for each item.
3. Iterating Over Different Data Types
🔹 Lists:
colors = ["red", "green", "blue"]
for color in colors:
print(color)
🔹 Strings:
word = "hello"
for letter in word:
print(letter)
🔹 Tuples:
coordinates = (10, 20, 30)
for value in coordinates:
print(value)
🔹 Dictionaries:
person = {"name": "Alice", "age": 25}
for key in person:
print(key, person[key])
4. Using range()
in Loops
range()
is often used to generate a sequence of numbers.
for i in range(5):
print(i)
Output:
0
1
2
3
4
You can customize range(start, stop, step)
:
for i in range(1, 10, 2):
print(i)
5. Nested for
Loops
A for
loop inside another is called a nested loop.
for i in range(1, 4):
for j in range(1, 4):
print(f"{i} x {j} = {i*j}")
This is useful in matrix operations or dealing with multi-dimensional data.
6. Using break
and continue
🔸 break
— exits the loop prematurely:
for num in range(10):
if num == 5:
break
print(num)
🔸 continue
— skips the current iteration:
for num in range(10):
if num % 2 == 0:
continue
print(num)
7. Looping with else
Python allows an else
clause in loops.
for num in range(3):
print(num)
else:
print("Loop completed")
If the loop completes without hitting a break
, the else
runs.
8. Real-World Examples
🔹 1. Summing Numbers in a List:
numbers = [1, 2, 3, 4]
total = 0
for num in numbers:
total += num
print("Total:", total)
🔹 2. Counting Vowels in a String:
text = "education"
vowels = "aeiou"
count = 0
for char in text:
if char in vowels:
count += 1
print("Vowels:", count)
🔹 3. Generating a Multiplication Table:
for i in range(1, 6):
for j in range(1, 6):
print(i * j, end="\t")
print()
🔹 4. Filtering Even Numbers:
numbers = [1, 2, 3, 4, 5, 6]
for n in numbers:
if n % 2 == 0:
print(n)
🔹 5. Reading User Input:
names = []
for i in range(3):
name = input("Enter a name: ")
names.append(name)
print("Names:", names)
9. Common Mistakes to Avoid
- Forgetting indentation
- Modifying a list while iterating over it
- Using incorrect range values
- Assuming
for
loops behave like C-style loops (they don’t) - Over-nesting loops unnecessarily
10. Best Practices
- Use descriptive loop variables (
item
,char
,number
) - Avoid deeply nested loops—consider functions or list comprehensions
- Prefer
for
overwhile
for finite sequences - Use
enumerate()
when you need index and value:
for i, value in enumerate(["a", "b", "c"]):
print(i, value)
- Leverage list comprehensions for concise looping:
squares = [x**2 for x in range(10)]
The for
loop is one of the most important tools in Python, allowing you to iterate over sequences efficiently. Whether you’re dealing with a list of numbers, a string of characters, or a dictionary of key-value pairs, the for
loop is your go-to solution for repetition and automation.
Once you’ve mastered the basics, you’ll be able to build powerful logic, manipulate data, and write more dynamic and responsive programs.