How to insert multiple elements into a list?
The following accomplishes this while avoiding creation of a new list. However I still prefer @RFV5s method.
def insert_to_list(original_list, new_list, index): tmp_list = [] # Remove everything following the insertion point while len(original_list) > index: tmp_list.append(original_list.pop()) # Insert the new values original_list.extend(new_list) # Reattach the removed values original_list.extend(tmp_list[::-1]) return original_list
Note that it's necessary to reverse the order of tmp_list
because pop()
gives up the values from original_list
backwards from the end.