Alex Rivera | Logout

How do I prepend to a short python list?

Asked 2011-12-16T17:30:01.267
821

list.append() appends to the end of a list. This explains that list.prepend() does not exist due to performance concerns for large lists. For a short list, how do I prepend a value?

Edit
Report

1 Answer

1139

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.

answered 2011-12-16T18:08:26.647

Your Answer