Python For Loops – Syntax Example

KB Viewed: 731

Python For Loops – Syntax Example

Python for loop is an essential tool that helps you do things repeatedly with items in a list, one item at a time. Think of it like going through a checklist. This article will show you how to use the “for loop” with simple examples and clear explanations.

Imagine you have a list of things, like fruits, in a basket. You can use a “for loop” to pick up each fruit, one by one, and do something with it, like eat it or count it. This loop makes it easy to work with lots of items without doing the same thing over and over again manually.

Before we dive into examples, let’s refresh our memory on the basic syntax of the for loop:

For items in sequence:

# Code to be executed for each item

item: Represents the current item in the sequence during each iteration.

sequence: The collection of elements to be iterated over.

Example 1: Iterating through a List of Strings:

Let’s begin by iterating through a list of strings and printing each string’s length.

fruits = ["apple", "banana", "cherry", "date", "elderberry"]

for fruit in fruits:

print(f"The length of {fruit} is {len(fruit)} characters.")
Output:
The length of apple is 5 characters.
The length of banana is 6 characters.
The length of cherry is 6 characters.
The length of date is 4 characters.
The length of elderberry is 10 characters.

Example 2: Using range() for Numeric Iteration:

The range() function generates a sequence of numbers that can be used with the for loop.

for i in range(1, 6):

print(i)
Output:
1
2
3
4
5

Example 3: Iterating with Step in range():

To create more intricate patterns, you can specify a step value for the range() function.

for i in range(0, 10, 2):

print(i)
Output:
0
2
4
6
8

Example 4: Iterating Through a String Backwards:

Strings can be treated as sequences, allowing you to iterate through them in reverse.

word = "Python"

for char in reversed(word):

print(char)
Output:
n
o
h
t
y
p

Example 5: Iterating Through a List with Index:

To access the index and list element, you can use the enumerate() function.

colors = ["red", "green", "blue"]

for index, color in enumerate(colors):

print(f"Color {index + 1}: {color}")
Output:
Color 1: red
Color 2: green
Color 3: blue

Example 6: Using zip() to Iterate Multiple Lists:

The zip() function combines multiple lists, allowing you to iterate through them simultaneously.

names = ["Alice", "Bob", "Charlie"]

scores = [85, 92, 78]

for name, score in zip(names, scores):

print(f"{name} scored {score}")
Output:
Alice scored 85
Bob scored 92
Charlie scored 78

Example 7: Looping Through a Dictionary’s Items:

Using its methods, you can loop through a dictionary’s keys, values, or both.

student_scores = {"Alice": 85, "Bob": 92, "Charlie": 78}

for student, score in student_scores.items():

print(f"{student} scored {score}")
Output:
Alice scored 85
Bob scored 92
Charlie scored 78

Example 8: Nested for Loops for Patterns

Nested for loops can be used to create interesting patterns.

for i in range(5):

for j in range(i + 1):

print("*", end=" ")

print()
Output:
*
* *
* * *
* * * *
* * * * *

Conclusion:

The for loop in Python is a powerful tool that helps you go through lists easily. When you learn to use it well and understand its different forms, you can work with data, create patterns, and solve various problems smartly and efficiently.