Search code examples
pythonbuilt-in

Error "object of type 'NoneType' has no len()" on list explicitely created with list()


I am new to Python and for my AI class I was trying to do an Huffman encoding program for strings. For that, I need to build an optimized weigthed tree. Thing is, I'm trying to call the len() function on a variable explicitly created with the list() built-in function, but it doesn't work. What am I doing wrong ?

Here's the code:

def opti(text):
        occ = occurences(text)
        occ = dict(sorted(occ.items(), key=lambda item: item[1]))
        l_n = list(occ.items())
        while len(l_n) > 1:
                n1 = l_n.pop(0)
                n2 = l_n.pop(0)
                n = Noeud(n1[1] + n2[1], n1, n2)
                l_n.append((n, n.valeur))
                l_n = l_n.sort(key=lambda tup: tup[1])
        return l_n

class Noeud:
        def __init__(self, value, left, right):
                self.value = value
                self.left = left
                self.right = right

If I print the variable l_n I'm clearly getting a list so I don't understand why this isn't working. I've already tried looking for an answer on other topics but the answer mostly were about other functions modifying the type to NoneType whereas here I'm clearly using the list constructor function.

The function occurences returns a dictionary containing the number of occurences of each character in a string, if that matters.


Solution

  • l_n = l_n.sort(key=lambda tup: tup[1])
    

    Here sort() function sorts list inplace. Hence it retuns None.

    Instead try this:

    l_n = sorted(l_n, key=lambda tup: tup[1])

    OR Just this: l_n.sort(key=lambda tup: tup[1])