Python | Remove all sublists outside the given range

Given, list of lists and a range, the task is to traverse each sub-list and remove sublists containing elements falling out of given range.

Examples:

Input : 
left= 10, right = 17, list = [[0, 1.2, 3.4, 18.1, 10.1],
                              [10.3, 12.4, 15, 17, 16, 11],
                              [100, 10, 9.2, 11, 13, 17.1], ]

Output: [[10.3, 12.4, 15, 17, 16, 11]]


Input : 
left= 1, right = 9, list = [[11, 12, 15, 17, 3],
                            [3, 1, 4, 5.2, 9, 19],
                            [2, 4, 6, 7.2, 8.9]]

Output: [[2, 4, 6, 7.2, 8.9]]

 
Method #1 : Iterating through each sublist.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python code to remove all the 
# sublist outside the given range
  
# Initialisation of list of list
list = [[0,1.2,3.4,18.1,10.1], 
        [10.3,12.4,15,17,16,11],
        [1000,100,10,3.2,11,13, 17.1], ]
  
# Defining range
left, right = 10, 17
  
# initialization of index
b=0
  
for t in list:
    a=0
    for k in t:
        if k<left or k>right:
            a=1
    if a==1:
        list.pop(b)
    b=b+1
  
# printing output
print(list)

chevron_right


Output:

[[10.3, 12.4, 15, 17, 16, 11]]

 
Method #2: Using list comprehension

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python code to remove all the 
# sublist outside the given range
  
# Initialisation of list of list
list = [[11, 12, 15, 17, 3],
        [3, 1, 4, 5.2, 9, 19],
        [2, 4, 6, 7.2, 8.9]]
  
# Defining range
left = 1
right = 9
  
# Using list comprehension
Output = [i for i in list if (min(i)>=left and max(i)<=right)]
  
# Printing output
print (Output)

chevron_right


Output:

[[2, 4, 6, 7.2, 8.9]]


My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.