How do I insert element to a list not by index in Python?

Viewed 45

I want to insert new element into a list by value and not by index. like:

list = [ 'apple', 'peach', 'orange']

I want to insert 'banana' before 'orange'

3 Answers

A possible function is

def insert_before(l, b, v):
    l.insert(l.index(b), v)

Then use it like this

l = [ 'apple', 'peach', 'orange']
insert_before(l, "orange", "banana")

There is no single command to do this.

You need to first find the index of the item before which you want to insert, like so:

lst = [ 'apple', 'peach', 'orange']

try:
    before = lst.index('organge')
except ValueError: #no banana in the list
    lst.append('orange')

Then insert it by the index you found:

lst.insert(before, 'banana')

it is better to rename list

list1 = [ 'apple', 'peach', 'orange']
list1.insert(2,'banana')
print(list1)
Related