user17773050
user17773050

Reputation:

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.

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"]

Upvotes: 1

Views: 6121

Answers (3)

LukasNeugebauer
LukasNeugebauer

Reputation: 1337

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]

Upvotes: 2

Stijn B
Stijn B

Reputation: 360

You can do this :

if 'A' in hand:
    hand[hand.index('A')] = <replacement>

Upvotes: 0

Ashin Shakya
Ashin Shakya

Reputation: 776

Try this.

a = ["A", 3, "A"]
try:
    # Replace first occurrence of A with B
    a[a.index("A")] = "B"
except ValueError:
    pass
print(a)

Upvotes: 0

Related Questions