5 Best Ways to Python Prepend to List [with Examples]
Table of Contents
Why do we need to Python prepend to a list ?
Prepend is a way of adding a new element at the beginning of a list in Python. The main reason to use prepend is to maintain the order of elements in the list, especially when you want the newly added element to be the first element in the list.
For example, Suppose you have a list of users according to their priority. Now you want to add the most prior user to the list then you will pretend to add him at the first position.
Table of Contents
Different Ways to Python Prepend to List
1. Using insert() method to prepend to list
The Easiest and most straightforward way is the insert() method .The insert function takes 2 arguments.
- index – An “index” refers to the position of an element within that data structure.
- value -The “value” of an element refers to the data stored in that particular location.
Syntax:
list_name.insert(index , value)
Example:
names = ["John" ,"Mark", "Daniel"]
names.insert(0 , "Stacy")
print(names)
Output:
['Stacy', 'John', 'Mark', 'Daniel']
In the above example, the Stacy name is inserted at position 0.
2. With the Slicing [] operator
Slicing is a powerful feature in Python that allows you to extract a portion of a list, tuple, string, or any other sequence type.
It allows you to select a range of elements from the sequence by specifying the start and end indices, as well as the step (if desired).
Prepend in Python can be achieved using slicing by concatenating two lists. You can create a new list with the element you want to prepend as the first element, followed by the original list.
For Example:
salaries = [10, 20 ,30, 40, 50]
salaries[0:2] = [5 , 15]
print(salaries)
Output:
[5, 15, 30, 40, 50]
In the above example , all the numbers which are in range 0 to 2 are getting replaced by the new list of [5,15].
3. With the [] and + Operator
We can use the + operator to concatenate two lists. To add an element to a list at the first position, you can create a new list with the element and then concatenate it with the original list.
Syntax :
old_list = [new_element] + old_list
For Example:
numbers = [10 ,20 ,30 ,40 ,50]
numbers = [5] + numbers
print(numbers)
Output:
[5, 10, 20, 30, 40, 50]
In this example, we have created a new list with a single element of the old list and appended the old list to this new list using + operator.
4. Use [] and * Operator
You can use the * operator to repeat a list multiple times. To prepend an element to a list, you can create a new list with the element and repeat it one time, and then concatenate it with the original list.
Syntax:
old_list = [new_element] * repetition + old_list
For Example:
vehicles = ["Cars","Cars","Bike"]
vehicles = ["Bike"] *2 + vehicles
print(vehicles)
Output
['Bike', 'Bike','Cars', 'Cars', 'Bike']
In the above example we have added 2 bikes at the start of the list
5. Using Collection module
A deque is a data structure in Python that allows you to insert and remove elements from both ends efficiently, unlike a regular list where inserting or removing elements from the beginning is an expensive operation.
Collections.deque.appendleft() is a method in Python that allows you to add an element to the left (beginning) of a double-ended queue (deque).
For Example:
from collections import deque
#initialise list with list of message tokens
message = ["Welcome" , "to" , "Goom !"] #converting list to deque object
message = deque(message) #left appending the new message
tokensmessage.appendleft("User")
message.appendleft("Hello")
print(message)
Output:
deque(['Hello', 'User', 'Welcome', 'to', 'Goom !'])
The appendleft() method allows you to add elements to the beginning of the deque in an efficient manner.
Errors while working on prepend to a list in Python
TypeError
‘list’ object is not callable: This error occurs when you try to prepend an element to a list and use the same name for the list and a built-in Python function.
For example:
message = ["goom" , "best place to learn python"]
print(message(0))
Output:
Traceback (most recent call last):File "<stdin>", line 1, in <module>TypeError: 'list' object is not callable
To avoid this error we can use the list names other than python built in functions.
For example :
message = ["goom" , "best place to learn python"]
print(message[0])
Output:
goom
IndexError
list assignment index out of range:
This error occurs when you try to prepend an element using the wrong index value.
For example:
goom = ["Easy to learn" , "Easy to understand"]
goom[3] = "Easy to execute"
Output:
Traceback (most recent call last):File "<stdin>", line 1, in <module>IndexError: list assignment index out of range
To fix this error, use a proper valid index and check for size before adding the value to the index.
AttributeError
This error occurs when you try to perform some operation on a list using the wrong function name.
For example:
goom = ["Easy to learn" , "Easy to understand"]
goom.add(0 , "best place to learn")
print(goom)
Output –
File "/home/main.py", line 2, in <module>goom.add(0 , "best place to learn")AttributeError: 'list' object has no attribute 'add'
To fix this error , use the proper names from the documentation before using them to change data
For Example:
goom = ["Easy to learn" , "Easy to understand"]
goom.insert(0 , "best place to learn")
print(goom)
Output:
['best place to learn', 'Easy to learn', 'Easy to understand']
Use Cases for prepend elements to list in Python
Queue Operations
A queue is a data structure that follows the First-In-First-Out (FIFO) principle. Which means any element that is added to the queue first gets removed first .Prepending elements to a list can be used to implement a queue, where elements are added to the beginning of the list and removed from the end.
For Example:
user_queue = ['Robert' , 'Goom' ,'Rebecca']
def add_user(name):
user_queue.insert(0 ,name)
print("User Added and the Queue is:", user_queue)
def remove_user():
user_queue.pop()
print("User removed and the Queue is:", user_queue)
print("Initial Queue :", user_queue)
add_user("Hawk")
add_user("Tom")
remove_user()
remove_user()
Output –
Initial Queue : ['Robert', 'Goom', 'Rebecca']
User Added and the Queue is: ['Hawk', 'Robert', 'Goom', 'Rebecca']
User Added and the Queue is: ['Tom', 'Hawk', 'Robert', 'Goom', 'Rebecca']
User removed and the Queue is: ['Tom', 'Hawk', 'Robert', 'Goom']
User removed and the Queue is: ['Tom', 'Hawk', 'Robert']