I get an error when adding or subtracting waypoints in MissionPlanner

I write code for mission planning with use Dronekit and Rover 4.2.3 SITL. When I added or subtract waypoints, get an error.
ERROR:

Traceback (most recent call last):
  File "/home/jungo/Desktop/pixhawkCode/Dronekit_test/mission_basic.py", line 237, in <module>
    print('Distance to waypoint (%s): %s' % (nextwaypoint, distance_to_current_waypoint()))
  File "/home/jungo/Desktop/pixhawkCode/Dronekit_test/mission_basic.py", line 111, in distance_to_current_waypoint
    missionitem=vehicle.commands[nextwaypoint-1] #commands are zero indexed
  File "/home/jungo/.local/lib/python3.6/site-packages/dronekit/__init__.py", line 3071, in __getitem__
    raise IndexError('Index %s out of range.' % index)
IndexError: Index 3 out of range.

CODE:

while True:
    print("|||||||||||||||||||||||||")
    print(vehicle.commands.count)
    print("|||||||||||||||||||||||||")
    nextwaypoint=vehicle.commands.next
    print('Distance to waypoint (%s): %s' % (nextwaypoint, distance_to_current_waypoint()))
    
    if nextwaypoint==vehicle.commands.count and distance_to_current_waypoint() <= 3.00:
        print('Return to launch')
        vehicle.mode = VehicleMode("RTL")
        break
    time.sleep(1)
def distance_to_current_waypoint():

    nextwaypoint = vehicle.commands.next
    if nextwaypoint==0:
        return None
    missionitem=vehicle.commands[nextwaypoint-1] #commands are zero indexed
    lat = missionitem.x
    lon = missionitem.y
    alt = missionitem.z
    targetWaypointLocation = LocationGlobalRelative(lat,lon,alt)
    distancetopoint = get_distance_metres(vehicle.location.global_frame, targetWaypointLocation)
    return distancetopoint