Explain Codes LogoExplain Codes Logo

Append integer to beginning of list in Python

python
list-manipulation
performance
best-practices
Nikita BarsukovbyNikita Barsukov·Sep 19, 2024
TLDR
Prepend an integer using the `insert` method or with list concatenation:

```python
my_list.insert(0, integer_to_add)  # Prepends in-place. Like queue-jumping in a list!
my_list = [integer_to_add] + my_list  # New list where integer leads the parade

Example:

my_list = [2, 3, 4] my_list.insert(0, 1) # Result: [1, 2, 3, 4]

OR

my_list = [1] + my_list # Result: [1, 2, 3, 4]

Choosing the right tool for the job

Knowing the right tool to use when prepending an element in a list can save you significant time and resources.

Using insert to prepend single items

The insert function is your best friend when you want to prepend a single element. It's as if the item has a VIP pass granting it immediate access to the front of the list.

my_list.insert(0, integer_to_add)

But bear in mind that this might not work so well if you're frequently adding items to the start of the list.

Adding to the start with list concatenation

Using list concatenation to prepend an item is as easy as sending an email with an attachment.

my_list = [integer_to_add] + my_list # New list with the prepended item.

This does create a new list though, so it might not be the best option if you're counting your memory pennies.

When deque beats list

This is where Python's double-ended queue deque comes in, especially if you're frequently appending items to both ends of your list.

from collections import deque my_deque = deque([2, 3, 4]) my_deque.appendleft(1) # Result: deque([1, 2, 3, 4])

This switch could be the best thing since sliced bread for your performance-critical application.

Advanced unpacking for list merging

Lastly, Python's unpacking feature with * could be your secret sauce for merging lists.

my_list = [1, *my_list] # Advanced. Use with caution, like a chef's knife.

This is the code equivalent of putting extra cheese on your pizza. It improves readability and it's oh so satisfying to use.

Dodging the pitfalls

There are a few common pitfalls when dealing with lists. Let's figure out how to avoid stepping in them.

Avoiding bad variable names

Naming a list list is like naming your dog Dog. It's possible, but it can lead to confusion.

numbers = [2, 3, 4] # Better

Beware of the negative indexing

list.insert supports negative indexing, but -1 will add the element second from the last, not the start.

my_list.insert(-1, integer_to_add) # Add it second to last, like stepping in at the last moment.

Slice for the win

If you want to prepend, but in a cooler way, use a slice.

my_list[0:0] = [integer_to_add] # Like adding a page to the start of a book.

This is like handing out free cookies, everyone will love your style for this.