Home > Blockchain >  Simplifying for loop in Python
Simplifying for loop in Python

Time:03-14

I have a code snippet like this in Python:

#list_1 have a previous value that we dont know
n = 40 #This value can change

list_2 = [0, 0, 0, 0]

#We are trying all the values possibles for 4 positions and 40 different numbers

for a in range(n):
    for b in range(n):
        for c in range(n):
            for d in range(n):
                list_2[0] = a
                list_2[1] = b
                list_2[2] = c
                list_2[3] = d
                if list_1 == list_2:
                   print("Ok")

I want to change the nested for loops into something simpler; what can I do?

CodePudding user response:

Use itertools.product() with the repeat parameter to reduce the amount of nesting:

from itertools import product

for a, b, c, d in product(range(n), repeat=4):
    list_2 = [a, b, c, d] # Can condense the assignments into one line as well.
    if list_1 == list_2:
        print("Ok")

CodePudding user response:

A few ways, some using itertools.product...

for [*list_2] in product(range(n), repeat=4):
    if list_1 == list_2:
        print("Ok")
list_2 = []
for list_2[:] in product(range(n), repeat=4):
    if list_1 == list_2:
        print("Ok")
if tuple(list_1) in product(range(n), repeat=4):
    print("Ok")
if list_1 in map(list, product(range(n), repeat=4)):
    print("Ok")
if len(list_1) == 4 and all(x in range(n) for x in list_1):
    print("Ok")
if len(list_1) == 4 and set(list_1) <= set(range(n)):
    print("Ok")
  • Related