x = ['1', '2', '4', 'c'], so x[1]=='2', which makes the expression (x[0] != "1" and x[1] != "2" and x[2] != "3") be evaluated as False.

When conditions are joined by and, they return True only if all conditions are True, and if they are joined by or, they return True when the first among them is evaluated to be True.

Answer from shiva on Stack Overflow
🌐
Finxter
blog.finxter.com › home › learn python blog › python filter(lambda multiple conditions)
Python filter(lambda multiple conditions) - Be on the Right Side of Change
February 5, 2024 - The lambda function takes an accumulator acc and element x, appending x when it meets the conditions. In summary, there are several methods to filter a list in Python by multiple conditions.
Top answer
1 of 4
10

x = ['1', '2', '4', 'c'], so x[1]=='2', which makes the expression (x[0] != "1" and x[1] != "2" and x[2] != "3") be evaluated as False.

When conditions are joined by and, they return True only if all conditions are True, and if they are joined by or, they return True when the first among them is evaluated to be True.

2 of 4
8
['1', '2', '4', 'c']

Fails for condition

x[0] != "1"

as well as

x[1] != "2"

Instead of using or, I believe the more natural and readable way is:

lambda x: (x[0], x[1], x[2]) != ('1','2','3')

Out of curiosity, I compared three methods of, er... comparing, and the results were as expected: slicing lists was the slowest, using tuples was faster, and using boolean operators was the fastest. More precisely, the three approaches compared were

list_slice_compare = lambda x: x[:3] != [1,2,3]

tuple_compare = lambda x: (x[0],x[1],x[2]) != (1,2,3)

bool_op_compare = lambda x: x[0]!= 1 or x[1] != 2 or x[2]!= 3

And the results, respectively:

In [30]: timeit.Timer(setup="import timeit,random; rand_list = [random.randint(1,9) for _ in range(4)]; list_slice_compare = lambda x: x[:3] != [1,2,3]", stmt="list_slice_compare(rand_list)").repeat()
Out[30]: [0.3207617177499742, 0.3230015148823213, 0.31987868894918847]

In [31]: timeit.Timer(setup="import timeit,random; rand_list = [random.randint(1,9) for _ in range(4)]; tuple_compare = lambda x: (x[0],x[1],x[2]) != (1,2,3)", stmt="tuple_compare(rand_list)").repeat()
Out[31]: [0.2399928924012329, 0.23692036176475995, 0.2369164465619633]

In [32]: timeit.Timer(setup="import timeit,random; rand_list = [random.randint(1,9) for _ in range(4)]; bool_op_compare = lambda x: x[0]!= 1 or x[1] != 2 or x[2]!= 3", stmt="bool_op_compare(rand_list)").repeat()
Out[32]: [0.144389363900018, 0.1452672728203197, 0.1431527621755322]
Discussions

