loop in loop in python

Looping in loops, also known as nested loops, is a common task in programming. In Python, we can achieve this by using one or more loops inside another loop.

Let's say we want to print all the possible combinations of two lists, we can use nested loops as follows:

main.py
list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']

for i in list1:
    for j in list2:
        print(i, j)
99 chars
7 lines

In the above example, we have two lists list1 and list2. We then use two for loops, one for each list, to print all the possible combinations of the two lists.

The outer loop iterates over the elements of list1, while the inner loop iterates over the elements of list2. Inside the inner loop, we print out the current values of i and j.

Nested loops can be used for many tasks, including matrix multiplication, image processing, and data analysis. However, be careful not to create too many nested loops as it can lead to slow and inefficient code.

related categories

gistlibby LogSnag