[Solved] How do I check elements of the list here [closed]


The definition of valid_list should be out of the for loop, otherwise it will be overwritten. Besides, use a flag_valid to indicate whether the invalid elements exist. Try this code:

from itertools import permutations 

def code():
    valid_list = []
    for line,lists in enumerate(permutations(range(4))):        
        flag_valid = True
        for index,elements in enumerate(lists):
            if index != len(lists) - 1:  #list index out of range escape condition
                if abs(lists[index] - lists[index + 1]) == 1:
                    flag_valid = False
                    break;
        if flag_valid == True:
                valid_list.append(lists)
    return valid_list

print code()

1

solved How do I check elements of the list here [closed]