Python For Loop with Examples

Python has become one of the go-to programming languages today, and it’s easy to see why—its simplicity and readability make it a favorite among many. A key feature that gives Python its strength and efficiency is the use of loops. Among the different types of loops available, the for loop stands out as one of the most frequently used control flow statements.

Blogging Illustration

In this article, we’ll dive into everything you need to know about the Python for loop, complete with examples. We’ll cover the syntax, how it operates, the range function, nested loops, and how to loop through various data types, among other things.

Whether you’re just starting out in coding or you already have a grasp of the basics, this guide will be a valuable resource as you work towards mastering loops in Python.

If you’re eager to learn Python through hands-on projects and real-time mentorship, be sure to check out the Python Programming Course in Noida (uncodemy.com), tailored specifically for both beginners and seasoned professionals.

What is a For Loop in Python?

A for loop in Python is designed to iterate over a sequence, which could be a list, tuple, string, or range. It enables the programmer to run a block of code multiple times, depending on how many items are in the sequence.

This control structure is particularly handy when you already know how many times you want to execute a statement or a series of statements.

Python For Loop Syntax

for variable in sequence:

# block of code

Explanation:

- A variable is simply a name that holds the value of an item in a sequence during each loop iteration.

- A sequence refers to a collection of items, which can be a list, string, tuple, or range.

How Python's For Loop Works:

In Python, the for loop uses the iter function to create an iterator from the sequence. It then calls the next function repeatedly to fetch the next item until it hits the end of the sequence.

Let’s break this down with a straightforward example.

Basic Example of For Loop

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

apple

banana

cherry

Explanation:

- In this example, the loop runs three times—once for each fruit in the list. During each cycle, the variable 'fruit' takes on the value of the next item from the list.

- This is a fundamental Python program for beginners, perfect for grasping how loops function.

Using range in a For Loop:

Python has a handy built-in function called range, which is often used with for loops. It creates a sequence of numbers.

Here’s the syntax for range:

range(start, stop, step)

- start: The starting value (default is 0)

- stop: The ending value (exclusive)

- step: The increment (default is 1)

Example 1: Loop from 0 to 4
for i in range(5):
print(i)
Output:
0
1
2
3
4
Example 2: Loop from 1 to 10 with step 2
for i in range(1, 11, 2):
	print(i)
Output:
1
3
5
7
9

Looping Through a String

Strings in Python are iterable. You can loop through each character using a for loop.

Example:
for char in "Python":
	print(char)
Output:
P
y
t
h
o
n

Looping Through a List

Lists are one of the most frequently used data types in Python.

Example:
languages = ["Python", "Java", "C++"]
for lang in languages:
    print("Learning", lang)
Output:

Learning Python
Learning Java
Learning C++

Looping Through a Dictionary

You can loop through dictionaries using .items(), .keys(), or .values().

Example:
student = {"name": "Alice", "age": 22, "course": "Python"}
for key, value in student.items():
	print(key, ":", value)
Output:

name : Alice
age : 22
course : Python

Nested For Loops

You can use one for loop inside another, which is called a nested loop.

Example:
for i in range(1, 4):
	for j in range(1, 4):
    	print(i, "*", j, "=", i*j)
    print("------")
Output:
1 * 1 = 1
 1 * 2 = 2
 1 * 3 = 3
2 * 1 = 2
 2 * 2 = 4
 2 * 3 = 6
3 * 1 = 3
 3 * 2 = 6
 3 * 3 = 9

Using break in For Loop

The break statement is used to exit the loop prematurely when a condition is met.

Example:
for i in range(10):
	if i == 5:
    	break
	print(i)
Output:
0
1
2
3
4

Using continue in For Loop

The continue statement skips the current iteration and moves to the next one.

Example:
for i in range(5):
	if i == 2:
    	continue
	print(i)
Output:
0
 1
 3
 4

Else Clause in For Loop

Python allows you to use an else clause with a for loop. It executes only when the loop completes all iterations without encountering a break.

