Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 755
Daniil Grankin Avatar asked Nov 01 '13 21:11

Daniil Grankin


People also ask

Can you prepend to a list in Python?

To prepend to a list in Python, use the list. insert() method with index set to 0, which adds an element at the beginning of the list. The insert() is a built-in Python function that inserts an item to the list at the given index.

What can I use instead of append in Python?

append() adds a single element to the end of the list while . extend() can add multiple individual elements to the end of the list.

What is the difference between append () and extend () of lists with example?

When append() method adds its argument as a single element to the end of a list, the length of the list itself will increase by one. Whereas extend() method iterates over its argument adding each element to the list, extending the list.


2 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] 
like image 106
Martijn Pieters Avatar answered Sep 21 '22 13:09

Martijn Pieters


This is what you need ;-)

a = b + a 
like image 38
Artur Avatar answered Sep 25 '22 13:09

Artur