I want to replace two or more elements with a single element in a list like this:
mylist=['a','b','c']
Now I want to replace 'a' and 'b' elements with another element 'z'. So output should be:
['z','z','c']
a list-comprehension an option:
mylist = ['a', 'b', 'c']
new_list = [x if x not in "ab" else "z" for x in mylist]
print(new_list) # ['z', 'z', 'c']
if the elements you want to replace are more complicated you could try:
if x not in {"a", "b"}
if you want to change things based on the index i you can use enumerate:
new_list = [x if i >= 2 else "z" for i, x in enumerate(mylist)]
print(new_list) # ['z', 'z', 'c']
but then you could consider slicing:
new_list = 2 * ["z"] + mylist[2:]
if i >= 2 part much because what if the list is bigger? Let's say it contains 10 elements and i want to replace first, third, and seventh element for example? I can't do that this way. Do you know any other solutions?
["z" if x in ("a", "b") else x for x in mylist]