38

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.

dreftymac
  • 31,404
  • 26
  • 119
  • 182
Daniil Grankin
  • 3,841
  • 2
  • 29
  • 39
  • 3
    Why can't you do `b.extend(a)`? –  Nov 01 '13 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. – Peque Jul 31 '14 at 14:14

4 Answers4

99

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]
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Sadly, a[-1:] doesn't work (for obvious reasons). It would be so nice to have symmetry, but alas… – Jürgen A. Erhard Aug 05 '21 at 11:07
  • @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. – Martijn Pieters Aug 05 '21 at 13:35
17

This is what you need ;-)

a = b + a
Artur
  • 7,038
  • 2
  • 25
  • 39
4

You could use collections.deque:

import collections
a = collections.deque([1, 2, 3])
b = [4, 5, 6]
a.extendleft(b[::-1])
TerryA
  • 58,805
  • 11
  • 114
  • 143
  • 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. – dstromberg Nov 01 '13 at 22:52
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.

dstromberg
  • 6,954
  • 1
  • 26
  • 27