Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove all elements from a list after a particular value

Tags:

Given a list l1 = ['apple', 'pear', 'grapes, 'banana']

How can I remove all items after 'pear'

like image 429
ustroetz Avatar asked Jan 27 '15 11:01

ustroetz


People also ask

How do you remove an element from a list based on value?

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.

How do you remove all the occurrences of a particular element in a list?

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.

Does the remove method remove all occurrences of an item from a list?

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 .


2 Answers

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']
like image 72
Vivek Sable Avatar answered Sep 28 '22 09:09

Vivek Sable


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']
like image 24
Jon Clements Avatar answered Sep 28 '22 10:09

Jon Clements