Given a list l1 = ['apple', 'pear', 'grapes, 'banana']
How can I remove all items after 'pear'
The remove() method is one of the ways you can remove elements from a list in Python. The remove() method removes an item from a list by its value and not by its index number.
Use the remove() Function to Remove All the Instances of an Element From a List in Python. The remove() function only removes the first occurrence of the element. If you want to remove all the occurrence of an element using the remove() function, you can use a loop either for loop or while loop.
The remove() method, when invoked on a list, takes an element as its input argument. After execution, it removes the first occurrence of the input element from the list. The remove() method doesn't return any value. In other words, it returns None .
use list slice method
>>> l1 = ['apple', 'pear', 'grapes', 'banana']
>>> target_ibdex = l1.index('pear')
>>> target_ibdex
1
>>> l1[:target_ibdex+1]
['apple', 'pear']
>>>
With exception handling when element is not present in the list.
>>> l1 = ['apple', 'pear', 'grapes', 'banana']
>>> target_element = "mango"
>>> try:
... target_index = l1.index(target_element) + 1
... except ValueError, e:
... target_index = None
...
>>> l1[:target_index]
['apple', 'pear', 'grapes', 'banana']
when element present in the list
>>> l1 = ['apple', 'pear', 'grapes', 'banana']
>>> target_element = "pear"
>>> try:
... target_index = l1.index(target_element) + 1
... except ValueError, e:
... target_index = None
...
>>> l1[:target_index]
['apple', 'pear']
You can build a custom generator function which will work on any iterable, not just lists - although for your example, list.index
, exception handling and slicing is fine...
def takewhile_including(iterable, value):
for it in iterable:
yield it
if it == value:
return
l1 = ['apple', 'pear', 'grapes', 'banana']
print('Until pear', list(takewhile_including(l1, 'pear')))
# Until pear ['apple', 'pear']
print('Until blah', list(takewhile_including(l1, 'blah')))
# Until blah ['apple', 'pear', 'grapes', 'banana']
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