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)]
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With