Nested Loops

A nested loop is a loop that is inside another loop. In other words, a loop is nested within another loop. Here's an example of a nested loop in Python:

# initialize the outer loop variable i to 1
i = 1

# while the outer loop variable i is less than or equal to 3
while i <= 3:
    # initialize the inner loop variable j to 1
    j = 1

    # while the inner loop variable j is less than or equal to 3
    while j <= 3:
        # print the value of the outer and inner loop variables
        print(f"i = {i}, j = {j}")
        # increment the inner loop variable j by 1
        j = j + 1

    # increment the outer loop variable i by 1
    i = i +1

In this example, the outer while loop will execute 3 times, and the inner while loop will execute 3 times on each iteration of the outer loop. This means that the inner while loop will execute a total of 9 times.

Here's an example of iterating over a list of list

# iterate over a list of lists
list_of_lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

for sublist in list_of_lists:
    # iterate over the elements in the current sublist
    for element in sublist:
        print(element)

Nested loops are useful for iterating over a list of lists, or for any situation where you need to loop over multiple sequences in a single block of code. By using nested loops, you can avoid writing separate loops for each sequence, which can make your code more concise and easier to read.

Server Academy Members Only

Want to access this lesson? Just sign up for a free Server Academy account and you'll be on your way. Already have an account? Click the Sign Up Free button to get started..

0 0 votes
Lesson Rating
Subscribe
Notify of
profile avatar
0 Comments
Inline Feedbacks
View all comments

Saving Progress...

Sign up for free!

Sign up for free and get instant access to this course!.

Python 3 Fundamentals

0%

0/1 Lessons

Installing Python on Windows

• 1hr 17min

0 / 4 lessons complete

Python Basics

• 28min

0 / 7 lessons complete

Python Variables

• 41min

0 / 8 lessons complete

Even more Python Variables!

• 41min

0 / 6 lessons complete

Conditional Statements

• 15min

0 / 3 lessons complete

Writing Functions

• 30min

0 / 5 lessons complete

Python Loops

• 23min

0 / 5 lessons complete

Python PIP and Modules

• 18min

0 / 4 lessons complete

RegEx

• 26min

0 / 4 lessons complete

Working with APIs

• 12min

0 / 3 lessons complete

Course Conclusion

• 2min

0 / 1 lessons complete