Here are five ways to prepend to a list in Python:
- Using insert() Method
- Using list slicing
- Using the + operator
- Using list unpacking
- Using collections.deque.appendleft()
Prepending an item to a list means adding the item at the beginning of the list.
Method 1: Using insert() Method
The list.insert() method allows you to insert an item at any position in the list. To prepend, insert at position 0.
Visual Representation
Example
# Define a list with some elements
sample_list = [6, 9, 12, 15]
print("Before Prepending:", sample_list)
# The insert() method adds '3' at the index 0
sample_list.insert(0, 3)
print("After Prepending:", sample_list)
Output
Before Preprending: [6, 9, 12, 15]
After Preprending: [3, 6, 9, 12, 15]
Method 2: Using list slicing
The slice [:0] specifies the position before the first element of the list. By assigning [3] to this slice, you are effectively inserting 3 at the start of the list.
Visual Representation
Example
# Define a list with some elements
sample_list = [6, 9, 12, 15]
print("Before Prepending:", sample_list)
sample_list[:0] = [3] # Prepend 3 to the list
print("After Prepending:", sample_list)
Output
Before Prepending: [6, 9, 12, 15]
After Prepending: [3, 6, 9, 12, 15]
Method 3: Using the + operator
You can use square brackets [] and the + operator to create a new list with the item and concatenate it with the original list.
Visual Representation
Example
# Define a list with some elements
sample_list = [6, 9, 12, 15]
print("Before Prepending:", sample_list)
my_list = [3] + sample_list
print("After Prepending:", my_list)
Output
Before Prepending: [6, 9, 12, 15]
After Prepending: [3, 6, 9, 12, 15]
Method 4: Using list unpacking
The * operator(works well in Python 3.5 and later) unpacks the elements of the list and prepends the item 3 to the existing list.
Visual Representation
Example
# Define a list with some elements
sample_list = [6, 9, 12, 15]
print("Before Prepending:", sample_list)
sample_list = [3, *sample_list]
print("After Prepending:", sample_list)
Output
Before Prepending: [6, 9, 12, 15]
After Prepending: [3, 6, 9, 12, 15]
Method 5: Using collections.deque.appendleft() function
For very large lists, consider using collections.deque for efficient appends and prepends.
The appendleft() function can perform the push-like operation from the front of the double-ended queue.
Example
# Define a list with some elements
from collections import deque
sample_list = deque([6, 9, 12, 15])
print("Before Prepending:", sample_list)
sample_list.appendleft(3)
print("After Prepending:", sample_list)
Output
Before Prepending: deque([6, 9, 12, 15])
After Prepending: deque([3, 6, 9, 12, 15])