for loops in python

for loops in python is one of the important concepts in python. for loops are used to iterate over items in the collection. You can use for loop on strings, lists, multiple numbers as they are a collection of items.

for loop on string:

You can loop through a string as string is a sequence of characters.

Example:

for item in 'Tutorial':
    print(item)

Output:

T
u
t
o
r
i
a
l

for loop on list:

You can loop through list as list is collection of items.

Example:

for item in ['John', 'Jane', 'Jack', 'Jim']:
    print(item)

Output:

John
Jane
Jack
Jim

for loop on range of numbers:

You can use loop through range of numbers using for loop.

Example:

for item in range(1, 5):
    print(item)

Output:

1
2
3
4

Nested for loops:

We can use for loop inside another for loop by nesting them.

for x in range(4):
    for y in range(3):
        print(f'({x}, {y})')

Output:

(0, 0)
(0, 1)
(0, 2)
(1, 0)
(1, 1)
(1, 2)
(2, 0)
(2, 1)
(2, 2)
(3, 0)
(3, 1)
(3, 2)

Conclusion:

In this tutorial, you learned how to iterate over the collection of items using for loops in python. You also learned how to use nested for loops in python. If you have problems while implementing code, you can ask me through the comment section.

See Also:

Strings in python

Variables in python

Leave a Reply

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