0

Consider the following list:

data = ['A', 'B', 'CAT', 'C', 'CAT', 'CAT', 'CAT']

The CATs 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 CATs is unknown and there may or may not be some CATs 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.

aneroid
  • 12,983
  • 3
  • 36
  • 66

1 Answers1

3

How about:

while len(data) > 1 and data[-1] == data[-2]:
  data.pop()

This trims trailing duplicates of any kind. If you specifically want to only trim 'CAT', it's easy to adapt the code to do that.

NPE
  • 486,780
  • 108
  • 951
  • 1,012