How to Prepend a Value to a Python List?

Find out how you can prepend a value to a list in Python

In Python, you can prepend a value to an existing list by using the list.insert() method, for example, like so:

l = ['bar', 'baz']
l.insert(0, 'foo')

print(l) # ['foo', 'bar', 'baz']

This would do in-place modification of the list (as opposed to returning a new one) — which means that it would mutate/modify the original list.

You can shorten this by using slice assignment (list[start:stop] = [value]), for example, like so:

l = ['bar', 'baz']
l[0:0] = ['foo']

print(l) # ['foo', 'bar', 'baz']

This is the known as the extended indexing syntax — where specifying [0:0] as both, the start and stop values to the slice operator, prepends the value (e.g. ['foo']) to the list. The 0 on the left side, however, can also be omitted in this case:

l = ['bar', 'baz']
l[:0] = ['foo']

print(l) # ['foo', 'bar', 'baz']

This is similar to using the slice function (slice(start, stop)):

l = ['bar', 'baz']
l[slice(0, 0)] = ['foo']

print(l) # ['foo', 'bar', 'baz']

If prepending to a list is costing you performance-wise, then perhaps you should consider using a deque instead (as lists are not the most optimal for prepending values). In terms of time complexity, prepending to a list is an O(n) operation, as opposed to O(1) with deque.


Hope you found this post useful. It was published . Please show your love and support by sharing this post.