How To Create Nested For Loops In Python?


While creating applications with python we generally need to use list like or array data structures. If we will iterate over list like data we generally use for loop. But some times the data may have multiple dimensions. In order to cope with multiple dimensions we have to define nested for loops.

Nested For Loop

for loops can be nested inside each other. There is no restriction about the count of inner for loop. But using unnecessary nested loops will create performance bottlenecks. We can use following syntax for nested loops.

for A in LIST1:
  for B in LIST2:
    for C in LIST3:
      print(A,B,C)

Nested Loop With Multiple Lists

There are different use cases for nested for loops in Python. In this part we will examine nested for loops with multiple lists. In this example we have lists named name  , car , number . We will nest all lists with 3 for and then print them to the console.

names=['ismail','ali','elif']       
cars=['mercedes','porshe','hyundai'] 
numbers=[1,2,3]
for name in names:                       
  for car in cars:                       
    for number in numbers:               
      print(name+" has "+str(number)+" "+car)
Nested Loop With Multiple Lists
Nested Loop With Multiple Lists

Nested Loop With Single Multi Dimension List

Another popular use case for nested is is iterating over multi dimension lists. Multi dimension list have a list where its elements are list too. Here we will use list named persons where each element is a list which contains personal information.

persons=[['ismail', 30], ['ali', 5], ['elif', 10]]


for person in persons: 
  for value in person: 
    print(value)
Nested Loop With Single Multi Dimension List
Nested Loop With Single Multi Dimension List

Nested Loop with Multiple Range Function

range()function is used to create number lists in a very efficient and easy way. We have all ready examined the range() function and relate topic in the following tutorial.

LEARN MORE  How Enumerate In Python Programming Language?

Python For Loop Tutorial With Examples and Range/Xrange Functions

We will create nested loop with two range() function where each of them starts from 1 and ends at 5. We will multiple each of them

for x in range(1,5): 
  for y in range(1,5): 
    print(x*y)
Nested Loop with Multiple Range Function
Nested Loop with Multiple Range Function

Leave a Comment