Saravanan Selvam
Saravanan Selvam

Reputation: 139

How to reduce the nested 'For Loop' complexity in python?

In the below mentioned code,my outer loop runs unnecessarily even if the condition is satisfied at the first iteration.I dont want to run the nested loop unnecessarily.How to reduce the nested loop complexity to increase the code performance?

 for i in List1:
   for j in sourceList:
     for k in List2:
      if (j[0]==i[1] and j[1]==k[1]):
       print (i[0],k[0])

Upvotes: 2

Views: 4491

Answers (3)

lmiguelvargasf
lmiguelvargasf

Reputation: 69725

Considering your goal is to print line by line i[0], k[0], you could use list comprehensions to reduce the complexity of a for loop as follows:

'\n'.join(f'{i[0]},{k[0]}' for i in List1 for j in sourceList if j[0]==i[1] for k in List2 if j[1]==k[1])

Upvotes: 1

Devesh Kumar Singh
Devesh Kumar Singh

Reputation: 20490

You can check the first condition if j[0] == i[1] before starting the innermost loop, and break on the first match.

for i in List1:
    for j in sourceList:
        #Check condition and only then run inner loop
        if j[0] == i[1]:
            for k in List2:
                #Break out of loop on first match
                if j[1] == k[1]:
                    print(i[0], k[0])
                    break
        else:
            continue

Upvotes: 1

U13-Forward
U13-Forward

Reputation: 71570

You can do break:

for i in List1:
    for j in sourceList:
        for k in List2:
            if (j[0]==i[1] and j[1]==k[1]):
                print (i[0],k[0])
                break

Or use a def (function):

def f():
    for i in List1:
        for j in sourceList:
            for k in List2:
                if (j[0]==i[1] and j[1]==k[1]):
                    return (i[0],k[0])

Upvotes: 0

Related Questions