0

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']
1
  • ["z" if x in ("a", "b") else x for x in mylist] Commented Mar 11, 2020 at 12:45

1 Answer 1

1

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:]
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you, this works but i was wondering if there was a method to use indices of the list. Like mylist[0] and mylist[1] to replace 'a' and 'b'. Sorry if I wasn't clear.
Yes but I don't like the 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?
Thanks I feel dumb

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.