Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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, "-")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading