Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List comprehension : is there a concise way to refer to the initial expression in the if condition?

I am trying to write a pretty simple list comprehension of the form

[initial-expression for name in collection if condition(initial-expression)]

But I am facing a case where intial expression is embedding some 'advanced' logic I do not want to duplicate in the if condition.

Verbose solution

At this point, I wrote :

[alias for alias in [initial-expression for name in collection]
 if condition(alias)]

Since the initial expression (in the outermost list comprehension) is the identity, it seems overkill.

Is there a common way to refer to an initial expression in the if condition using some symbolic name ?

like image 354
Ad N Avatar asked Sep 06 '25 00:09

Ad N


2 Answers

Yup, it's called filter and map :)

filter(condition, map(lambda name: initial-expression, collection))
like image 174
Viktor Kerkez Avatar answered Sep 07 '25 20:09

Viktor Kerkez


In practice, you should go with your "verbose" solution. There is one improvement I would make for the sake of code clarity and efficiency.

Change:

mylist = [alias for 
          alias in [initial_expression for
                    name in collection]
          if condition(alias)]

to

aliases = (initial_expression for name in collection)
mylist = [alias for alias in aliases if condition(alias)]

or

aliases = (initial_expression for name in collection)
mylist = list(filter(condition, aliases))
like image 21
Joel Cornett Avatar answered Sep 07 '25 20:09

Joel Cornett