How to remove element of list based on condition in the sublist

remove multiple elements from list python
python remove element from list by index
python remove all occurrences from list
remove list of elements from list python
remove string from list python
python remove item from list if contains
python remove duplicate items from list
python remove items from list by index

I have the following list of list:

list_of_list = [["-", " ", "P"], ["-", " ", "L"], ["-", " ", "R"], ["K", "|", "K"], ["K", "|", "K"], ["I", " ", "-"], ["K", "|", "K"], ["-", " ", "K"], ["-", " ", "V"], ["-", " ", "D"], ["-", " ", "P"], ["-", " ", "K"], ["-", " ", "K"], ["-", " ", "D"], ["-", " ", "Q"], ["-", " ", "E"], ["A", "|", "A"], ["N", " ", "-"], ["-", " ", "K"], ["-", " ", "E"], ["R", "|", "R"], ["-", " ", "L"], ["-", " ", "K"], ["R", "|", "R"], ["S", " ", "-"], ["N", " ", "-"], ["S", " ", "-"], ["K", "|", "K"], ["-", " ", "I"], ["-", " ", "R"], ["K", "|", "K"], ["-", " ", "L"], ["-", " ", "E"]]

Which looks like this:

In [48]: list_of_list
Out[48]:
[['-', ' ', 'P'], # remove this
 ['-', ' ', 'L'], # remove this
 ['-', ' ', 'R'], # remove this
 ['K', '|', 'K'],
 ['K', '|', 'K'],
 ['I', ' ', '-'],
 ['K', '|', 'K'],
 ['-', ' ', 'K'],
 ['-', ' ', 'V'],
 ['-', ' ', 'D'],
 ['-', ' ', 'P'],
 ['-', ' ', 'K'],
 ['-', ' ', 'K'],
 ['-', ' ', 'D'],
 ['-', ' ', 'Q'],
 ['-', ' ', 'E'],
 ['A', '|', 'A'],
 ['N', ' ', '-'],
 ['-', ' ', 'K'],
 ['-', ' ', 'E'],
 ['R', '|', 'R'],
 ['-', ' ', 'L'],
 ['-', ' ', 'K'],
 ['R', '|', 'R'],
 ['S', ' ', '-'],
 ['N', ' ', '-'],
 ['S', ' ', '-'],
 ['K', '|', 'K'],
 ['-', ' ', 'I'],
 ['-', ' ', 'R'],
 ['K', '|', 'K'],
 ['-', ' ', 'L'],  # remove this
 ['-', ' ', 'E']]  # remove this

As shown in the output above, what I want to do is to remove the element of the beginning and the end of the list. In the beginning, we remove all the lists where the 2nd element is empty until it finds |. In the end, we remove all the list after the last | found is empty.

The desired output is this:

[['K', '|', 'K'],
 ['K', '|', 'K'],
 ['I', ' ', '-'],
 ['K', '|', 'K'],
 ['-', ' ', 'K'],
 ['-', ' ', 'V'],
 ['-', ' ', 'D'],
 ['-', ' ', 'P'],
 ['-', ' ', 'K'],
 ['-', ' ', 'K'],
 ['-', ' ', 'D'],
 ['-', ' ', 'Q'],
 ['-', ' ', 'E'],
 ['A', '|', 'A'],
 ['N', ' ', '-'],
 ['-', ' ', 'K'],
 ['-', ' ', 'E'],
 ['R', '|', 'R'],
 ['-', ' ', 'L'],
 ['-', ' ', 'K'],
 ['R', '|', 'R'],
 ['S', ' ', '-'],
 ['N', ' ', '-'],
 ['S', ' ', '-'],
 ['K', '|', 'K'],
 ['-', ' ', 'I'],
 ['-', ' ', 'R'],
 ['K', '|', 'K']]

How can I achieve that?

Just slicing:

s = ''.join(b for a,b,c in list_of_list)
list_of_list[s.find('|'):s.rfind('|')+1]

How to remove element of list based on condition in the sublist, Just slicing: s = ''.join(b for a,b,c in list_of_list) list_of_list[s.find('|'):s.rfind('|')+1]. I have two lists that have the same length, lstA, lstB, I want to remove elements that are not good based on some conditions, but at the meantime, I also want to remove the elements in lstB that have the same position with the unwanted one in lstA. like below: lstA = ['good','good2', ''] lstB = [1,2,3] I want '' in lstA and 3 in lstB removed:

Slicing + enumerate:

l=[i for i,v in enumerate(list_of_list) if v[1]=='|']
l2=list_of_list[l[0]:l[-1]+1]
print(l2)

Output:

[['K', '|', 'K'], ['K', '|', 'K'], ['I', ' ', '-'], ['K', '|', 'K'], ['-', ' ', 'K'], ['-', ' ', 'V'], ['-', ' ', 'D'], ['-', ' ', 'P'], ['-', ' ', 'K'], ['-', ' ', 'K'], ['-', ' ', 'D'], ['-', ' ', 'Q'], ['-', ' ', 'E'], ['A', '|', 'A'], ['N', ' ', '-'], ['-', ' ', 'K'], ['-', ' ', 'E'], ['R', '|', 'R'], ['-', ' ', 'L'], ['-', ' ', 'K'], ['R', '|', 'R'], ['S', ' ', '-'], ['N', ' ', '-'], ['S', ' ', '-'], ['K', '|', 'K'], ['-', ' ', 'I'], ['-', ' ', 'R'], ['K', '|', 'K']]

Remove multiple elements from a list in Python, Given a list of numbers, write a Python program to remove multiple elements from a list based on the given condition. Example: Input: [12, 15, 3, 10] Output:  The above example will remove “Hello” from the list stack. Note that not all collections support item removal. In that case the method will throw an UnsupportedOperationException in case an attempt is made to remove a matching element.

