Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,970 questions

51,912 answers

573 users

How to remove all sublists outside a given range in a list of lists with Python

1 Answer

0 votes
def remove_sublists_range(lstlst, lower, upper):
    filtered_lst = [sublist for sublist in lstlst if min(sublist) >= lower and max(sublist) <= upper]
     
    return filtered_lst
 
list_of_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
lower_bound = 2
upper_bound = 7


'''
[1, 2, 3]
min = 1 → 1 < 2 fails
Not kept

[4, 5, 6]
min = 4 → 4 ≥ 2 OK
max = 6 → 6 ≤ 7 OK
Kept

[7, 8, 9]
min = 7 → 7 ≥ 2 OK
max = 9 → 9 > 7 fails
Not kept

[10, 11, 12]
min = 10 → 10 > 7 → fails
Not kept
'''

result = remove_sublists_range(list_of_list, lower_bound, upper_bound)
print(result)


 
'''
run:
 
[[4, 5, 6]]
 
'''

 



answered 4 hours ago by avibootz
edited 2 hours ago by avibootz
...