How to insert multiple elements into a list? How to insert multiple elements into a list? python python

How to insert multiple elements into a list?


To extend a list, you just use list.extend. To insert elements from any iterable at an index, you can use slice assignment...

>>> a = list(range(10))>>> a[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]>>> a[5:5] = range(10, 13)>>> a[0, 1, 2, 3, 4, 10, 11, 12, 5, 6, 7, 8, 9]


Python lists do not have such a method. Here is helper function that takes two lists and places the second list into the first list at the specified position:

def insert_position(position, list1, list2):    return list1[:position] + list2 + list1[position:]


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.