Filtering list of objects on multiple conditions
Hi all, interested in your approaches and suggestions to this problem. Let's say I have created a custom Player class that contains many attributes… More on reddit.com
🌐 r/learnpython
4
1
July 27, 2023
Multiple conditions in python filter function
No, why would you expect your output to include 2 when your condition explicitly says x!=2? The other condition excludes any even number, since an odd number modulus 2 returns 1, and 1 converts to True. 0 converts to False. So, you're explicitly filtering out any number evenly divisible by 2. More on reddit.com
🌐 r/learnprogramming
4
1
January 7, 2019
python - How to filter list based on multiple conditions? - Stack Overflow
The approach is to exclude digits from the comparison. So in the lambda function, for each mylist item we replace digits with '', then compare against the only item in target_list, target_list[0]. filter will match all items where the lambda function is True More on stackoverflow.com
🌐 stackoverflow.com
November 25, 2019
Applying multiple filters to a list.
[x for x in L if f1(x) and f2(x)]? More on reddit.com
🌐 r/Python
9
9
September 1, 2017
🌐
Spark By {Examples}
sparkbyexamples.com › home › python › using filter() with lambda in python
Using filter() with Lambda in Python - Spark By {Examples}
May 31, 2024 - In Python, the filter() function is used to filter elements of an iterable (e.g., a list) based on a certain condition. When combined with the lambda
🌐
Kanoki
kanoki.org › 2022 › 09 › 12 › python-lambda-if-else-elif-with-multiple-conditions-and-filter-list-with-conditions-in-lambda
python lambda if, else & elif with multiple conditions and filter list with conditions in lambda | kanoki
September 12, 2022 - We can use bitwise operator in lambda to create the condition, Here we want to verify if score is greater than 7 and less than 10 or if it is less than 5 or not · grade = lambda x: ((x>7) & (x<=10))| (x<=5) grade(12) Out: False · We could also write only the if statement without an else like ...
🌐
GeeksforGeeks
geeksforgeeks.org › lambda-filter-python-examples
Lambda and filter in Python Examples - GeeksforGeeks
April 8, 2025 - Before diving into examples, let’s ... in Python: lambda function: A small, anonymous function defined using the lambda keyword. It can take any number of arguments but has only one expression. filter() function: A built-in function that filters elements from an iterable based on a condition (function) ...
🌐
PäksTech
pakstech.com › blog › python-multiple-filter
Combine Multiple Filter Conditions in Python | PäksTech
October 3, 2022 - def get_first_match( products, name_contains=None, min_price=None, max_price=None, product_categories=None, ): filters = [] if name_contains: filters.append(lambda p: name_contains in p["name"]) if min_price: filters.append(lambda p: p["price"] >= min_price) if max_price: filters.append(lambda p: p["price"] <= max_price) if product_categories: filters.append(lambda p: p["category"] in product_categories) try: return next(filter(lambda p: all(f(p) for f in filters), products)) except StopIteration: return None
🌐
YouTube
youtube.com › the python oracle
python lambda list filtering with multiple conditions - YouTube
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn--Music by Eric Matyashttps://www.soundimage.orgTrack title: The Buil
Published: December 19, 2022
Views: 44
🌐
Reddit
reddit.com › r/learnpython › filtering list of objects on multiple conditions
r/learnpython on Reddit: Filtering list of objects on multiple conditions
July 27, 2023 - filter(lambda p: 20 <- p.age < 25, filter(lambda p: p.height > 180, filter(lambda p: p.team == "Rovers", player_list))) which should give you an idea of how you could iterate over a list of filtering functions and return the objects that pass all of the filters. Pandas - Filter based on multiple conditions · r/learnpython • · upvote · · comments · Applying multiple filters to a list. r/Python • ·
Find elsewhere
🌐
CopyProgramming
copyprogramming.com › howto › python-lambda-list-filtering-with-multiple-conditions
Python: Multiple condition filtering of lists in Python using lambda functions
June 17, 2023 - If the condition is met for a certain row, the value will be True , otherwise it will be False . We can utilize the boolean column as a component in the dataframe indexed_df[boolean_column] to retrieve only the rows that have a matching value in boolean_column as True . Lambda to filter list python Code Example, Python Filter List with Lambda python by Gorgeous Gazelle on Sep 25 2021 Donate Comment 0 xxxxxxxxxx 1 # creating a list in Python 2 mylist= [3,5,1,5,7,8,2,6] 3 4 #filter all the odd numbers using list Comprehension 5 result = [x for x in mylist if x%2!=0] 6 print('The odd numbers are ',list(result)) 7 8 9
🌐
Reddit
reddit.com › r/learnprogramming › multiple conditions in python filter function
r/learnprogramming on Reddit: Multiple conditions in python filter function
January 7, 2019 -

Question is to find all the prime numbers between two given numbers.

i made a 'list' of numbers between the two given number(let the 2 numbers be 1 and 100).

then i did this

l1=list(filter(lambda x:x!=2 and x%2,l))

where l is my list with all numbers.

output i got [1,3,5,6.....99]

shouldn't my output be [1,2,3....99]

