Append integer to beginning of list in Python
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:
OR
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.
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.
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.
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.
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.
Beware of the negative indexing
list.insert
supports negative indexing, but -1 will add the element second from the last, not the start.
Slice for the win
If you want to prepend, but in a cooler way, use a slice.
This is like handing out free cookies, everyone will love your style for this.
Was this article helpful?