pythoncoder
pythoncoder

Reputation: 675

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

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

Upvotes: 0

Views: 122

Answers (4)

DirtyBit
DirtyBit

Reputation: 16772

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

Upvotes: 0

YusufUMS
YusufUMS

Reputation: 1493

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)

Upvotes: 0

kathir raja
kathir raja

Reputation: 1016

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

Upvotes: 0

Ma0
Ma0

Reputation: 15204

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.

Upvotes: 1

Related Questions