Search code examples
pythonlistinsert

Look for item inside list, when found, inside same item before it. (python)


inside a list I'm looking for the item '-', when we find it, I want to insert '-' before it. Should be pretty easy but I'm struggling :S


Solution

  • Use the list.insert and list.index methods. index gives you the index of the item you're looking for, insert does what it says it does:

    l = ['a', 1, '-', 2] # random list
    l.insert(l.index('-'), '-')
    print(l)
    

    Reacting to your comment: If you have more than one occurence, it works a bit less elegantly:

    l = ["a", 1, "-", 2, "-", 2, 5, "-"]
    # get indices of '-'
    idxs = [i for i, c in enumerate(l) if c == "-"]
    # loop over indices and insert, account for already added items
    for i, idx in enumerate(idxs):
        l.insert(idx + i, "-")