Filter elements from the end of a list

filter, list, python

Solution

This sounds to me like you want a '`rstrip()` for lists'. You can use `.pop()` with a while loop:

while somelist and somelist[-1][1] == 0:
    somelist.pop()

This alters the list in place.

To create a copy, you'd have to first find a slice end-point, then slice up to that point for a quick copy:

end = len(somelist)
while end and somelist[end - 1][1] == 0:
    end -= 1
newlist = somelist[:end]

Problem

I have a data structure that looks like this: ``` [(1, 2), (2, 3), (4, 0), (5, 10), (6, 0), (7, 0)] ``` What is the best way to filter out only tuples at the end of the list where the second element is 0? The desired output is: ``` [(1, 2), (2, 3), (4, 0), (5, 10)] ```

Original source