>>> 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.
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.
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) .
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.
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:]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With