def shorten(thelist, maxlen, shorten):
    """
    If thelist has more elements than maxlen, remove elements to make it of size maxlen.
    The parameter shorten is a string which can be one of left, right, both or middle
    and specifies where to remove elements.
    :param thelist: the list to shorten
    :param maxlen: maximum length of the list
    :param shorten: one of left, right, both, middle, where to remove the elements
    :return: the shortened list
    """
    if len(thelist) <= maxlen:
        return thelist
    if shorten == "right":
        return thelist[0:maxlen]
    elif shorten == "left":
        return thelist[-maxlen-1:-1]
    elif shorten == "both":
        excess = len(thelist) - maxlen;
        left = int(excess/2)
        right = excess - left
        return thelist[left:-right]
    elif shorten == "middle":
        excess = len(thelist) - maxlen;
        left = int(excess/2)
        right = excess - left
        return thelist[0:left]+thelist[-right:]
    else:
        raise Exception("Not a valid value for the shorten setting: {}".format(shorten))