make all of the subplots have the same limits, turn off unnecessary ticks

def align_subplots(N,M,xlim=None, ylim=None):
    """make all of the subplots have the same limits, turn off unnecessary ticks"""
    #find sensible xlim,ylim
    if xlim is None:
        xlim = [np.inf,-np.inf]
        for i in range(N*M):
            plt.subplot(N,M,i+1)
            xlim[0] = min(xlim[0],plt.xlim()[0])
            xlim[1] = max(xlim[1],plt.xlim()[1])
    if ylim is None:
        ylim = [np.inf,-np.inf]
        for i in range(N*M):
            plt.subplot(N,M,i+1)
            ylim[0] = min(ylim[0],plt.ylim()[0])
            ylim[1] = max(ylim[1],plt.ylim()[1])

    for i in range(N*M):
        plt.subplot(N,M,i+1)
        plt.xlim(xlim)
        plt.ylim(ylim)
        if (i)%M:
            plt.yticks([])
        else:
            removeRightTicks()
        if i<(M*(N-1)):
            plt.xticks([])
        else:
            removeUpperTicks()