0

I have a list containing many alphabets, and I want to replace a random "a" with "b", how can I do it?

alphabets = ["a", "c", "a", "a", "b", "c"]

Examples of wanted output:

["a", "c", "a", "b", "b", "c"]
["b", "c", "a", "a", "b", "c"]
["a", "c", "b", "a", "b", "c"]

1 Answer 1

3

I assume that alphabets always has an 'a' and that you always want to change exactly one 'a' to a 'b' at random.

from random import randint

alphabets = ["a", "c", "a", "a", "b", "c"]

# get indices in alphabets associated with the value "a"
indices = [i for i, x in enumerate(alphabets) if x == 'a']

print(f"{'Before':6}: {alphabets}")

# randomly change one of the "a"s to a "b" 
alphabets[indices[randint(0, len(indices) - 1)]] = "b"

print(f"{'After':6}: {alphabets}")

Example output:

Before: ['a', 'c', 'a', 'a', 'b', 'c']
After : ['b', 'c', 'a', 'a', 'b', 'c']
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.