🌐
Note.nkmk.me
note.nkmk.me › home › python
Filter (Extract/Remove) Items of a List with in Python: filter() | note.nkmk.me
May 15, 2023 - filter() returns an iterator in ... (lambda) and functions defined with def · Apply multiple conditions · Specify None as the first argument · Extract False elements: itertools.filterfalse() Use list comprehensions and ...
🌐
EyeHunts
tutorial.eyehunts.com › home › python filter(lambda)
Python filter(lambda)
January 19, 2023 - Python filter(lambda) is possible because you can use the Lambda function inside the filter() built-in function. The filter method filters elements from an iterable that meets a specific condition.
🌐
Pinnsg
pinnsg.com › databricks-multiple-filters-using-a-python-lambda-statement
Databricks Multiple Filters using a Python Lambda statement
JavaScript is disabled in your browser · Please enable JavaScript to proceed · A required part of this site couldn’t load. This may be due to a browser extension, network issues, or browser settings. Please check your connection, disable any ad blockers, or try using a different browser
Top answer
1 of 4
2

You can define a "filter-making function" that preprocesses the target list. The advantages of this are:

  • Does minimal work by caching information about target_list in a set: The total time is O(N_target_list) + O(N), since set lookups are O(1) on average.
  • Does not use global variables. Easily testable.
  • Does not use nested for loops
def prefixes(target):
    """ 
    >>> prefixes("FOLD/AAA.RST.TXT")
    ('FOLD', 'AAA', 'RST')

    >>> prefixes("FOLD/AAA.RST.12345.TXT")
    ('FOLD', 'AAA', 'RST')
    """
    x, rest = target.split('/')
    y, z, *_ = rest.split('.')
    return x, y, z

def matcher(target_list):
    targets = set(prefixes(target) for target in target_list)
    def is_target(t):
        return prefixes(t) in targets
    return is_target

Then, you could do:

>>> list(filter(matcher(target_list), mylist))
['FOLD/AAA.RST.12345.TXT', 'FOLD/AAA.RST.87589.TXT']
2 of 4
1

Define a function to filter values:

target_list = ["FOLD/AAA.RST.TXT"]

def keep(path):
    template = get_template(path)
    return template in target_list

def get_template(path):
    front, numbers, ext = path.rsplit('.', 2)
    template = '.'.join([front, ext])
    return template

This uses str.rsplit which searches the string in reverse and splits it on the given character, . in this case. The parameter 2 means it only performs at most two splits. This gives us three parts, the front, the numbers, and the extension:

>>> 'FOLD/AAA.RST.12345.TXT'.rsplit('.', 2)
['FOLD/AAA.RST', '12345', 'TXT']

We assign these to front, numbers and ext.

We then build a string again using str.join

