How to insert multiple elements into a list?

45,610

Solution 1

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]

Solution 2

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:]
Share:
45,610
TheRealFakeNews
Author by

TheRealFakeNews

Updated on July 09, 2022

Comments

  • TheRealFakeNews
    TheRealFakeNews almost 2 years

    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]

  • Quantum7
    Quantum7 over 6 years
    Note this returns a new list, unlike the insert method
  • sta
    sta over 3 years
    Thank you for contributing an answer. Would you kindly edit your answer to to include an explanation of your code? That will help future readers better understand what is going on, and especially those members of the community who are new to the language and struggling to understand the concepts.
  • Eric Aya
    Eric Aya over 3 years
    Same solution as in Corvus' answer.
  • Manngo
    Manngo about 2 years
    This does the job, but doesn’t answer the actual question directly. The answer should have been something like myList[1:1] = otherList.
  • Alexander
    Alexander almost 2 years
    Why would you pop items and add them to another list one by one?