patternpythonCriticalCanonical
Append integer to beginning of list in Python
Viewed 0 times
integerappendlistbeginningpython
Problem
How do I prepend an integer to the beginning of a list?
[1, 2, 3] ⟶ [42, 1, 2, 3]Solution
>>> x = 42
>>> xs = [1, 2, 3]
>>> xs.insert(0, x)
>>> xs
[42, 1, 2, 3]How it works:
list.insert(index, value)Insert an item at a given position. The first argument is the index of the element before which to insert, so
xs.insert(0, x) inserts at the front of the list, and xs.insert(len(xs), x) is equivalent to xs.append(x). Negative values are treated as being relative to the end of the list.Code Snippets
>>> x = 42
>>> xs = [1, 2, 3]
>>> xs.insert(0, x)
>>> xs
[42, 1, 2, 3]Context
Stack Overflow Q#17911091, score: 1323
Revisions (0)
No revisions yet.