Python for keyword

Python for keyword is a powerful construct that allows you to iterate over a sequence of elements or perform repetitive tasks with ease.

Whether you’re dealing with lists, tuples, strings, or even custom objects, the for loop provides a concise and intuitive way to iterate through each item.

Iterating over Sequences

One of the most common use cases of the for loop is to iterate over sequences such as lists, tuples, and strings.

The for loop follows the syntax:

for item in sequence:
    # Code block

Now, let’s take a look at this example:

fruits = ['apple', 'banana', 'grape']
for fruit in fruits:
    print(fruit)

Output:

apple
banana
grape

In this example, the for loop iterates through the fruits list, assigning each item to the variable fruit.

The code block then prints each fruit to the console.

Iterating with Range

The for loop can also be used with the built-in range() function to generate a sequence of numbers.

The range() function creates a range object that represents a sequence of numbers from a start value (inclusive) to an end value (exclusive).

Here’s an example:

for num in range(1, 6):
    print(num)

Output:

1
2
3
4
5

In this case, the for loop iterates through the numbers generated by the range() function and prints each value to the console.

Iterating over Dictionaries

The for loop can be used to iterate over dictionaries as well.

When iterating over a dictionary, the loop variable represents each key in the dictionary.

You can then access the corresponding value using the key.

Consider the following example:

student_grades = {'Paul': 95, 'Steve': 79, 'Eve': 88}
for student in student_grades:
    print(student, ":", student_grades[student])

Output:

Paul : 95
Steve : 79
Eve : 88

In this case, the for loop iterates over the keys in the student_grades dictionary, and for each key, it prints the key-value pair.

Nested for Loops

Python allows you to have nested for loops, where you can iterate over multiple sequences simultaneously.

This is particularly useful when working with two-dimensional lists or matrices.

Let’s consider an example:

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for row in matrix:
    for element in row:
        print(element)

Output:

1
2
3
4
5
6
7
8
9

In this example, the outer for loop iterates over each row in the matrix, and the inner for loop iterates over the elements in each row.

The code block prints each element individually.

Conclusion

The for keyword is a versatile tool in Python that enables you to iterate over sequences, perform repetitive tasks, and process data efficiently.

Leave a Reply

Your email address will not be published. Required fields are marked *