Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 421
mwcz Avatar asked Sep 11 '11 02:09

mwcz


People also ask

What is the list extend () method?

The extend() method adds the specified list elements (or any iterable) to the end of the current list.

How append () and extend () are different with reference to list in Python?

Python append() method adds an element to a list, and the extend() method concatenates the first list with another list (or another iterable). When append() method adds its argument as a single element to the end of a list, the length of the list itself will increase by one.

How do I add elements to the end of a list?

If we want to add an element at the end of a list, we should use append . It is faster and direct. If we want to add an element somewhere within a list, we should use insert . It is the only option for this.


1 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.

like image 74
David Z Avatar answered Sep 25 '22 08:09

David Z