insert()Method to Prepend to a List in Python
deque.appendleft()Method to Prepend to a List in Python
- Create a New List to Prepend to a List in Python
This tutorial describes how to prepend to a list in Python. The tutorial also lists some example codes to explain multiple ways of prepending to a list.
insert() Method to Prepend to a List in Python
insert() is one of the prevalent and most used approaches.
insert() is provided by the
list library. The
list.insert(pos, element) takes two arguments,
element as its parameters.
pos defines the position of the element.
An example code to use this method is shown below:
lists =['james', 'tim', 'jin'] lists.insert (0, "steve") print (lists)
['steve', 'james', 'tim', 'jin']
However, the time consumed by the
list.insert() operation is a little more. To improve the time performance, we can use the
deque.appendleft() Method to Prepend to a List in Python
collections module of Python offers multiple data structures. In Python 2.4,
deque(), a double-ended queue, is added to the
collections. It is a list like a container that is efficient in appending and pop up processes. The
deque data structure has an
appendleft(element) method. It takes an element and appends it at the beginning of the list.
An example code for this method is given below:
import collections dequeue = collections.deque([5,2,6,8,1]) print(dequeue) dequeue.appendleft(10) print(dequeue)
deque([5, 2, 6, 8, 1]) deque([10, 5, 2, 6, 8, 1])
Create a New List to Prepend to a List in Python
A very simple and trivial solution can be creating a new list with the desired element, x, for example, at the 0th index of the list. Of course, you will not prepend x to the list but create a new list with x already at the first position in the list.
A basis code for this approach is given below.
lists =['james', 'tim', 'jin'] new_list = ['x'] + lists print (new_list)
['x', 'james', 'tim', 'jin']
Use List Slicing to Prepend to a List in Python
List slicing is yet another method to prepend to a list. An element is prepended to the list by assigning the
0th slice to it.
An example code for this method is as follows:
temp_list = [4,5,8,10,13] print(temp_list) temp_list[:0] =  print(temp_list)
[4, 5, 8, 10, 13] [12, 4, 5, 8, 10, 13]