Python Loops
Estimated reading: 3 minutes 265 views

Python for Loops – A Complete Guide with Examples

Introduction – Why for Loops Are Essential

In Python programming, the for loop is one of the most powerful tools for iteration. Whether you’re looping over a list of users, reading characters from a string, or analyzing data from a file—for loops provide an elegant and efficient solution.

Unlike while loops, which require explicit condition handling, Python’s for loop iterates directly over sequences. This makes it readable and intuitive—just the way Python was designed to be.

What You Will Learn:

  • Basic for loop syntax and mechanics
  • Iterating over common data types: lists, strings, dictionaries, and ranges
  • Advanced for loop techniques: nested loops, enumerate(), zip()
  • Common pitfalls and best practices

Python for Loop Syntax

for variable in iterable:
    # code block
  • variable: A temporary placeholder for the current value from the iterable.
  • iterable: A sequence or collection (list, tuple, string, range, etc.)

Example 1: Looping Over a List

fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

Output:

apple
banana
cherry

Explanation:

The variable fruit takes each item in the list one-by-one and prints it.

Tip: You can loop over any iterable—lists, strings, tuples, dictionaries, sets.


Iterating with range()

Example 2: Numbers from 0 to 4

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

Output:

0
1
2
3
4

Tip: range(start, stop, step) is often used in numeric iterations.


Looping Through Strings

Example 3: Character by Character

name = "Python"
for char in name:
    print(char)

Output:

P
y
t
h
o
n

Using enumerate() – Index with Item

Example 4:

languages = ["Python", "Java", "C++"]
for index, lang in enumerate(languages):
    print(index, lang)

Output:

0 Python
1 Java
2 C++

Best Practice: enumerate() is preferred over manual indexing using range(len(...)).


Looping Over Two Lists with zip()

Example 5:

names = ["Alice", "Bob", "Charlie"]
scores = [85, 90, 95]

for name, score in zip(names, scores):
    print(f"{name}: {score}")

Output:

Alice: 85
Bob: 90
Charlie: 95

Note: zip() stops at the shortest list length.


Nested for Loops

Example 6: Multiplication Table

for i in range(1, 4):
    for j in range(1, 4):
        print(f"{i} x {j} = {i*j}")

Use Case: Nested loops are useful in matrices, grids, and Cartesian products.


for Loop with else

Example 7:

nums = [1, 3, 5]
for num in nums:
    if num % 2 == 0:
        print("Even number found.")
        break
else:
    print("No even number found.")

Output:

No even number found.

Insight: The else block runs only if the loop completes without break.


Common Pitfalls

PitfallFix
Modifying list while iteratingUse .copy() or list comprehension
Forgetting colon : after forEnsure correct syntax
Using range() with strings/listsLoop directly over the iterable

Best Practices

  • Prefer enumerate() for indexed loops
  • Use zip() for parallel iteration
  • Avoid changing the looped collection during iteration
  • Combine for with else for search patterns

Summary – Key Takeaways

  • Python for loops iterate over any iterable, including lists, strings, and dictionaries.
  • range() is useful for numeric loops.
  • enumerate() and zip() enhance loop readability and efficiency.
  • for-else adds unique search/loop-completion behavior.
  • Use nested loops wisely to avoid complexity.

Frequently Asked Questions (FAQ)

Can I use for loops with dictionaries?

Yes. Use .items(), .keys(), or .values() to iterate:

for key, value in my_dict.items():
    print(key, value)

What is the difference between for and while loops?

  • for loops are used with iterables.
  • while loops execute as long as a condition is True.

How do I loop through a list in reverse?

Use reversed():

for item in reversed(my_list):
    print(item)

Can I break a for loop early?

Yes, use break:

for i in range(10):
    if i == 5:
        break

What’s the benefit of for-else?

It helps in search loops:

for x in data:
    if condition(x):
        break
else:
    print("Not found")

Share Now :
Share

Python for Loops

Or Copy Link

CONTENTS
Scroll to Top