I wrote this function to filter a list to show all items after a given item is seen. Somewhat similar to the builtin string method str.rpartition(sep). I have a feeling there is a more compact way to do this, perhaps using a list comprehension. Any ideas?
def ignore_until(the_list, match):
# Ignore all items in the_list prior to match
found = False
for index, item in enumerate(the_list):
if item == match:
found = True
break
if found:
return the_list[index:]
else:
return []
my_list = ['red','orange','yellow','green']
assert ignore_until(my_list, 'yellow') == ['yellow','green']
assert ignore_until(my_list, 'blue') == []
EDIT:
After seeing the answers for the above question, I realized that 5 of the 6 answers focused on the index() builtin method for the list data type. Actually, I need to use a regular expression, and didn’t realize that omitting that from my question would affect people’s answers. Here’s the regex code:
import re
def ignore_until(the_list, pattern):
# Ignore all items in the_list prior to the item containing pattern.
found = False
for index, item in enumerate(the_list):
if re.search(string=item, pattern=pattern):
found = True
break
if found:
return the_list[index:]
else:
return []
my_list = ['red','orange','yellow','green']
assert ignore_until(my_list, 'yellow') == ['yellow','green']
assert ignore_until(my_list, 'blue') == []
Here’s a version that reproduces what str.partition does (i.e. returns three lists):
and here’s a version which works with arbitrary iterables, not necessary lists:
Improved version: