Search code examples
pythonlistloopspython-3.7

How to find if there are 2 elements of same value consecutively in a list?


For example, [1,3,3,5] should return True while [1,3,1,3] should return False.

I am looking for a simple solution using loops.

I tried the following:

def conseq(nums):
    for i in range (len(nums)):
        if nums[i]==nums[i+1]:
            return True
            break
        else:
            return False

Solution

  • The first time your function encounters 2 consecutive numbers which are different, it returns False. Returning from a function ends that function immediately, the function does not continue after that. This is also why the break is not necessary.

    Another issue with your code is that once you reach the final number, nums[i + 1] will access out of the bounds of the array. That's why you should iterate over len(nums) - 1 rather than len(nums) - there's no reason to check the final number because there's nothing after it.

    def conseq(nums):
        for i in range(len(nums) - 1):
            if nums[i]==nums[i+1]:
                return True
    
        # Only return False once we've exhausted all numbers.
        # Since we didn't return True so far - it means there are
        # no consecutive equal numbers, so we can safely return False
        return False