James
James

Reputation: 673

More concise way to filter a list?

If I have a list

a=[4, 5, 6]

as far as I know the simplest way to filter it is like:

[i for i in a if a<6]

Now I have just been introduced to dataframes, where for a dataframe like

df = pd.DataFrame({'a':[4, 5, 6], 'b':[7, 1, 2]})

I can apply a (row) filter just by specifying the element and the condition:

df[df['a']<6]

This seems more concise and maybe less confusing (once you get used to it) than the way to filter a list. Couldn't a list filter by applied by simply specifying a condition in the [], like

a[<6]

Obviously, it isn't implemented this way currently, but isn't the current method relatively verbose? Why couldn't it be simplified?

Upvotes: 1

Views: 117

Answers (3)

Robᵩ
Robᵩ

Reputation: 168616

You can't have exactly the syntax you're asking for, but if you want to create your own list class, you can have one just as succinct:

class List(list):
    def __lt__(self, other):
        return List(i for i in self if i < other)

a = List([4,5,6])
b = a < 6
assert b == [4,5]

Upvotes: 1

combinatorist
combinatorist

Reputation: 566

Yes, the python language could be built so that a[<6] did the filtering you want, but then every python programmer and every python compiler would have to learn that special syntax just to save a little source code in a few special cases: >, >=, ==, <=, <.

Pandas does something like that as you showed, but it is built for lots of numerical analysis, so that syntactic sugar may be more worth the cost. Also, pandas tends to provide lots of syntactic sugar inspired by the R language so it's not very idiomatic python.

Upvotes: 0

Chinny84
Chinny84

Reputation: 966

You have the simplest way above. However, you can use the following

filtered_list = filter(lambda k: k < 6, original_list)

This looks great, but I still have a soft spot for the list comprehension.

Upvotes: 1

Related Questions