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

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

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

Disclosure: My content contains affiliate links.

43,239 questions

56,142 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 Feb 17 by avibootz
edited Feb 17 by avibootz
...