1

for suppose if I have a list of unique elements,

list = [.......,'a','b','c',.....]

How to replace 'a','b' with 'd' such that it results,

list = [.....,'d','c'.....] 

without any loops.

I have tried doing this, but it's not working.

list[list.index('a'):list.index('b')] = 'd'

2 Answers 2

2

A slice l[start:stop] does not include the element at the stop position.

Your code is almost correct, you only need to add 1 to list.index('b'):

In [14]: l = ['a', 'b', 'c', 'e']

In [15]: l[l.index('a'):l.index('b') + 1] = 'd',

In [16]: l
Out[16]: ['d', 'c', 'e']

Also: try to avoid using names of built-in functions and types as variable names.

Sign up to request clarification or add additional context in comments.

Comments

0

You can first join the list, then use replace:

l = ["a", "d", "c", "a", "b", "c", "e"] #example list
new_list = list(''.join(l).replace("abc", "dc"))

Output:

['a', 'd', 'c', 'd', 'c', 'e']

2 Comments

This works for one-character strings, but will it work for multi-character strings and non-string objects?
@vaultah since the OP specifically used single-character strings in his example and even posted is desired output in the same manner, I tailored my solution for single-character strings only.

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.