Python: How to Remove Keyframe outside a frame range

So I am trying to make a function that will delete all keyframe outside of a certain range. (Start and End Specificaly), However, blender is acting wierdly that I dont know what is wrong with it.

def Delete_Outside_Frame_Range(object, action, start, end):

    for fc in action.fcurves:
        for kf in fc.keyframe_points:

                frame =

                if frame < start or frame > end:      


scene = bpy.context.scene
start = scene .frame_start
end = scene .frame_end

object = bpy.context.object
action = object .animation_data.action

Delete_Outside_Frame_Range(object, action, start, end)

This code theoretically should work? But It just gives me “Keyframe is not in FCurve”. If I wrap it in a try block, it actually delete some random keyframe for some reason. I really have no idea what is wrong with this.

It would be really helpful for me if you can help me to fix this problem

Thank you