Search code examples
pythonlistinsert

How to insert multiple elements into a list?


In JavaScript, I can use splice to insert an array of multiple elements in to an array: myArray.splice(insertIndex, removeNElements, ...insertThese).

But I can't seem to find a way to do something similar in Python without having concat lists. Is there such a way? (There is already a Q&A about inserting single items, rather than multiple.)

For example myList = [1, 2, 3] and I want to insert otherList = [4, 5, 6] by calling myList.someMethod(1, otherList) to get [1, 4, 5, 6, 2, 3]


Solution

  • 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]