list.append()
is the obvious choice for adding to the end of a list. Here's a reasonable explanation for the missing list.prepend()
. Assuming my list is short and performance concerns are negligible, is
list.insert(0, x)
or
list[0:0] = [x]
idiomatic?
While Python has a method to append values to the end of a list, there is no prepend method. By the end of this tutorial, you'll have learned how to use the . insert() method and how to concatenate two lists to prepend. You'll also learn how to use the deque object to insert values at the front of a list.
Solution: Use the list. insert(0, x) element to insert the element x at the first position 0 in the list.
The s.insert(0, x)
form is the most common.
Whenever you see it though, it may be time to consider using a collections.deque instead of a list. Prepending to a deque runs in constant time. Prepending to a list runs in linear time.
If you can go the functional way, the following is pretty clear
new_list = [x] + your_list
Of course you haven't inserted x
into your_list
, rather you have created a new list with x
preprended to it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With