HiveBrain v1.2.0
Get Started
← Back to all entries
snippetpythonCritical

How do I prepend to a short python list?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
howlistpythonshortprepend

Problem

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?

Solution

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.

Context

Stack Overflow Q#8537916, score: 1139

Revisions (0)

No revisions yet.