0

Basically, my code removes all duplicates that is next to eachother but for some reason i get error for empty list. I would like to know what code should I add to remove the error when the list is empty?

My code works for list with integers like below for example:

def remove_adjacent(nums):
    k2 = [a for a,b in zip(nums, nums[1:]+[not nums[-1]]) if a != b]
    return k2

remove_adjacent([1, 2, 2, 2, 3, 3]) == [1, 2, 3]

AS you can see it works but when I have an empty list I get this error:

 remove_adjacent([]) == list index out of range

What code should i add to fix this function?

1 Answer 1

2

Try to check first using if statement if the list argument is empty, then return an empty list (or any text depends on the description of the problem) if it is.

def remove_adjacent(nums):
    if len(nums) == 0: 
        return []   
    k2 = [a for a,b in zip(nums, nums[1:]+[not nums[-1]]) if a != b]
    return k2

Another approach to check if list is empty:

if not nums:
    return []

Or return string based on the given condition of the problem

You can also try using try-except block to catch the IndexError in case the given list is empty.

def remove_adjacent(nums):
    try:
        k2 = [a for a,b in zip(nums, nums[1:]+[not nums[-1]]) if a != b]
    except IndexError:
        k2 = "The list is empty"
    return k2
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.