Search code examples
pythondata-analysis

IF-Else One-Line Comprehension


Here is the example of my code:

It returns True if 3 is followed by 3, else returns False Below code is working like a charm

def has_33(nums):
    for i in range(len(nums)-1):
        if (nums[i] ==3) and (nums[i+1] ==3):
            return True
    return False
has_33([1, 3, 3])

Below code is working as well:

def has_33(nums):
    return any([(nums[i] ==3) and (nums[i+1] ==3) for i in range(len(nums)-1)])

When I try to make one-line comprehension of this code, it doesn't work:

def has_33(nums):
    return True if (nums[i] ==3) and (nums[i+1] ==3) else False for i in range(len(nums)-1)

has_33([1, 3, 3])

I am just curious to know why it doesn't work and how to fix it.


Solution

  • If you are trying to use list comprehension then following code works flawlessly:

    def has_33(nums):
        return   any([True if (nums[i] ==3) and (nums[i+1] ==3) else False  for i in range(len(nums)-1) ])
    print(has_33([1, 3, 3]))