added invalid index check for insert_at_index