Explain Codes LogoExplain Codes Logo

How do I prepend to a short python list?

python
performance
best-practices
collections
Alex KataevbyAlex Kataev·Jan 1, 2025
TLDR

To prepend to a Python list, use either .insert(0, value) or [value] + list. The first method modifies the list in-place, while the second creates a new list.

.insert():

my_list = [1, 2, 3] my_list.insert(0, 0) # No magic. Just prepending. Now my_list is [0, 1, 2, 3]

Concatenation:

my_list = [1, 2, 3] my_list = [0] + my_list # Presto! New list created with [0, 1, 2, 3]

Opt for .insert() if you desire direct modification, or use concatenation to create a new list with the element prepended.

Going beyond vanilla prepending

While .insert(0, value) is a classic method, let’s dig into the performance implications. If you're operating with short lists, .insert() will be efficient. However, for longer lists, consider opting for collections.deque.

Using deque for high performance:

from collections import deque d = deque([1, 2, 3]) d.appendleft(0) # deque([0, 1, 2, 3]). Faster than a cheetah!

.extendleft() with iterables:

from collections import deque d = deque([1, 2, 3]) d.extendleft([0, -1, -2]) # deque([-2, -1, 0, 1, 2, 3]). No sweat!

Slice assignment for a zippy addition:

my_list = [1, 2, 3] my_list[:0] = [0] # Just like new shoes. Feels great!

If reversing the list suits you, do it and use .append() for improved performance. Finally, the * operator can come in handy when needing to prepend multiple items:

my_list = [1, 2, 3] my_list = [-1, 0, *my_list] # [-1, 0, 1, 2, 3]. It’s like magic, but not!

Prepending alternatives and their trade-offs

Prepending isn't a native list operation in Python, hence we need to get creative. Be cognizant: multiple prepending operations can be costly, especially if your "short" list is at risk of growing large.

Concatenating vs modifying the original list:

Concatenation using + prevents changes to the original list, perfect when originality is a necessity.

Avoiding magic numbers and adding clarity with variables:

Using a variable instead of directly inserting at the 0 index can enhance both intent clarity and code readability.

Choosing the right tool for the job:

Opt for the method that aligns with your specific scenario — list size and operation frequency. deque shines for frequent updates, while insert() and concatenation excel for few changes.

Optimizing prepending process

Performance concerns are often dismissed when dealing with small lists. But as lists grow, deque comes into the limelight due to its efficiency with large lists. It's optimized for quick operations at either end — a beast of efficiency.

Deque in practice:

As your list size increases, or if you start performing multiple prepends, deque is your trusted guide to maintaining optimal speed and efficiency.

Critical practices and looming pitfalls

Certain best practices safeguard efficiency, while some pitfalls threaten to ruin your day when prepending to a list:

  • Performance testing: Carry out benchmarks if dealing with lists of varying sizes.
  • Need Analysis: For a one-time prepend, performance concerns are moot. But frequent updates demand efficiency.
  • Code legibility: As code is read more often than written, prioritize clarity over conciseness.
  • Ready for change: If your "short" list might grow, plan for scalability.