1

Is there something similar to a as keyword in list comprehensions?

Example: instead of

L = [foo(bar(baz(bla(x)))) for x in X if foo(bar(baz(bla(x)))) == 1]

it would be:

L = [foo(bar(baz(bla(x)))) as y for x in X if y == 1]
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Basj
  • 41,386
  • 99
  • 383
  • 673
  • 1
    If you are using 3.8 you can use the [walrus operator](https://www.python.org/dev/peps/pep-0572/) – Sayandip Dutta May 28 '20 at 11:24
  • `L = [1 for x in X if 1 == foo(bar(baz(bla(x)))) ]` would work in this case ... but walrussing is probably the better way – Patrick Artner May 28 '20 at 11:25
  • No, there isn't an `as` keyword, if you are on Python 3.8 you can use an assignment expression, i.e. the "walrus operator". If not, you can always just use the equivalent for-loop – juanpa.arrivillaga May 28 '20 at 11:26
  • `list(filter(lambda x: x == 1, (foo(...) for x in X)))` – deceze May 28 '20 at 11:29
  • @PatrickArtner Right, but this is because I took a trivial case where `foo(bar(baz(bla(x))))` is the same on both sides. If there is one less function on one side, `[1 for ...` does not work anymore. – Basj May 28 '20 at 11:33

1 Answers1

1

In python 3.8 you can use walrus operator to do this:

>>> L = [y for x in X if (y := foo(bar(baz(bla(x))))) == 1]
Sayandip Dutta
  • 15,602
  • 4
  • 23
  • 52