1

How can i replace a string in list of lists in python but i want to apply the changes only to the specific index and not affecting the other index, here some example:

mylist = [["test_one", "test_two"], ["test_one", "test_two"]]

i want to change the word "test" to "my" so the result would be only affecting the second index:

mylist = [["test_one", "my_two"], ["test_one", "my_two"]]

I can figure out how to change both of list but i can't figure out what I'm supposed to do if only change one specific index.

asked Mar 2, 2020 at 3:39
1
  • how about tuple in list ? it won't accept reassigning the value? Commented Mar 2, 2020 at 3:51

2 Answers 2

3

Use indexing:

newlist = []
for l in mylist:
 l[1] = l[1].replace("test", "my")
 newlist.append(l)
print(newlist)

Or oneliner if you always have two elements in the sublist:

newlist = [[i, j.replace("test", "my")] for i, j in mylist]
print(newlist)

Output:

[['test_one', 'my_two'], ['test_one', 'my_two']]
answered Mar 2, 2020 at 3:43
Sign up to request clarification or add additional context in comments.

Comments

2

There is a way to do this on one line but it is not coming to me at the moment. Here is how to do it in two lines.

for two_word_list in mylist:
 two_word_list[1] = two_word_list.replace("test", "my")
answered Mar 2, 2020 at 3:43

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.