Python : For Loops

In Python, for loops are used to iterate over a sequence (such as a list, tuple, string, or range) or any iterable object. Here's how you can use for loops:

Basic for loop with a list:


my_list = [1, 2, 3, 4, 5]

for item in my_list:
    print(item)


This loop will iterate over each element in the list my_list and print it.

for loop with a range:


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


This loop will print numbers from 0 to 4. range(5) generates numbers from 0 up to, but not including, 5.

 for loop with a string:



my_string = "Hello"

for char in my_string:
    print(char)


This loop will iterate over each character in the string my_string and print it.

for loop with enumerate():


You can use enumerate() to get both the index and the value of each item in a sequence.


my_list = ['a', 'b', 'c']

for index, value in enumerate(my_list):
    print(f"Index: {index}, Value: {value}")

 

for loop with dictionary:


my_dict = {'a': 1, 'b': 2, 'c': 3}

for key, value in my_dict.items():
    print(f"Key: {key}, Value: {value}")


This loop will iterate over each key-value pair in the dictionary my_dict and print them.

Nested for loops:


You can nest for loops within each other.


for i in range(3):
    for j in range(3):
        print(f"i: {i}, j: {j}")

 

break statement:


You can use the break statement to exit the loop prematurely.


for i in range(5):
    print(i)
    if i == 2:
        break

 

continue statement:


The continue statement can be used to skip the rest of the code inside the loop for the current iteration and proceed to the next iteration.


for i in range(5):
    if i == 2:
        continue
    print(i)

 

else block with for loops:


Similar to while loops, you can include an else block with a for loop. The else block executes when the loop completes normally (i.e., without encountering a break statement).


for i in range(5):
    print(i)
else:
    print("Loop completed normally")

 

These are some common patterns for using for loops in Python. They are useful for iterating over sequences or performing repetitive tasks.