44

I can perform

a = [1,2,3] b = [4,5,6] a.extend(b) # a is now [1,2,3,4,5,6] 

Is there way to perform an action for extending list and adding new items to the beginning of the list?

Like this

a = [1,2,3] b = [4,5,6] a.someaction(b) # a is now [4,5,6,1,2,3] 

I use version 2.7.5, if it is important.

2
  • 3
    Why can't you do b.extend(a)? Commented Nov 1, 2013 at 21:59
  • 2
    @iCodez: sometimes a is called very_important and b is called aux. You may want to keep the former and forget about the latter. Commented Jul 31, 2014 at 14:14

4 Answers 4

112

You can assign to a slice:

a[:0] = b 

Demo:

>>> a = [1,2,3] >>> b = [4,5,6] >>> a[:0] = b >>> a [4, 5, 6, 1, 2, 3] 

Essentially, list.extend() is an assignment to the list[len(list):] slice.

You can 'insert' another list at any position, just address the empty slice at that location:

>>> a = [1,2,3] >>> b = [4,5,6] >>> a[1:1] = b >>> a [1, 4, 5, 6, 2, 3] 
Sign up to request clarification or add additional context in comments.

2 Comments

Sadly, a[-1:] doesn't work (for obvious reasons). It would be so nice to have symmetry, but alas…
@JürgenA.Erhard: There absolutely is symmetry, but -1 is not the end of the list, it is the last element. a[-1:] is symmetrical with a[:1] at the start of the list, both contain 1 element. This is why I explicitly mention len(list) in my answer.
17

This is what you need ;-)

a = b + a 

4 Comments

u'll end up adding the corresponding array elements.
@magarwal Only if you are using numpy.
not if you need to modify a, try this: >>> a is b+a (b+a is neither b nor a, but a completely new object) ;)
Sometimes, you need to preserve a; e.g. if it is a memory reference in another list. This solution won't work in this case
4

You could use collections.deque:

import collections a = collections.deque([1, 2, 3]) b = [4, 5, 6] a.extendleft(b[::-1]) 

1 Comment

This is the best way if you don't need to be able to access arbitrary elements. insert and adding lists tends to yield quadratic algorithms, where linear is possible.
3

If you need fast operations and you need to be able to access arbitrary elements, try a treap or red-black tree.

>>> import treap as treap_mod >>> treap = treap_mod.treap() >>> for i in range(100000): ... treap[i] = i ... >>> treap[treap.find_min() - 1] = -1 >>> treap[100] 100 

Most operations on treaps and red-black trees can be done in O(log(n)). Treaps are purportedly faster on average, but red-black trees give a lower variance in operation times.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.