24

I'm translating some of my Python code to Scala, and I was wondering if there's an equivalent to Python's list-comprehension:

[x for x in list if x!=somevalue]

Essentially I'm trying to remove certain elements from the list if it matches.

smci
  • 29,564
  • 18
  • 109
  • 144
Stupid.Fat.Cat
  • 9,713
  • 18
  • 73
  • 133

1 Answers1

35

The closest analogue to a Python list comprehension would be

for (x <- list if x != somevalue) yield x

But since you're what you're doing is filtering, you might as well just use the filter method

list.filter(_ != somevalue)

or

list.filterNot(_ == somevalue)
Chris Martin
  • 29,484
  • 8
  • 71
  • 131
  • 2
    @Shelby.S by the way, former two [will be desugared to the identical code](http://stackoverflow.com/a/1059501/298389) – om-nom-nom Jun 28 '13 at 11:10