Use a list comprehension:

[y for x,y in A if x>2]

Demo:

>>> A=[(1,'A'),(2,'H'),(3,'K'),(4,'J')]
>>> [y for x,y in A if x>2]
['K', 'J']
>>> 
Answer from U13-Forward on Stack Overflow
🌐
KDnuggets
kdnuggets.com › 2022 › 11 › 5-ways-filtering-python-lists.html
5 Ways of Filtering Python Lists - KDnuggets
November 14, 2022 - It is easy to write, and you can even add multiple if-else conditions without an issue. Learn list comprehension with code examples by reading When to Use a List Comprehension in Python. scores = [200, 105, 18, 80, 150, 140] filtered_scores = [s for s in scores if s >= 150] print(filtered_scores)
Discussions

Filtering list of objects on multiple conditions
'm looking for the most straightforward and intuitive way to filter these values. not sure there is an "in-between" where you avoid all the work but also get the functionality.. More on reddit.com
🌐 r/learnpython
4
1
July 27, 2023
How to filter a list of lists based on a variable set of conditions with Python? - Stack Overflow
Question related to this post. I need help to filter a list of lists depending on a variable set of conditions. Here is an extract of the list: ex = [ # ["ref", "type", "date"] [1, 'CB',... More on stackoverflow.com
🌐 stackoverflow.com
python - How to filter list based on multiple conditions? - Stack Overflow
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. More on stackoverflow.com
🌐 stackoverflow.com
November 25, 2019
Conditional loop filtering - Ideas - Discussions on Python.org
Python comprehension expressions have filtering built in: [thing.foo for thing in bunch_of_things if thing.bar > 42] But in regular loops we need to do this: for thing in bunch_of_things: if thing.bar > 42: do_something_with(thing.foo) It would be nice to have the same type of filtering in ... More on discuss.python.org
🌐 discuss.python.org
0
April 18, 2023
🌐
Mimo
mimo.org › glossary › python › filter
Python filter(): Syntax, Usage, and Examples
You should reach for filter() when you want to streamline conditional selection. It's especially useful for: Keeping only valid data entries from a list or array ... Instead of managing temporary lists and for loops manually, you express your filtering logic in one line. This approach is similar to filtering in other languages like Java or SQL, but with Python's more concise syntax.
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-filter-a-list-based-on-the-given-list-of-strings
Filter a list based on the Given List of Strings - Python - GeeksforGeeks
July 11, 2025 - Explanation: list comprehension ... The remaining paths are stored in res . This method applies a filtering condition using the filter() combined with a lambda expression....
🌐
Real Python
realpython.com › lessons › filtering-elements-list-comprehensions
Filtering Elements in List Comprehensions (Video) – Real Python
Conditional statements can be added to Python list comprehensions in order to filter out data. In this lesson, you learned how to use filtering to produce a list of even squares. The returned data is the same as before except for the fact that only even squares are returned.
Published   March 1, 2019
🌐
W3Schools
w3schools.com › python › numpy › numpy_array_filter.asp
NumPy Filter Array
In the example above we hard-coded the True and False values, but the common use is to create a filter array based on conditions. Create a filter array that will return only values higher than 42: import numpy as np arr = np.array([41, 42, 43, 44]) # Create an empty list filter_arr = [] # go through each element in arr for element in arr: # if the element is higher than 42, set the value to True, otherwise False: if element > 42: filter_arr.append(True) else: filter_arr.append(False) newarr = arr[filter_arr] print(filter_arr) print(newarr) Try it Yourself »
🌐
LabEx
labex.io › tutorials › python-how-to-filter-list-with-conditions-419442
Python - How to filter list with conditions
By understanding these basics, you'll be well-equipped to handle list filtering in your Python projects with LabEx's powerful learning resources. Python allows complex filtering using logical operators: ## Multiple condition filtering data = [10, 15, 20, 25, 30, 35, 40] filtered_data = [x for x in data if x > 20 and x < 40] print(filtered_data) ## Output: [25, 30, 35]
Find elsewhere
🌐
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 -

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 relating to a particular sportsperson's characteristics:

@dataclass
class Player:
    id: int
    first_name: str
    last_name: str
    age: int
    height: int
    weight: int
    team: int
    games_played: int
    ...

If I create a small (~500) length list of these objects and then want to filter on multiple conditions, what's the best way for me to do that?

Of course, in a one off situation I could write something like:

filtered = [player for player in player_list if 20 <= player.age < 25 and player.height > 180 and player.team == "Rovers"]

This gives me the flexibility to filter exactly how I'd like but it's not the most glamorous solution in my opinion, especially if I want to try out lots of different filters.

I had a thought that this might be easier to by creating something like a PlayerFilter class which can be instantiated and then have filters added to a dict attribute or similar, and then can be applied to a list of players and return the filtered list. This seems more Pythonic to me but also seems slightly overkill and I'm looking for the most straightforward and intuitive way to filter these values. I'm imagining if a random python user was to use my package with this filter implementation, I'm not sure if that would make sense.

Is the complexity a side effect of using a list of objects to store my data as opposed to something like a dataframe? I've considered this too but I want to maintain the ability to call the methods that I've created for my custom player class on any filtered output.

Let me know what you think!

🌐
Spark By {Examples}
sparkbyexamples.com › home › python › filter elements from python list
Filter Elements from Python List - Spark By {Examples}
May 31, 2024 - The filter() is a built-in function in Python that is used to filter the elements from the iterable object like list, set e.t.c. This function will directly filter the elements in a list by taking the condition as a parameter.
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-filter-list-by-boolean-list
Python | Filter list by Boolean list - GeeksforGeeks
July 12, 2025 - Check if the current element of my_list should be included in the filtered list by checking the corresponding boolean value in bool_list. If the boolean value is True, include the current element in the filtered list using the append() method or a list comprehension with an if condition.
🌐
IONOS UK
ionos.co.uk › digital guide › websites › web development › python filter function
What is Python’s filter function and how to use it
May 26, 2025 - The filter() function in Python lets you apply a condition to an iterable and select the elements that satisfy the condition. What follows is an iterator that contains the filtered results.
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

🌐
Byby
byby.dev › py-filter-a-list
How to filter a list in Python
# Given list of numbers numbers ... to the list of numbers even_numbers = list(filter(is_even, numbers)) print(even_numbers) # [2, 4, 6, 8, 10] The filter() function can be used in conjunction with a lambda function, as this allows the filtering criteria to be quickly defined ...
🌐
Finxter
blog.finxter.com › python-filter-list-based-on-another-list
Python Filter List Based on Another List – Be on the Right Side of Change
February 5, 2024 - List comprehension and the filter() function provide a clear and Pythonic way to achieve the same with or without order preserved. itertools.filterfalse() is a useful addition when you want to filter based on a condition for exclusion.
🌐
Ansible
docs.ansible.com › ansible › latest › playbook_guide › playbooks_filters.html
Using filters to manipulate data — Ansible Community Documentation
You can also use Python methods to transform data. You can create custom Ansible filters as plugins, though we generally welcome new filters into the ansible-core repo so everyone can use them. Because templating happens on the Ansible control node, not on the target host, filters execute on the control node and transform data locally. Filters can help you manage missing or undefined variables by ...
🌐
Simplilearn
simplilearn.com › home › resources › software development › filter in python: an introduction to filter() function [with examples]
Filter in Python: An Introduction to Filter() Function [with Examples]
July 10, 2024 - Filter in python is used to filter the given sequence with the help of a function that tests each element in the iterable to be true or not. Learn more now!
Address   5851 Legacy Circle, 6th Floor, Plano, TX 75024 United States
🌐
Packetswitch
packetswitch.co.uk › filtering-lists-based-on-conditions-in-ansible
Filtering Lists Based on Conditions in Ansible
January 1, 2024 - In this blog post, we're going to look at how to filter lists in Ansible. Filtering is a key skill when working with lists, as it lets you sort through and find exactly what you need.
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']
🌐
Python.org
discuss.python.org › ideas
Conditional loop filtering - Ideas - Discussions on Python.org
April 18, 2023 - Python comprehension expressions have filtering built in: [thing.foo for thing in bunch_of_things if thing.bar > 42] But in regular loops we need to do this: for thing in bunch_of_things: if thing.bar > 42: …