[Solved] Replace list object based on indexes of another list (Python)


You can get all of the indices whose value is x using a list comprehension:

indices = [i for i, elem in enumerate(word) if elem == x]

So you would have:

>>> word = ["p", "y", "t", "h", "o", "n"]
status = ["_", "_", "_", "_", "_", "_"]
>>> >>> word
['p', 'y', 't', 'h', 'o', 'n']
>>> status
['_', '_', '_', '_', '_', '_']

Then, the user makes a guess, say we have guess="t", then:

>>> guess="t"
>>> indices = [i for i, x in enumerate(word) if x == guess]
>>> indices
[2]

Then we mutate the status list to show the indices that were found:

for i in indices:
    status[i] = guess

We can then display status as a string:

print(' '.join(status))
_ _ t _ _ _

1

solved Replace list object based on indexes of another list (Python)