>>> '.'.join(['FOLD/AAA.RST', 'TXT']
'FOLD/AAA.RST.TXT'

So this is what get_template returns:

>>> get_template('FOLD/AAA.RST.12345.TXT')
'FOLD/AAA.RST.TXT'

We can use it like so:

mylist = [
    "FOLD/AAA.RST.12345.TXT",
    "FOLD/BBB.RST.12345.TXT",
    "RUNS/AAA.FGT.12345.TXT",
    "FOLD/AAA.RST.87589.TXT",
    "RUNS/AAA.RST.11111.TXT"
]

from pprint import pprint

pprint(filter(keep, mylist))

Output:

['FOLD/AAA.RST.12345.TXT'
 'FOLD/AAA.RST.87589.TXT']
🌐
Finxter
blog.finxter.com › how-to-filter-in-python-using-lambda-functions
How to Filter in Python using Lambda Functions? – Be on the Right Side of Change
The second argument is the iterable to be filtered—the lambda function checks for each element in the iterable whether the element pass the filter or not. The filter() function returns an iterator with the elements that pass the filtering condition.
🌐
GeeksforGeeks
geeksforgeeks.org › python-filter-rows-with-elements-as-multiple-of-k
Python – Filter rows with Elements as Multiple of K | GeeksforGeeks
June 2, 2023 - The original list is : [[5, 10, 15], [4, 8, 3], [100, 15], [5, 10, 23]] Rows with K multiples : [[5, 10, 15], [100, 15]] Time Complexity: O(n) where n is the number of elements in the list “test_list”. Auxiliary Space: O(1) additional space is not needed ... In this, we perform task of filtering using filter() and lambda function and task of checking for all elements in rows using all(). ... # Python3 code to demonstrate working of # Access element at Kth index in String # Using filter() + lambda + all() # initializing string list test_list = [[5, 10, 15], [4, 8, 3], [100, 15], [5, 10, 23]] # printing original list print("The original list is : " + str(test_list)) # initializing K K = 5 # using all() to check for all elements being multiples of K res = list(filter(lambda sub : all(ele % K == 0 for ele in sub), test_list)) # printing result print("Rows with K multiples : " + str(res))
Top answer
1 of 2
2

I would simply make a function that returns the conditional:

def makeConditions(**p):
    fieldname = {"ref": 0, "type": 1, "date": 2 }
    def filterfunc(elt):
        for k, v in p.items():
            if elt[fieldname[k]] != v: # if one condition is not met: false
                return False
        return True
    return filterfunc

Then you can use it that way:

>>> list(filter(makeConditions(ref=1), ex))
[[1, 'CB', '2017-12-11'], [1, 'CB', '2017-11-08']]
>>> list(filter(makeConditions(type='CB'), ex))
[[1, 'CB', '2017-12-11'], [2, 'CB', '2017-12-01'], [1, 'CB', '2017-11-08']]
>>> list(filter(makeConditions(type='CB', ref=2), ex))
[[2, 'CB', '2017-12-01']]
2 of 2
0

You was almost there, the idea is to create a list with the functions that checks the conditions you need, once you have them you can just call those functions over the list they have to check and use all function to check if all of them are evaluated to True, note the use of partial so the function in the filter call only takes the data list; check this:

from functools import partial

ex = [
    # ["ref", "type", "date"]
    [1, 'CB', '2017-12-11'],
    [2, 'CB', '2017-12-01'],
    [3, 'RET', '2017-11-08'],
    [1, 'CB', '2017-11-08'],
    [5, 'RET', '2017-10-10'],
]

conditions  = {"ref": 3}
conditions2 = {"ref": 1, "type": "CB"}

def apply(data, *args):
"""
same as map, but takes some data and a variable list of functions instead
it will make all that functions evaluate over that data
"""
  return map(lambda f: f(data), args)


def makeConditions(p, myList):
    # For each key:value in the dictionnary
    def checkvalue(index, val, lst):
      return lst[index] == val
    conds = []
    for key, value in p.items():
        if key == "ref":
            conds.append(partial(checkvalue, 0, value))
        elif key == "type":
            conds.append(partial(checkvalue, 1, value))
        elif key == "date":
            conds.append(partial(checkvalue, 2, value))
    return all(apply(myList, *conds)) # does all the value checks evaluate to true?

#use partial to bind the conditions to the makeConditions function
print(list(filter(partial(makeConditions, conditions), ex)))
#[[3, 'RET', '2017-11-08']]
print(list(filter(partial(makeConditions, conditions2), ex)))
#[[1, 'CB', '2017-12-11'], [1, 'CB', '2017-11-08']]

Here you have a live example

Do I have to execute the filter() function for each sublist or is it possible to do it for the whole global list?

Filter iterates over all the list aplying a function for each of the elements, if the function evaluates to True then the element will remind in the result, so filter works over the whole global list

🌐
GeeksforGeeks
geeksforgeeks.org › filtering-a-list-of-dictionary-on-multiple-values-in-python
Filtering a List of Dictionary on Multiple Values in Python | GeeksforGeeks
February 7, 2024 - The filter function in combination with a lambda function is another approach for filtering lists based on multiple criteria.