Example:
for i in range(3):
	print(i)
else:
    print("Loop completed successfully")
Output:
0
 1
 2
 Loop completed successfully

Iterating Over Multiple Sequences Simultaneously

When it comes to Python, the for loop isn’t just for going through a single sequence. It’s actually quite versatile and can handle multiple sequences at once! This is made possible by a handy built-in function called zip(). What zip() does is pair up elements from two or more sequences and gives them back as tuples during each loop iteration.

For instance, imagine you have a list of student names and another list with their scores. You can easily process both lists together in one go using this method. It keeps everything in sync, so you don’t have to worry about managing index positions manually. This approach is particularly useful in scenarios like data analysis, creating real-time dashboards, or comparing data from different sources that are related.

Not only does this method enhance readability, but it also helps reduce the chances of bugs that often pop up when you’re dealing with parallel lists using manual indexing. So, if you want a clean and efficient way to work with related data sets in Python, iterating over multiple sequences at the same time with a for loop is definitely the way to go!

Memory Efficiency with For Loops

One of the standout benefits of using for loops in Python is their memory efficiency, especially when you're working with large datasets. Python supports iterator-based looping techniques, which means it processes data one element at a time instead of loading the entire sequence into memory all at once.

This approach is particularly useful when handling massive data files, live data streams, or resource-intensive tasks like machine learning and large-scale data analysis. Unlike some traditional looping methods in other programming languages that might keep entire sequences in memory (which can lead to higher RAM usage), Python’s loop structures often utilize generators or lazy evaluation techniques that only use memory as needed.

As a result, Python for loops not only bring elegance and simplicity to your code but also enhance performance and scalability, making them a great choice for writing production-ready applications. Developers who grasp and apply this memory-efficient strategy can create more robust, faster, and resource-friendly applications.

Learn Python Practically with Uncodemy

If you’re the type of person who thrives on hands-on learning, practical projects, and personalized guidance, then you should definitely check out the Python Programming Course at Uncodemy in Noida (uncodemy.com). This course is crafted to help you get a solid grip on essential concepts like loops, conditionals, functions, and file handling, catering to everyone from beginners to advanced learners.

With experienced trainers, real-world projects, and support for job placements, Uncodemy makes sure you not only learn but also get ready for the job market.

Conclusion

Grasping the Python for loop through examples empowers you to navigate sequences and handle repetitive tasks with ease. Whether you’re dealing with strings, lists, dictionaries, or ranges, for loops are vital tools in your Python arsenal.

We’ve explored a range of practical applications for for loops, from beginner-friendly code to more advanced examples. Dive into your own coding experiments, modify the examples provided, and watch your Python skills flourish.

If you’re committed to building a solid foundation in Python, think about enrolling in the Python Programming Course at Uncodemy in Noida (uncodemy.com) to fast-track your learning journey.

FAQs on Python For Loop

Q1. What’s the purpose of a for loop in Python?

Ans. A for loop in Python is designed to help you go through a sequence, whether it’s a list, tuple, string, or range. It’s a great way to automate repetitive tasks in a way that’s both efficient and easy to read.

Q2. Can we use a for loop with strings?

Ans. Absolutely! Strings are iterable in Python, so you can use a for loop to go through each character in a string one by one.

Q3. How does a for loop differ from a while loop?

Ans. A for loop is ideal when you know exactly how many times you want to iterate, while a while loop keeps running as long as a certain condition remains true.

Q4. What’s the role of range in a for loop?

Ans. The range function creates a sequence of numbers, which is often used in for loops to repeat a block of code a specific number of times.

Q5. Is it possible to use else with a for loop?

Ans. Yes, you can include an else block with a for loop in Python. This block runs after the loop finishes normally, but it won’t execute if the loop is exited with a break statement.

Placed Students

Our Clients

Partners

Uncodemy Learning Platform

Uncodemy Free Premium Features

Popular Courses