Consider the following list:
data = ['A', 'B', 'CAT', 'C', 'CAT', 'CAT', 'CAT']
The CAT
s at the end of the list must be reduced from three to one. There is a CAT
inside the list (after B
) that shouldn't be removed. What is a good way of doing this? The number of trailing CAT
s is unknown and there may or may not be some CAT
s inside the list. So the desired output is:
data = ['A', 'B', 'CAT', 'C', 'CAT']
One way I thought of was:
count = 0
for i in reversed(data):
if i == 'CAT':
count += 1
else:
break
if count > 1:
del data[-count:]
It is quite lengthy for achieving a somewhat smaller task.