Looping through selected objects one at a time?
Essentially you need to create a list of objects based on the current selection that will not change if the selection changes.

import bpy
# store selection in list that in future will not change with selection
sel_objs = [obj for obj in bpy.context.selected_objects if obj.type == 'MESH']
bpy.ops.object.select_all(action='DESELECT')
if sel_objs:
    obj1 = sel_objs.pop()
    obj1.select = True
    bpy.context.scene.objects.active = obj1
while len(sel_objs) &gt;= 1:
    obj2 = sel_objs.pop()
    obj2.select = True
    bpy.ops.object.join()