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

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?

7 s
7

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.

Leave a Comment