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
pythoncoder
  • 575
  • 3
  • 8
  • 17

4 Answers4

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.

Ma0
  • 15,057
  • 4
  • 35
  • 65
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

kathir raja
  • 640
  • 8
  • 19
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)
YusufUMS
  • 1,506
  • 1
  • 12
  • 24
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
DirtyBit
  • 16,613
  • 4
  • 34
  • 55