Can I extend list in Python with prepend elements instead of append?
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]
You could use collections.deque
:
import collectionsa = collections.deque([1, 2, 3])b = [4, 5, 6]a.extendleft(b[::-1])