This Python tutorial explains how to prepend to a list. The article also includes several sample scripts that demonstrate various methods of prepending to a list.
To append an item to the end of a list, we usually utilize the append() procedure. However, appending an element to the beginning of a list, also known as prepending an element to a list, is sometimes required.
In Python, the term prepend is a shortcut for the term pre-append. You might have used the append() function to add as many values to the end of a data structure as feasible. On the other hand, the prepend term is used to put values at the beginning of any data structure. As a result, we’ll explore various techniques for performing prepend on a list data structure.
You’ll have learned how to utilize the .insert() method and prepend two lists by the end of this article. You’ll also discover how to use the deque object to add values to the beginning of a list. It is recommended in many circumstances because it uses substantially less memory than other alternatives.
Let’s get started.
The Ramifications of Prepending a Python List
Lists in Python are mutable container data types, which are changeable. As a result, it can be tempting to add something to a list. This approach, however, can be memory-heavy depending on the size of your list.
It is because there is no “room” at the top of the list. Python must move all other things forward when you move an item to the front of a list. Later in this article, you’ll learn about the deque data structure, which represents a double-ended queue. Items are freely introduced at the beginning or end of these deque objects.
Using the insert() method to prefix a list in Python
One of the most common and widely used techniques is to utilize insert(). The list library provides the insert() method. It is the list. insert(pos, element) takes two arguments as parameters: pos and element. The pos define the element’s location. The following is an example of how to utilize this method:
comp_list =['Apple', 'Microsoft', 'Google'] comp_list .insert (0, "IBM") print(comp_list)
The list.insert() action, on the other hand, takes a little longer. We can use collections to boost our time performance. Next, let’s explore our second example by adding an integer list to our coding project on num_list. The “print” clause turns this list into a string type before printing it. The insert() function is responsibly used to insert the value “324” at the “0” index of this list. The value will be changed back to a string type before being printed on the terminal after being appended to the beginning of a list.
num_list = [ 32, 34, 56, 38, 50, 69, 47, 35, 23, 11] Print ("Before prepend list : " + str(num_list)) num_list.insert(0, 324) Print ("After prepend list : " + str(num_list))
Following the execution of this python code, two lists appear. The first is the list that a user created. The second list has been amended to include the value “324” at the beginning.
Make use of the deque.appendleft()
In Python, use appendleft(), the method to add to a list. Python’s collections module provides a variety of data structures. Deque(), a double-ended queue, was added to the collections in Python 2.4. It’s a container-like list that’s good for appending and pop-up processes. Appendleft(element) is a method in the deque data structure. It takes one element and appends it to the list’s beginning. The following is an example of code for this method:
import collections num_dequeue = collections.deque([15,12,16,18,11,19,20]) print(num_dequeue) num_dequeue.appendleft(21) print(num_dequeue)
Below is another deque() example. Import it into your code and make a “num_list” integer list. The string type is used to print the list. To free up space at the beginning of the list, the deque() function is used. The revised list will then be appended with the value “78” using the “deque” package’s “appendleft()” function. In the end, the new list is printed.
from collection import deque num_list = [ 12, 14, 26, 38, 50] Print ("Num List before prepending to the list : " + str(num_list)) num_list = deque(num_list) num_list.appendleft(78) Print ("Num List after prepending to the list : " + str(num_list))
Create a New List in Python to Prepend to an Existing List
Creating a new list with the desired member, for example, ‘Chrome Book,’ at the 0th index of the list, is a very basic and trivial approach. Of course, you will not append ‘Chrome Book’ to the list; instead, you will build a new list with ‘Chrome Book’ at the top. This method’s foundation code is shown below.
comp_list =['Apple', 'Microsoft', 'Google'] new_list = ['Chrome Book'] + comp_list print (new_list)
Use List Slicing to Prepend a List in Python
List slicing is another way to add items to a list. By assigning the 0th slice to an element, it gets prepended to the list. This method’s example code is as follows:
num_list = [44,45,48,50,43] print(num_list ) num_list [:0] =  print(num_list)
Programmers are familiar with the idea of slicing. An integer list is initially created and printed. The first slice begins at index 0, the second at index 3, the third at index 6, and the fourth at index 9, whereas the last slice starts at index 9. The front element of a list would be omitted on each slice, but the value “35” would be appended. The list has been printed after each new slice.
num_list = [0, 12, 14, 16, 18, 20, 29, 27, 35, 43, 51] Print ("Num List status before prepending to the list : " + str(num_list)) num_list[:0] =  Print ("Num List status after first prepending to the list : " + str(num_list)) num_list[:3] =  Print ("Num List status after second prepending to the list : " + str(num_list)) num_list[:6] =  Print ("Num List status after third prepending list : " + str(num_list)) num_list[:9] =  Print ("Num List status after fourth prepending to the list : " + str(num_list))
Using a List and the Operator +
You’ve probably noticed that the plus sign, sometimes known as the “+” sign, only works with string variables. That’s correct, and we’ll use square brackets and the + sign to append some value to the beginning of a list. As a result, we’ve created an integer-type list. We printed this list after first converting it to a string type. The list is incremented on the next line by attaching the value “45” with the help of square brackets at the beginning. The + sign indicates the concatenation. After being transformed into a string-type list, the revised list is printed out once more.
num_list = [ 12, 44, 36, 18, 10, 56, 87, 65, 93, 31] Print ("Num List status before prepending to the List : " + str(num_list )) num_list =  + num_list #appending at the num_list's beginning Print ("Num List status after prepending to the list : " + str(num_list ))
Example: Prepending a List using Slicing Operation
# list Initialization item_list = ['d',0.9, 3,'g', 47] # Use slicing method to append at beginning item_list[:0] = ['a'] # display the list by printing print(item_list)
Example: Prepending a List using the Insert() function
# list initialization num_list = [18, 22, 9, 45, 67] # using insert() in appending at the lists beginning num_list.insert(0, 63) # display the list by printing print(num_list)
Example: Prepending a List using the ‘+’ operator in Python
# list initialization num_vals = [18, 12, 39, 50, 67] # using the '+' operator to append at beginning num_vals =  + num_vals # display the list by printing print(num_vals)
Example: using the augmented assignment operator to prepend an item to a list
The distinction is that we must reassign to the prefix rather than vice versa. It is exemplified in the following example:
# To prepend an item to a list, use the augmented assignment operator. word_lists = ['Code', 'under', 'Scored'] word_prefix = ['Hi'] word_prefix += word_lists print(word_prefix) # Returns: ['Hi', 'Code', 'under', 'Scored']
This article is written to help any Python user properly grasp the notion of “prepend.” We’ve gone over four different and simple techniques for appending values to the beginning of a list data structure.
The insert method provides a simple technique to move an item to the front of a Python list. There are two parameters to the .insert() method. These include the index position in which the item is inserted and the item to be added. The operation is performed in place, eliminating the need to create a new object.
The + operator in Python is very versatile. When two lists are joined, they are combined in the order in which they appear. It indicates that we can generate a list containing this item when we want to prepend it (or several items). To join the two lists, all we have to do now is use the + operator.
Prepend a Python List Using the List Slicing method can be tricky initially, but it’s an excellent way to move an item to the top of a list. We allocate a single-valued list to another list’s [:0] slice. It makes the item appear before the 0th item in the list.
The deque class is a part of the immensely versatile collections library. This class depicts a double-ended queue, which in other languages is a stack or a queue. It can allow you to prepend things to the left without worrying about the memory consequences of relocating all values.
It’ll be fantastic if you’d practice these concepts more and find new and novel ways to apply them.