Can I extend list in Python with prepend elements instead of append?
Asked Answered
A

4

43

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.

Airspace answered 1/11, 2013 at 21:57 Comment(2)
Why can't you do b.extend(a)?Originate
@iCodez: sometimes a is called very_important and b is called aux. You may want to keep the former and forget about the latter.Diagnostician
N
107

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]
Newsstand answered 1/11, 2013 at 21:58 Comment(3)
Sadly, a[-1:] doesn't work (for obvious reasons). It would be so nice to have symmetry, but alas…Coremaker
@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.Newsstand
Strange why the list.extend() method does not have a parameter of position for extend index. Like b.extend(a, 0).Vinegar
R
17

This is what you need ;-)

a = b + a
Romantic answered 1/11, 2013 at 22:0 Comment(4)
u'll end up adding the corresponding array elements.Odometer
@Odometer Only if you are using numpy.Bickerstaff
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) ;)Jaundiced
Sometimes, you need to preserve a; e.g. if it is a memory reference in another list. This solution won't work in this caseGaiety
M
4

You could use collections.deque:

import collections
a = collections.deque([1, 2, 3])
b = [4, 5, 6]
a.extendleft(b[::-1])
Meares answered 1/11, 2013 at 22:1 Comment(1)
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.Persia
P
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.

Persia answered 1/11, 2013 at 22:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.