2

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'

Szeverin
  • 41
  • 3
  • 1
    You should use Google before go to StackOverflow. There are bunch of tutorial about this that will be easier to understand than what we can answer here. – BrainFl Mar 29 '22 at 11:36
  • I didn't find.. – Szeverin Mar 29 '22 at 11:38
  • Read [ask] and don't expect us to google this for you. – baduker Mar 29 '22 at 11:39
  • Does this answer your question? [Insert an element at a specific index in a list and return the updated list](https://stackoverflow.com/questions/14895599/insert-an-element-at-a-specific-index-in-a-list-and-return-the-updated-list) – BrainFl Mar 29 '22 at 11:40
  • if not by index, then how? always same place, always last, 1st? please be precise – Ren Mar 29 '22 at 11:40
  • look.. I know append extend and insert My qustation is how to insert an item by value because insert addt value by index – Szeverin Mar 29 '22 at 11:41
  • I think SO is more for specific questions for specific people, not just general questions. Also, make sure to search things up before asking about them because there might be an answer to your problem already. – KingTasaz Mar 29 '22 at 11:41
  • If you can't use index, you can't do it (unless you want to place it at the last place). – BrainFl Mar 29 '22 at 11:42
  • what do you mean by "value" alphabetic order of the string? other value? – Ren Mar 29 '22 at 11:43

3 Answers3

1

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")
Raida
  • 1,206
  • 5
  • 17
  • 1
    You shouldn't name a list to `list` because it the next time you want to convert a tuple to a list, it might think the `list` is `[ 'apple', 'peach', 'orange']` – BrainFl Mar 29 '22 at 11:44
  • Yes right, I modify it. I took the name used by the author. – Raida Mar 29 '22 at 11:45
1

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')
Lev M.
  • 6,088
  • 1
  • 10
  • 23
0

it is better to rename list

list1 = [ 'apple', 'peach', 'orange']
list1.insert(2,'banana')
print(list1)
leonardik
  • 131
  • 6
  • 2
    @Szeverin wants to insert by specifying the value, not the index. – Raida Mar 29 '22 at 11:43
  • 1
    I said not by index.. I have to got the value which is 'orange'. I have to use orange and not 2 what is an index. Can't explain better – Szeverin Mar 29 '22 at 11:44