'Python replace random specific element in list

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


Solution 1:[1]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1