How do I insert a list at the front of another list?


>>> a = ['']
>>> k = ['nice', '-n', '10'] 
>>> a.insert(0, k)
>>> a
[['nice', '-n', '10'], '']

I want to list k to be on the same level as, rather than a sublist.

Asked By: canadadry



Apply slicing:

a[0:0] = k

Or do it manually:

a = k + a

The first approach remain the same for insertion at any place, i.e. a[n:n] = k
would insert k at position n, but the second approach would not be the same, that will be

a = a[:n] + k + a[n:]
Answered By: Sufian Latif
>>> k + a
['nice', '-n', '10', '']
Answered By: dhg

Use list concatenation:

a = k + a
Answered By: David Robinson

instead of:

>>> a.insert(0, k)


>>> k.extend(a)
>>> k
['nice', '-n', '10', '']

this updates the “k” list “in place” instead of creating a copy.

the list concatenation (k + a) will create a copy.

the slicing option (a[0:0] = k) will also update “in place” but IMHO is harder to read.

Answered By: Paulo Scardine
>>> a = ['']
>>> k = ['nice', '-n', '10']
>>> k.extend(a)
>>> print k
['nice', '-n', '10', '']
Answered By: thavan
    list1=list(xrange(1,11)) # numbers 1 to 10 in list
    list1[:0]=[0,0,0] # adds triple 0s to front of list
    list1+=[11,12,13] #adds [11,12,13] to the end of list
    print list1
Answered By: Stefan Gruenwald
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.