List of List- delete characters

Viewed 38

I have a huge list like

list = [["a", "bfgf", "c%2"], ["b", "hhj", "kkkk", "f%2"]]

I want to remove %2 end of every last item in lists of list.

I tried

list = [[item[-1].replace('%2', '') for item in lst] for lst in list]

and it did not work

2 Answers

Your way does not work because you are not changing the value in place. Your statement simply takes a copy of every sub-list, stores it in lst, then changes the data in that copy, and not the actual list itself.

Try it in this way, and tell me if it works.

myList= [["a","bfgf","c%2"],["b","hhj","kkkk","f%2"]]

for i in range(len(myList)):
    Last=myList[i].pop()
    Last=Last.replace("%2","")
    myList[i].append(Last)

print (myList)

For your nested list you can also use a nested list comprehension to remove the unwanted characters.

ini_list = [["a", "bfgf", "c%2"],["b", "hhj", "kkkk", "f%2"]]
ini_list = [[val.replace('%2', '') for val in sublist] for sublist in ini_list]
print(ini_list)
# output
[['a', 'bfgf', 'c'], ['b', 'hhj', 'kkkk', 'f']]
Related