Perhaps a bit more semantic would be to use any.

for sublist in the_list:
    if any(item in filters_exclude for item in sublist):
        continue
    filtered_list.append(sublist)

Maybe overkill, but you could even factor that into its own function then use the builtin filter

def good_list(some_list):
    return not any(item in filters_exclude for item in some_list)

filtered_list = filter(good_list, the_list)

This should accomplish the goal you described. However, the code you wrote has potential issues, as mentioend in the comments.

Answer from sytech on Stack Overflow
๐ŸŒ
Finxter
blog.finxter.com โ€บ home โ€บ learn python blog โ€บ how to filter a list of lists in python?
How to Filter a List of Lists in Python? - Be on the Right Side of Change
May 9, 2020 - Short answer: To filter a list ... lists, use the list comprehension statement [x for x in list if condition(x)] and replace condition(x) with your filtering condition that returns True to include inner list x, and False otherwise...
Discussions

Deep Filter a List of Lists
Posted by u/[Deleted Account] - 3 votes and 3 comments More on reddit.com
๐ŸŒ r/learnpython
3
3
April 6, 2021
how to filter nested list in python - Stack Overflow
Communities for your favorite technologies. Explore all Collectives ยท Ask questions, find answers and collaborate at work with Stack Overflow for Teams More on stackoverflow.com
๐ŸŒ stackoverflow.com
nested list filtering in python? - Stack Overflow
is it possible to create nested filtering for list? I have a list of bookmarks that contains a list of tags. I want to filter for bookmarks with a specific tag. def filterListByTag(bookmarkList, t... More on stackoverflow.com
๐ŸŒ stackoverflow.com
May 23, 2017
pandas - Filtering a nested list in python - Stack Overflow
Hey guys i'm trying to filter a nested list to only include strings that include the word "yellow". My aim is to store each color in their own separate column into my dataframe I tried labels.str.... More on stackoverflow.com
๐ŸŒ stackoverflow.com
April 11, 2019
๐ŸŒ
w3resource
w3resource.com โ€บ python-exercises โ€บ lambda โ€บ python-lambda-exercise-40.php
Python: Find the nested lists elements, which are present in another list using lambda - w3resource
Write a Python program to find the nested list elements, which are present in another list using lambda. ... # Define a function 'intersection_nested_lists' that finds the intersection of elements between two nested lists def intersection_nested_lists(l1, l2): # Use list comprehension with a nested filter to find elements in each sublist of 'l2' present in 'l1' # For each sublist in 'l2', filter elements that are present in 'l1' and create a list of these elements result = [list(filter(lambda x: x in l1, sublist)) for sublist in l2] # Return the resulting nested list return result # Create two
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ deep filter a list of lists
r/learnpython on Reddit: Deep Filter a List of Lists
April 6, 2021 - I need help with deep filtering nested lists. def deepfilter(f,lst): if not lst: return [] elif type(lst[0]) == list: return [deepfilter(f,lst[0])] +โ€ฆ
Top answer
1 of 2
1

If you don't want to preserve the inner lists you can do it with a double list comprehension:

[item for inner in my_list for item in inner if 'yellow' in item]

yields:

[' Example4 (yellow)', ' Example14 (yellow)']

If you want to preserve the inner lists you can do it like this:

[ [item for item in inner if 'yellow' in item] for inner in my_list ]

yields:

[[' Example4 (yellow)'], [' Example14 (yellow)']]

2 of 2
1

Import necessary packages and intialize data:

import pandas as pd
import re

my_list = [['Example1 (purple)',
  ' Example2 (blue)',
  ' Example3 (orange)',
  ' Example4 (yellow)',
  ' Example5 (red)',
  ' Example6 (pink)',
  ' Example7 (sky)'],
 ['Example8 (purple)',
  ' Example9 (blue)',
  ' Example10 (orange)',
  ' Example11 (sky)',
  ' Example12 (green)',
  ' Example13 (green)',
  ' Example14 (yellow)',
  ' Example15 (red)',
  ' Example16 (pink)',
  ' Example17 (pink)',
  ' Example18 (green)',
  ' Example19 (sky)']]

Flatten the list, so its not nested lists in lists. (This is why you got an error that lists don't have split. If you do [x.split() for x in my_list] it will give an error because the elements made up of my_list are lists)

Define a flatlist function and flatten list:

flat_list = lambda l: [item for sublist in l for item in sublist]
flat = flat_list(my_list)

Create an empty dataframe

df = pd.DataFrame({})

Extract out the elements of the single flat list. this strips it of whitespace, then splits it by the space, taking the 0th element for the "Example1", and then strips it again to remove whitespace. do it again but take the 1st element for the color. Wrap it in () and separate by a comma to return it as a tuple.

splitout = [(x.strip().split(' ')[0].strip(), x.strip().split(' ')[1]) for x in pd.Series(flat)]

set the two dataframe columns. the first is just grabbing the first element of the splitout which is always Example, the second uses re.sub to remove the () from the color

df['Example'] = [x[0] for x in splitout]
df['Color'] = [re.sub('[/(/)]', '', x[1]) for x in splitout]

      Example   Color
0    Example1  purple
1    Example2    blue
2    Example3  orange
3    Example4  yellow
4    Example5     red
5    Example6    pink
6    Example7     sky
7    Example8  purple
8    Example9    blue
9   Example10  orange
10  Example11     sky
11  Example12   green
12  Example13   green
13  Example14  yellow
14  Example15     red
15  Example16    pink
16  Example17    pink
17  Example18   green
18  Example19     sky

Then you can pivot into a larger dataframe with colors for columns:

pd.pivot_table(df.assign(v=1), index='Example', columns='Color', values='v')

Color      blue  green  orange  pink  purple  red  sky  yellow
Example                                                       
Example1    NaN    NaN     NaN   NaN     1.0  NaN  NaN     NaN
Example10   NaN    NaN     1.0   NaN     NaN  NaN  NaN     NaN
Example11   NaN    NaN     NaN   NaN     NaN  NaN  1.0     NaN
Example12   NaN    1.0     NaN   NaN     NaN  NaN  NaN     NaN
Example13   NaN    1.0     NaN   NaN     NaN  NaN  NaN     NaN
Example14   NaN    NaN     NaN   NaN     NaN  NaN  NaN     1.0
Example15   NaN    NaN     NaN   NaN     NaN  1.0  NaN     NaN
Example16   NaN    NaN     NaN   1.0     NaN  NaN  NaN     NaN
Example17   NaN    NaN     NaN   1.0     NaN  NaN  NaN     NaN
Example18   NaN    1.0     NaN   NaN     NaN  NaN  NaN     NaN
Example19   NaN    NaN     NaN   NaN     NaN  NaN  1.0     NaN
Example2    1.0    NaN     NaN   NaN     NaN  NaN  NaN     NaN
Example3    NaN    NaN     1.0   NaN     NaN  NaN  NaN     NaN
Example4    NaN    NaN     NaN   NaN     NaN  NaN  NaN     1.0
Example5    NaN    NaN     NaN   NaN     NaN  1.0  NaN     NaN
Example6    NaN    NaN     NaN   1.0     NaN  NaN  NaN     NaN
Example7    NaN    NaN     NaN   NaN     NaN  NaN  1.0     NaN
Example8    NaN    NaN     NaN   NaN     1.0  NaN  NaN     NaN
Example9    1.0    NaN     NaN   NaN     NaN  NaN  NaN     NaN

whole code:

import pandas as pd
import re

flat_list = lambda l: [item for sublist in l for item in sublist]
flat = flat_list(my_list)

splitout = [(x.strip().split(' ')[0].strip(), x.strip().split(' ')[1]) for x in pd.Series(flat)]

df = pd.DataFrame({})
df['Example'] = [x[0] for x in splitout]
df['Color'] = [re.sub('[/(/)]', '', x[1]) for x in splitout]

pivot = pd.pivot_table(df.assign(v=1), index='Example', columns='Color', values='v')
Find elsewhere
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ python-filter-key-from-nested-item
Python - Filter Key from Nested item - GeeksforGeeks
April 27, 2023 - This is because we are storing the matched keys in the res list. Method #2: Using dictionary comprehension + get() The combination of above functions provide another way to solve this problem. In this, we perform the check of element presence using get(). ... # Python3 code to demonstrate working of # Filter Key from Nested item # Using dictionary comprehension + get() # initializing dictionary test_dict = {'gfg' : {'best' : 4, 'good' : 5}, 'is' : {'better' : 6, 'educational' : 4}, 'CS' : {'priceless' : 6}, 'Maths' : {'good' : 5}} # printing original dictionary print("The original dictionary : " + str(test_dict)) # initializing dictionary que_dict = {'good' : 5} # Filter Key from Nested item # Using dictionary comprehension + get() res = [ idx for idx in test_dict if test_dict[idx].get('good') == que_dict['good'] ] # printing result print("Match keys : " + str(res))
๐ŸŒ
Analytics Vidhya
analyticsvidhya.com โ€บ home โ€บ how to filter lists in python?
Filter Lists in Python: Mastering the Art of Data Manipulation
April 15, 2024 - In this article, we have covered the basics of list filtering in Python, including techniques like using the `filter()` function, list comprehension, lambda functions, conditional statements, and built-in functions/libraries. We have also explored practical methods for filtering lists based on value, condition, index, pattern matching, and data type. Furthermore, we have delved into advanced techniques such as chaining filters, negating filters, filtering nested lists, filtering with regular expressions, and filtering with custom functions.
Top answer
1 of 2
5

First of all, there is nothing wrong with defining a filtering or mapping function as a regular function via def if it would be a benefit to readability - remember "Readability counts" and "Sparse is better than dense". Just because there are inline lambda function in the language, does not mean you have to squeeze your logic into it.

Since you eventually want to build a generic solution for an arbitrary list depth, you can recursively apply the filtering function via map() + filter() to remove the None values:

def filter_function(e):
    if isinstance(e, list):
        return filter(None, map(filter_function, e))
    elif e > 10:
        return e

my_list = list(filter_function(my_list))  

Note that list() would be needed on Python 3.x, since filter() does not return a list.


Demo:

>>> my_list = [[1], [2, [3, 12, [4, 11, 12]]], [5, 6, 13, 14], [15]]
>>> 
>>> def filter_function(e):
...     if isinstance(e, list):
...         return filter(None, map(filter_function, e))
...     elif e > 10:
...         return e
... 
>>> 
>>> print(list(filter_function(my_list)))
[[[12, [11, 12]]], [13, 14], [15]]
2 of 2
2

Well, this is not a best practice, but you can create a lambda function: use parenthesis to group conditions:

f = lambda e: filter(None, [f(y) for y in e]) if isinstance(e, list) else (e if e > 10 else None)

my_list = [[1], [2, [3, 12, [4, 11, 12]]], [5, 6, 13, 14], [15]]

>>> f(my_list)
[[[12, [11, 12]]], [13, 14], [15]]

For python 3 users:

f = lambda e: list(filter(None, [f(y) for y in e])) if isinstance(e, list) else (e if e > 10 else None)
๐ŸŒ
Python Guides
pythonguides.com โ€บ filter-lists-in-python
How To Filter Lists In Python?
March 19, 2025 - We want to filter out the orders that have at least one item priced over $50. By using a nested list comprehension with the any() function, we can check if any item in the order meets the condition and include the entire order in the expensive_orders list. Check out How to Iterate Through a List Backward in Python?
๐ŸŒ
FavTutor
favtutor.com โ€บ blogs โ€บ filter-list-python
Python filter() Function: 5 Best Methods to Filter a List
November 11, 2023 - Filter() function is mostly used for lambda functions to separate lists, tuples, or sets for which a function returns True. It can also be used on nested lists.
๐ŸŒ
Built In
builtin.com โ€บ data-science โ€บ nested-list-comprehension-python
How to Write Nested List Comprehensions in Python | Built In
To do this we write a single list comprehension with two for loops. Itโ€™s key to remember three things when doing this: The expression is always the first term. The for loops are always written in the order of the nesting.