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

Replace an item in a list

I have a list which will add random items in any order. I am looking for a way to replace an item with another item & at the same time keep the same index position, without knowing which index position it will originally be in.

So for example randomly generated list: hand = ["A", 3]. I want to remove/replace "A"
Regardless if "A" was in Index 0 or 1 & when I re-add "A" it will be in the same index position.

And if in the event hand = ["A", 3, "A"]. I only want the first "A" to be removed/replaced.

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

one = ["A", 3, "A"]

if "A" in one[:2]:
    A = 11
    one.remove("A")
    one.append(A)

if "A" in one[2:]:
    a = 1
    one.remove("A")
    one.append(a)

What I’ve tried so far but this removes an item and adds it to the end of the list. This is the type of concept I am looking for

# Randomly generated list
hand = ["A", 3, "A"]
# Convert string to var(Numbers)
hand = [11, 3, 1]
one = sum(hand) 
# Convert hand back to list
hand = ["A", 3, "A"]

>Solution :

To replace all ‘A’s with a new item:

new_item = 'whatever'
hand = ["A", 3, "A"]
hand = [new_item if x == 'A' else x for x in hand]
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