Sorts a list, such that if l[b] in succsOf(l[a]) then a < b

def sort_by_successors(l, succsOf):
    """ Sorts a list, such that if l[b] in succsOf(l[a]) then a < b """
    rlut = dict()
    nret = 0
    todo = list()
    for i in l:
        rlut[i] = set()
    for i in l:
        for j in succsOf(i):
            rlut[j].add(i)
    for i in l:
        if len(rlut[i]) == 0:
            todo.append(i)
    while len(todo) > 0:
        i = todo.pop()
        nret += 1
        yield i
        for j in succsOf(i):
            rlut[j].remove(i)
            if len(rlut[j]) == 0:
                todo.append(j)
    if nret != len(l):
        raise ValueError("Cycle detected")