In Python, a for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string) or other iterable objects. Iterating over a sequence is called traversal.
Here’s a basic structure of a for loop in Python:
Syntax
for val in sequence:
# block of code to execute for each item in the sequence
Explanation :
for keyword: This keyword is used to define the for loop.
val: This is a variable that takes the value of the item inside the sequence on each iteration.
in keyword: This keyword is used to check if a value exists in the sequence.
sequence: This is a sequence of values over which to iterate.
: (colon): The colon is used to denote the start of a block of code.
Indentation: Python uses indentation to define blocks of code. The code within the for loop should be indented.
Here’s an basic example:
python for loop basic example
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Output
apple
banana
cherry
In this example, fruit is the variable that takes the value of the next item in fruits on each iteration. The print(fruit) line is executed for each item in fruits
Here are few more examples to understand and practice for-loop in python
1. Printing Numbers from 1 to 10:
printing numbers from 1 to 10 using for loop in python
for number in range(1, 11): # Use range(start, end) for inclusive range
print(number)
Output
1
2
3
4
5
6
7
8
9
10
2. Printing Characters in a String:
Printing Characters in a String example using for-loop in python
name = "Alice"
for character in name:
print(character)
Output
A
l
i
c
e
3. Summing Numbers in a List:
Calculate sum of elements in a list in python
numbers = [1, 2, 3, 4, 5]
total = 0
for number in numbers:
total += number
print("The sum is:", total)
Output
The sum is: 15
4. Finding the Maximum Element in a List:
Finding maximum element in a list using for-loop example in python
numbers = [5, 10, 2, 8]
largest = numbers[0] # Initialize with the first element
for number in numbers:
if number > largest:
largest = number
print("The maximum element is:", largest)
Output
The maximum element is: 10
5. Counting Even Numbers in a List:
Counting even num in a range using for-loop example-python
numbers = [1, 2, 3, 4, 5, 6]
even_count = 0
for number in numbers:
if number % 2 == 0: # Check for evenness
even_count += 1
print("There are", even_count, "even numbers.")
Output
There are 3 even numbers.
6. Reversing a String:
Python string reverse example using for-loop
text = "Tutorialsbox"
reversed_text = ""
for character in text[::-1]: # Slice the string in reverse order
reversed_text += character
print("The reversed string is:", reversed_text)
Output
The reversed string is: xobslairotuT
7. Creating a List of Squares from 1 to 5:
Examples for printing square values in a range using python for
squares = []
for number in range(1, 6):
square = number * number
squares.append(square)
print("The list of squares is:", squares)
Output
The list of squares is: [1, 4, 9, 16, 25]
8. Filtering Names Starting with 'A' (Case-Insensitive):
Example for filtering names using python for loop
names = ["Bob", "Alice", "Charlie", "adam"]
filtered_names = []
for name in names:
if name.lower().startswith('a'): # Lowercase for case-insensitive check
filtered_names.append(name)
print("Names starting with 'A':", filtered_names)
Output
Names starting with 'A': ['Alice', 'adam']
9. Skipping Even Numbers (Using continue):
Printing odd numbers using for loop with continue example in python
numbers = [1, 2, 3, 4, 5, 6]
for number in numbers:
if number % 2 == 0:
continue # Skip even numbers
print(number)
Output
1
3
5
10. Iterating with an Index:
Iterating with an index using python for-loop example
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits): # Use `enumerate` for index and item
print("Index:", index, "Fruit:", fruit)
Output
Index: 0 Fruit: apple
Index: 1 Fruit: banana
Index: 2 Fruit: cherry
These examples demonstrate various applications of for-loops in Python, making it a versatile tool for iterating and manipulating data.