Stupid.Fat.Cat
Stupid.Fat.Cat

Reputation: 11295

Is there a Scala equivalent to Python's list comprehension?

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.

Upvotes: 25

Views: 11594

Answers (1)

Chris Martin
Chris Martin

Reputation: 30736

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)

Upvotes: 39

Related Questions