'Difference between using function in function and just using one function in python?

In python, I made merge sort algorithm but it dosen't work.

def merge_sort(L:list):
    if len(L) > 1:
        mid = len(L) // 2
        left = merge_sort_help(L[:mid])
        right = merge_sort_help(L[mid:])
        merge(left, right)
    elif len(L) == 1:
        return L
def merge(left, right):
    ans = []
    while len(left) and len(right):
        if left[0] >= right[0]:
            ans.append(right.pop(0))
        elif left[0] < right[0]:
            ans.append(left.pop(0))
    if len(left):
        ans += left
    elif len(right):
        ans += right
    return ans

Error was TypeError: object of type 'NoneType' has no len(). But when I didn't use merge function and just copy/pasted the merge function into merge_sort function(above elif), it worked. What's the difference between using function in function and just using one function?



Solution 1:[1]

There's no difference as such. Converting a block of code into function will help you with reusing it in multiple places.

The error looks like some edge case is popping up in the merge function, where it is trying to get the length of a NoneType object.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 RaviTezu