Deselect first and last vertices of a path with Python
The two verts with largest angle between two linked selected edges.


  the angle between the first and the last edge may be different but
  it's always larger than between all the other selected edges


Going by images in question you have a closed loop, if the two verts are ends of selected edge path, see below.

Test Script orders a list of selected verts, orders them by "edge angle" if they have two selected linked edges else assigns -1.  The last two vertices are deselected.

Note this is only a proof of context. Getting the angle of three verts a, b, c, edges ab, bc, could also be done via checking dot product of normalized edge vectors. 

import bpy
import bmesh
from math import degrees

def edge_vec(e):
    return e.verts[1].co - e.verts[0].co

def edge_angle(v):
    edges = [e for e in v.link_edges if e.select]
    if len(edges) == 2:
        e0, e1 = edges
        return edge_vec(e1).angle(edge_vec(e0))

    return -1

context = bpy.context
scene = context.scene
ob = context.object
me = ob.data
bm = bmesh.from_edit_mesh(me)
verts = sorted((v for v in bm.verts if v.select), key=lambda v: edge_angle(v))

if len(verts) &gt;= 2:
    for v in verts[-2:]:
        print(v, degrees(edge_angle(v)))
        v.select = False

bmesh.update_edit_mesh(me)


EDIT

For the case here, where the verts in question are at either end of an edge path, it would be a matter of looking for selected verts that have only one selected edge in their link edges

verts = [v for v in bm.verts if v.select 
         and len(e for e in v.link_edges if e.select) == 1]