Using Python, I’m trying to read a list or strings backwards. When finding the item of interest, I want to print all of those items from that point to the end of the list. I can do this without recursion and it works fine, but I feel like there’s a nicer way to do this with recursion. 🙂
Example without recursion:
items = ['item1', 'item2', 'item3', 'item4', 'item5']
items_of_interest = []
items.reverse()
for item in items:
items_of_interest.append(item)
if item == 'item3':
break
else:
continue
items_of_interest.reverse()
print items_of_interest
['item3', 'item4', 'item5']
Update:
To add clarity to the question, the list is actually the output of a grep of a set of strings from a log file. The set of strings may be repeating and I only want the last set.
Recursion wouldn’t make this simpler, it would make it more complicated.
seems to be the simplest efficient way to do this to me. You only have to iterate over the list from the end to
'item3', sincereversedreturns an iterator.Edit: if you don’t mind iterating over the whole list to create a reversed version, you can use:
which is even simpler. It raises an error if
'item3'isn’t in the list. I’m usinglist(reversed())instead of[:]thenreverse()because it’s one iteration over the list instead of two.Edit 2: Based on your comment to the other answer, my first version does what you want — searches for the item from the end without iterating over the whole list. The version in the question has to iterate the list to reverse it, as does my second version.
A minimally modified, but more efficient, version of your original would be: