0

How to replace a element in list of list using python3?

txt =[[""],[""],[""]]
for i in txt:
   x = i.replace("", "apples")
   print(x)

Expected Output:

apples
apples
apples
3
  • 2
    Possible duplicate of Replace values in list using Python Commented Apr 8, 2019 at 6:06
  • i am asking for list of list Commented Apr 8, 2019 at 6:08
  • You can just use an answer from the question I have linked and apply it to all elements in your list. Commented Apr 8, 2019 at 6:09

4 Answers 4

1

To replace every instance of "" in the sublists of the main list txt, you can use the following list-comprehension:

txt =[[""],[""],[""]]
txt = [[x if not x=="" else 'apples' for x in sublist] for sublist in txt]

which produces:

[['apples'], ['apples'], ['apples']]

The code you have right now cannot work because given the way you loop over txt, i is the sublist and you python list objects do not have a .replace method.

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

Comments

0
def replace(value, new_value, outer_list):    
  for inner_list in outer_list:
    for i,element in enumerate(inner_list):
       if element == value:
          inner_list[i]= new_value
  return outer_list
txt =[[""],[""],[""]]
txt = replace("", "apple", txt)

This function could do your need

Comments

0

Try this one:

txt = [[""],[""],[""]]
for i in range(len(txt)):
    for ii in range(len(txt[i])):
        txt[i][ii] = (txt[i][ii]).replace("","apples")
print(txt)

Comments

0

Using list comprehension:

txt =[[""],[""],[""]]

print([[x if x != "" else 'apples' for x in sub] for sub in txt])

OUTPUT:

[['apples'], ['apples'], ['apples']]

To print them separately;

txt = [[x if x != "" else 'apples' for x in sub] for sub in txt]

for sub in txt:
   for elem in sub:
      print(elem)

OUTPUT:

apples
apples
apples

Comments

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.