Remove a list from a list of lists Python

  • A+
Category:Languages

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 

 


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]] 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: