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
  • 32,567
  • 20
  • 113
  • 146
Stupid.Fat.Cat
  • 10,755
  • 23
  • 83
  • 144

1 Answers1

37

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
  • 30,334
  • 10
  • 78
  • 137
  • 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