What's the idiomatic syntax for prepending to a short python list?


Question

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?

1
465
12/16/2011 5:30:01 PM

Accepted Answer

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.

671
12/16/2011 6:08:26 PM

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.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon