The_AlphaCeph
The_AlphaCeph

Reputation: 3

Replace multiple elements in a list with a single element

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

Upvotes: 0

Views: 1370

Answers (1)

hiro protagonist
hiro protagonist

Reputation: 46849

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

Upvotes: 1

Related Questions