Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove a list from a list of lists Python

Tags:

python

list

numpy

I have a list of lists:

[[0.0,3.3, 4.9, 7.5], [4, 6, 90, 21, 21.1], [3, 43, 99, 909, 2.11, 76, 76.9, 1000]]

I want to remove a sublist from the list if that sublist contains an element outside a given range.

For example; range = 3, 15

So, if a sublist contains, -69, -17, 0, 1, 2, 15.1, 246.99, i.e any element that is outside that range, I want that sublist removed.

The output that should be returned is a list of lists where all the sublists only contain values within that range:

[[6, 5, 7, 13, 12], [4, 6, 10], [9, 9, 4, 5, 11], [4, 4]]

I am aware that there are similar questions here such as:

Removing sublists from a list of lists

Python - Remove list(s) from list of lists (Similar functionality to .pop() )

I cannot get these solutions to work.

My goal is to not remove duplicates of lists: there are a lot of questions about that but that is not my goal.

My code:

max_value = 15
min_value = 3

for sublist in my_list:
  for item in sublist:
    if(item < min_value):
        my_list.pop(sublist)
    if(item > max_value):
        my_list.pop(sublist)
print(my_list)

Error:

TypeError: 'list' object cannot be interpreted as an integer
like image 658
Mazz Avatar asked Feb 01 '19 16:02

Mazz


People also ask

Can you remove a list from a list Python?

In Python, use list methods clear() , pop() , and remove() to remove items (elements) from a list. It is also possible to delete items using del statement by specifying a position or range with an index or slice.

How do I remove numbers from a list from another list in Python?

How to Remove an Element from a List Using the remove() Method in Python. To remove an element from a list using the remove() method, specify the value of that element and pass it as an argument to the method. remove() will search the list to find it and remove it.

How do I remove a list from nested list?

Remove items from a Nested List. If you know the index of the item you want, you can use pop() method. It modifies the list and returns the removed item. If you don't need the removed value, use the del statement.


1 Answers

You can use list comprehension. Here is a sample input and output. The idea is simple: For each sublist just check for the min and max if they fall outside the desired limits.

list_1 = [[0.0,3.3, 4.9, 7.5], [4, 6, 9, 11, 12.1], [3, 43, 99, 909, 2.11, 76, 76.9, 1000], ]

left = 3
right = 15

list_2 = [i for i in list_1 if (min(i)>=left and max(i)<=right)]
print (list_2)
# [[4, 6, 9, 11, 12.1]]
like image 68
Sheldore Avatar answered Oct 05 '22 19:10

Sheldore