Hacker News new | ask | show | jobs
by claytonjy 1992 days ago
As another point of comparison, as of python 3.8 you can do this in one list comp without nesting or double-computing areas with the walrus:

    result = [area for x,y in zip(heights,widths) if (area := to_area(x,y)) > 10]
I don't think that's very easy to read; I'd opt for two list comps like

    areas = [to_area(x,y) for x,y in zip(heights,widths)]
    result = [area for area in areas if area > 10]
But I agree with OP that map+filter is easier to read.
2 comments

I agree. My main problem is I don't want intermediary variables floating around. Especially something like "areas". If python localized variables to a blocked namespace, I wouldn't mind

In scala:

---

val widths = Seq(1,2,3)

val heights = Seq(4,5,6)

widths.zip(heights).foreach { case (w, h) => {

  val area = w * h

  if (area > 10) {

    println(s"Area: ${area}")

  }
}}

println(area) // error: not found: value area

You can do this without the walrus in a one liner as well, I believe:

    [area for area in (to_area(x, y) for x, y in zip(h, w)) if area > 10]

or generally, you can take a multiline statement like the one you have and replace named value with its expression. Add some indentation and it's not too bad:

    [area for area in 
     (to_area(x, y) for x, y in zip(h, w))
     if area > 10]