Append integer to beginning of list in Python

gen picture gen · Jul 28, 2013 · Viewed 770.9k times · Source

I have an integer and a list. I would like to make a new list of them beginning with the variable and ending with the list. Writing a + list I get errors. The compiler handles a as integer, thus I cannot use append, or extend either. How would you do this?

Answer

Nullify picture Nullify · Jul 28, 2013
>>>var=7
>>>array = [1,2,3,4,5,6]
>>>array.insert(0,var)
>>>array
[7, 1, 2, 3, 4, 5, 6]

How it works:

array.insert(index, value)

Insert an item at a given position. The first argument is the index of the element before which to insert, so array.insert(0, x) inserts at the front of the list, and array.insert(len(array), x) is equivalent to array.append(x).Negative values are treated as being relative to the end of the array.