Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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

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

like image 678
canadadry Avatar asked Jan 09 '12 08:01

canadadry


People also ask

How do I add a list in front of a list?

Use the + Operator to Append an Element to the Front of a List in Python. Another approach to append an element to the front of a list is to use the + operator. Using the + operator on two or more lists combines them in the specified order.

How do I add a list to the front in Python?

insert(i, x) function. You can use the list's insert() function that inserts an item at the specified position. To insert an item x at the front of the list l , use l. insert(0, x) .

How do I insert a list into another list?

Use the extend() Method to Append a List Into Another List in Python. Python has a built-in method for lists named extend() that accepts an iterable as a parameter and adds it into the last position of the current iterable. Using it for lists will append the list parameter after the last element of the main list.


1 Answers

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:] 
like image 121
Sufian Latif Avatar answered Sep 19 '22 15:09

Sufian Latif