Error in Merge Sort function in yield

I received a merge sort function from someone else, here’s the code:

def mergesort(lst):
    l = len(lst)
    if l <= 1:
        return lst
    return mergesorted(mergesort(lst[:l//2]), mergesort(lst[l//2:]))

def mergesorted(a, b):
    i, j = 0, 0
    la, lb = len(a), len(b)
    while i < la or j < lb:
        if i == la or (j != lb and a[i] > b[j]):
            yield b[j]
            j += 1
        else:
            yield a[i]
            i += 1

I’m still trying to understand how yield works, so when I was trying to print the result to test the function, I used

m = mergesort([4, 2, 5, 1, 6, 3])

for i in m :
    print(i)

It gave me this error:

Traceback (most recent call last):
    for i in m :
    la, lb = len(a), len(b)
TypeError: object of type 'generator' has no len()

Am I using the print statement wrong?

Answer

The fact that mergesorted has the yield keyword in it means that it’s a generator. And like the error message says, generators don’t have a len method.
The reason that generators don’t have a len method is because generators don’t actually know what values they’re going to yield, until it’s time to yield them. Unlike objects like lists or tuples.
In this case, I don’t see any advantage to using yield instead of return.

Leave a Reply

Your email address will not be published. Required fields are marked *