[Python] How to remove the last occurrence of an item from a list?

Discussão em 'Python' iniciado por Stack, Março 1, 2025.

  1. Stack

    Stack Membro Participativo

    The list.remove() function serves to remove the first time an item appears in a list. Is there a built-in function to remove the last time? For instance if I have a list, say:

    X = ['sf', 'cc', 'ch', 'sc', 'sh', 'ch']


    and I want to remove the last 'ch' from the list, is there a better method than what I'm currently doing, which is:

    X.reverse()
    X.remove('ch')
    X.reverse()


    I will soon also have to worry about cases where the item being removed is potentially not in the list. So methods that do not throw errors in this case would be preferred.

    Continue reading...

Compartilhe esta Página