Python For-In

The 'for-in' loop concepts in Python.

Remember: In Python, 'for' and 'for-in' loops are essentially the same thing. The 'for-in' loop is simply a more descriptive way of expressing a loop that iterates over items in an iterable. The keyword 'in' is used to indicate that the loop will iterate over each item in the specified iterable.

for-in

The 'for' loop in Python is used to iterate over a sequence (such as a list, tuple, string, or dictionary) or other iterable objects. It allows you to execute a block of code multiple times, each time with a different value from the sequence.

Its general syntax is as follows:

for element in iterable:
    # code block

Breakdown:

1. Iterable: An object capable of returning its members one at a time. This can be a sequence like a list, tuple, string, or a generator, etc.

2. Element: A variable that takes the value of the next item in the iterable for each iteration of the loop.

3. Code block: The indented block of code that gets executed for each iteration of the loop. This is where you put the logic you want to execute repeatedly.

Example of iterating over a list:

PDF Copy Code
# Python: for-in loop
my_list = [1, 2, 3, 4, 5]

for num in my_list:
    print(num)
Output:
1
2
3
4
5

You can also use the 'range()' function with the 'for' loop to iterate over a sequence of numbers:

PDF Copy Code
# Python: for-in loop with range() function

for i in range(5):
    print(i)
Output:
0
1
2
3
4

The 'for' loop can also be combined with conditional statements like 'if', 'elif', and 'else' for more complex logic within the loop.

PDF Copy Code
# Python: find odd or even number
for num in range(10):
    if num % 2 == 0:
        print(num, "is even")
    else:
        print(num, "is odd")
Output:
0 is even
1 is odd
2 is even
3 is odd
4 is even
5 is odd
6 is even
7 is odd
8 is even
9 is odd

Note: The code that is intended to be executed within the loop should be indented properly.

Nested for-in

Nested 'for-in' loops in Python allow you to iterate over multiple sequences or iterables in a nested fashion. This is useful when you need to traverse through elements of a multidimensional structure, such as a list of lists or a matrix.

PDF Copy Code
# Python: for-in loop to print matrix vnumbers
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

for row in matrix:
    for element in row:
        print(element, end=" ")
    print()  # Print a newline after each row
Output:
1 2 3 
4 5 6 
7 8 9 

In this example, we have a matrix represented as a list of lists. The outer loop iterates over each row of the matrix, and the inner loop iterates over each element within that row. We print each element followed by a space, and after each row, we print a newline character to move to the next line.

Learn how matrix algorithms work with programming examples.

What's Next?

We actively create content for our YouTube channel and consistently upload or share knowledge on the web platform.