list extend() to index, inserting list elements not only to the end

Question:

I’m looking for the most pythonic way to implement a version of the list extend function, where it extends to a given index instead of the end of the list.

a_list = [ "I", "rad", "list" ]                                                       
b_list = [ "am", "a" ]
a_list.my_extend( b_list, 1 ) # insert the items from b_list into a_list at index 1

print( a_list ) # would output: ['I', 'am', 'a', 'rad', 'list']

Is there a way to do this without building a new list, like this?

a_list = [ "I", "rad", "list" ]
b_list = [ "am", "a" ]
c_list = []

c_list.extend( a_list[:1] )
c_list.extend( b_list     )
c_list.extend( a_list[1:] )

print( c_list ) # outputs: ['I', 'am', 'a', 'rad', 'list']

That approach isn’t actually so bad, but I have a hunch it could be easier. Could it?

Asked By: mwcz

||

Answers:

Sure, you can use slice indexing:

a_list[1:1] = b_list

Just to demonstrate the general algorithm, if you were to implement the my_extend function in a hypothetical custom list class, it would look like this:

def my_extend(self, other_list, index):
    self[index:index] = other_list

But don’t actually make that a function, just use the slice notation when you need to.

Answered By: David Z
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.