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

Question:

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.

Asked By: Daniil Grankin

||

Answers:

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]
Answered By: Martijn Pieters

This is what you need 😉

a = b + a
Answered By: Artur

You could use collections.deque:

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

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.

Answered By: dstromberg
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.