Python Forum

Full Version: Returning true or false in a for loop
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hey everyone,

I'm trying to define a procedure that identifies if the length of each element in a list is the same length as the list. For example the list [[1,2],[3,4]] has a length of two and each element inside the list also has a length of two.

The problem I'm running into is how to return True or False using a 'for loop' for certain test cases.

For example in the below case, the list meets the criteria and returns true.

  def correct_length(n):
    for e in n:
        if len(e) != len(n):
            break
        return False
    return True
     
print correct_length([[1,2,3],
                    [2,3,1],
                    [3,1,2]])
But, when the criteria is not met as in the next example, the output is still true.

def correct_length(n):
    for e in n:
        if len(e) != len(n):
            break
        return False
    return True
        
print correct_length([[1,2,3],
                    [2,3,1],
                    [3,1,2,4]])
I think the problem is probably something simple, but have been beating my head on the desk for a while trying to figure it out. Any help would be greatly appreciated.
The problem is that when the for loop ends, you return False, even though you should return True. The solution is to put the return False where the break is. The return will 'break' out of the function, serving the same purpose.

Another useful trick for similar but more complicated situations is using else on a for loop:

def check_len(sequence):
    for sub_list in sequence:
        if len(sub_list) != len(sequence):
            break
    else:
        return True
    return False
The else statement on the for loop triggers if the break statement was never used.
Remove the break, and indent the return False to the same level as the break.
Thanks a lot guys, I appreciate you clearing up my syntax confusion.

Peace,
Brian