Just play with indexes

def ind(l):
    for i,v in enumerate(l):
        if v[1]=="|": return i

ll = ll[ind(ll):]
ll[::-1][ind(ll[::-1]):][::-1]

Python List remove(), If you need to delete elements based on the index (like the fourth element), you can use the pop() method. Also, you can use the Python del statement to remove​  In python list’s pop() function will remove the element at given index and also returns the deleted element. If index is not given then it deletes the last element.

You can use itertools.groupby:

import itertools
def remove_elements(l):
  new_data = [[a, list(b)] for a, b in itertools.groupby(l, key=lambda x:x[1] == ' ')]
  _, *content, _end = new_data
  return [c for _, c in content]

list_of_list = [["-", " ", "P"], ["-", " ", "L"], ["-", " ", "R"], ["K", "|", "K"], ["K", "|", "K"], ["I", " ", "-"], ["K", "|", "K"], ["-", " ", "K"], ["-", " ", "V"], ["-", " ", "D"], ["-", " ", "P"], ["-", " ", "K"], ["-", " ", "K"], ["-", " ", "D"], ["-", " ", "Q"], ["-", " ", "E"], ["A", "|", "A"], ["N", " ", "-"], ["-", " ", "K"], ["-", " ", "E"], ["R", "|", "R"], ["-", " ", "L"], ["-", " ", "K"], ["R", "|", "R"], ["S", " ", "-"], ["N", " ", "-"], ["S", " ", "-"], ["K", "|", "K"], ["-", " ", "I"], ["-", " ", "R"], ["K", "|", "K"], ["-", " ", "L"], ["-", " ", "E"]]
print(remove_elements(list_of_list))

Output:

[[['K', '|', 'K'], ['K', '|', 'K']], [['I', ' ', '-']], [['K', '|', 'K']], [['-', ' ', 'K'], ['-', ' ', 'V'], ['-', ' ', 'D'], ['-', ' ', 'P'], ['-', ' ', 'K'], ['-', ' ', 'K'], ['-', ' ', 'D'], ['-', ' ', 'Q'], ['-', ' ', 'E']], [['A', '|', 'A']], [['N', ' ', '-'], ['-', ' ', 'K'], ['-', ' ', 'E']], [['R', '|', 'R']], [['-', ' ', 'L'], ['-', ' ', 'K']], [['R', '|', 'R']], [['S', ' ', '-'], ['N', ' ', '-'], ['S', ' ', '-']], [['K', '|', 'K']], [['-', ' ', 'I'], ['-', ' ', 'R']], [['K', '|', 'K']]]

Or slightly longer solution, although more robust:

_start = [i for i in range(len(l)) if all(c[1] == ' ' for c in l[:i])]
_end = [i for i in range(len(l)) if all(c[1] == ' ' for c in l[i:])]
new_l = l[0 if not _start else _start[-1]:len(l) if not _end else _end[-1]-1]

Python : How to remove multiple elements from list ? – thispointer.com, Suppose we want to remove multiple elements from a list by index range, then we Delete elements from a Numpy Array by value or conditions in Python Python : Get number of elements in a list, lists of lists or nested list  The remove () method removes the item which is passed as an argument. If you need to delete elements based on the index (like the fourth element or last element), you can use the pop () method. Also, you can use del statement to remove items from a list or delete an entire list.

Python : How to remove element from a list by value or Index , Python : How to Check if an item exists in list ? | Search by Value or Condition · Delete elements, rows or columns from a Numpy Array by index  The remove() function uses the list element as the argument to delete. You have to pass only the single element which you want to delete. The function requires only one element and can delete the only single element from the list. Use the list variable concatenated with the remove() to remove the list element.

11. Lists, List slices¶. The slice operations we saw previously with strings let us work with sublists: We can also remove elements from a list by assigning an empty list to them: The del statement removes an element from a list: Python has a built-in type conversion function called list that tries to turn whatever you give it into a list. Remove multiple elements from list while Iterating Iterate over the list and remove them one by one if its divisible by 3 i.e.

Remove Elements From Lists | Python List remove() Method, The main reason why lists are an important tool in Python is because of the wide variety of the built-in functions it comes with. Lists are also very  Unlike member function list::erase, which erases elements by their position (using an iterator), this function ( list::remove) removes elements by their value. A similar function, list::remove_if, exists, which allows for a condition other than an equality comparison to determine whether an element is removed. Value of the elements to be removed.

Comments
  • Have you tried anything?
  • Wow!, i never new that there was a function called rindex for strings, Now i know, You just thought me rindex
  • This will not work if | does not exist in the input i.e list_of_list = [['-', ' ', 'P'], ['asd', ' ', 'J']]. A ValueError: substring not found will be raised.
  • @Ajax1234 Changed to rfind instead, which would return empty list in that case (not sure what OP would prefer, though). FWIW your code would raise exception too - ValueError: not enough values to unpack.
  • @wim My first solution would with itertools.groupby, however, my second solution does not. itertools.groupby is cleaner and works should the input be guaranteed to start and end with lists containing spaces.
  • @Ajax1234 So your first solution and second solution don't actually return equivalent results for the edge case - you should probably mention that they have a difference in behaviour in the answer. And seems the OP can't use your first solution anyway because it only works on Python 3.
  • I get invalid syntax for *content I'm using Python 2.7.
  • @scamander *content is only valid in Python3. However, my solution below it will work for both versions.
  • l[:i] and l[i:] is copying the list on every iteration. That's O(n^2) worst case. Also you talk about enumerate (which would have been better) but never used it.
  • @wim Ah yes, removed mention of enumerate.