Append to the Beginning of a List in Python
You can append items to the beginning of a list in Python using several methods:
(1) Using insert()
The insert()
method allows you to insert an element at a specified index in a list.
To append an item to the beginning of a list, you can use an index 0
.
For example:
my_list = [5, 10, 15, 20]
my_list.insert(0, 99)
print(my_list) # Output: [99, 5, 10, 15, 20]
(2) Using list concatenation
You can prepend a single-element list with the original list using list concatenation.
For example:
my_list = [5, 10, 15, 20]
my_list = [99] + my_list
print(my_list) # Output: [99, 5, 10, 15, 20]
You can prepend a list with multiple elements with the original list using list concatenation.
my_list = [5, 10, 15, 20]
my_list = [99, 88, 77] + my_list
print(my_list) # Output: [99, 88, 77, 5, 10, 15, 20]
(3) Using slicing
In Python, slicing extracts a portion of a sequence (like a list, tuple, or set).
Slicing can also be used to insert items at specific positions, including at the front of the list.
For example:
my_list = [5, 10, 15, 20]
my_list[:0] = [99]
print(my_list) # Output: [99, 5, 10, 15, 20]
In the above example, my_list[:0]
represents the slice at the beginning of the list, effectively an empty slice before the first element.
Assigning [99]
to my_list[:0]
inserts the value 99
at the start of the list.
You can use slicing to append multiple elements to the beginning of the list.
my_list = [5, 10, 15, 20]
my_list[:0] = [99, 88, 77]
print(my_list) # Output: [99, 88, 77, 5, 10, 15, 20]
(4) Using list unpacking
List unpacking in Python allows you to assign the elements of a list to individual variables in a single line of code.
You can use list unpacking to prepend an item to a list by creating a new list with the desired item and unpacking the original list into it.
For example:
my_list = [5, 10, 15, 20]
# Append 99 to the beginning of the list
my_list = [99, *my_list]
print(my_list) # Output: [99, 5, 10, 15, 20]
# You can also preprend multiple items
my_list = [77, 88, *my_list]
print(my_list) # Output: [77, 88, 99, 5, 10, 15, 20]
(5) Using collections.deque.appendleft()
If you need to prepend elements frequently, consider using deque
(double-ended queue) from the collections
module.
For example:
from collections import deque
my_deque = deque([5, 10, 15, 20])
my_deque.appendleft(99)
print(my_deque) # Output: deque([99, 5, 10, 15, 20])
Choosing the right method
Use insert()
if you only need to insert a single element at the beginning of a list occasionally.
Use deque
if you frequently append a single element at the beginning of a list. It is much faster than other methods.
Consider slicing, list concatenation, or list unpacking if you need to append multiple elements at the beginning of the list.
Consider list concatenation or unpacking if you need a new list instead of modifying the original list.