You could go a simpler and much shorter way using a dict and list the understanding as follows:
colors = ['red', 'blue', 'yellow', 'orange'] # First define you replaces replaces = { 'red': 'ping', 'blue': 'light blue', 'yellow': 'amarillo', 'purple': 'lavender' } # Then define the replacing function def replace(key, replaces): return replaces.get(key) or key # And then replace all the intended element colors = [replace(el, replaces) for el in colors]
So, what will this do, for each element, it will look for it in the dict, if it is in the dict (i.e. intended for replacement), then it will return the corresponding replacement, otherwise it will return to its original value.
So, by entering your conditions, you can do the following:
if 'purple' in colors and 'red' in colors: colors = [replace(el, { 'yellow': 'amarillo', 'purple': 'lavender' }) for el in colors] ...
And the same for any other conditions.
source share