-2

I'm trying to understand some code in python. (I don't know python, only c/c++)

def merge(left, right):
    result = []
    left_idx, right_idx = 0, 0
    while left_idx < len(left) and right_idx < len(right):

        if left[left_idx] <= right[right_idx]:
            result.append(left[left_idx])
            left_idx += 1
        else:
            result.append(right[right_idx])
            right_idx += 1

    if left:   # Confused by this line.
        result.extend(left[left_idx:])
    if right:
        result.extend(right[right_idx:])
    return result

I think I've understood most of the code above except for the if left and if right statements. The way I understand if statements are that they must have an expression following them which evaluates to either a 1 or 0.

user129048
  • 129
  • 7
  • Every value in Python (and pretty much every other language) has a 'truthy' or 'falsey' value in a boolean context. Look up which is which: it's in the docs. Empty list is falsey, non-empty list is truthy. It's been a long time since you were restricted to 0 and 1, even in C (C99 added stdbool.h) let alone C++ which has a proper boolean type. – Jared Smith Feb 02 '18 at 03:03
  • Possible duplicate of [What is Truthy and Falsy in python? How is it different from True and False?](https://stackoverflow.com/questions/39983695/what-is-truthy-and-falsy-in-python-how-is-it-different-from-true-and-false) – Stephen Rauch Feb 02 '18 at 03:16

1 Answers1

0

Think of this like this, what ever conditions given after if will be evaluated then coerced to a Boolean (not 0 and 1). If True -> execute the body of if.

bool([]) # false 
bool([2, 34]) # true
Arun Karunagath
  • 1,593
  • 10
  • 24