Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter elements from the end of a list

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)]
like image 937
user1728853 Avatar asked Dec 27 '22 06:12

user1728853


1 Answers

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]
like image 63
Martijn Pieters Avatar answered Feb 18 '23 05:02

Martijn Pieters