In Python, the for
loop is used to iterate over a sequence of elements, such as a list, tuple, string, or even a range of numbers. It allows you to perform a set of operations on each element of the sequence. Here’s the basic syntax of a for
loop in Python:
pythonCopy codefor variable in sequence:
# code to be executed for each element in the sequence
variable
is a temporary variable that takes on the value of each element in thesequence
during each iteration.sequence
is the collection of elements you want to iterate over.
Here are some examples of how you can use the for
loop in Python:
- Iterating over a list:
pythonCopy codefruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Output:
Copy codeapple
banana
cherry
- Iterating over a string:
pythonCopy codeword = "Python"
for letter in word:
print(letter)
Output:
cssCopy codeP
y
t
h
o
n
- Using the
range
function to iterate over a range of numbers:
pythonCopy codefor num in range(1, 6):
print(num)
Output:
Copy code1
2
3
4
5
- Iterating over a dictionary’s keys or values:
pythonCopy codeperson = {"name": "Alice", "age": 30, "city": "New York"}
# Iterate over keys
for key in person:
print(key)
# Iterate over values
for value in person.values():
print(value)
Output (keys):
Copy codename
age
city
Output (values):
sqlCopy codeAlice
30
New York
- Using
enumerate
to iterate over a sequence with both index and value:
pythonCopy codefruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
print(f"Index {index}: {fruit}")
Output:
yamlCopy codeIndex 0: apple
Index 1: banana
Index 2: cherry
The for
loop is a fundamental construct in Python for performing repetitive tasks, and it’s a powerful tool for working with collections of data. You can use it to process elements in a sequence, make decisions based on those elements, and perform various operations as needed.