Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 718
Stupid.Fat.Cat Avatar asked Jun 28 '13 01:06

Stupid.Fat.Cat


People also ask

What is for comprehension in Scala?

Scala offers a lightweight notation for expressing sequence comprehensions. Comprehensions have the form for (enumerators) yield e , where enumerators refers to a semicolon-separated list of enumerators. An enumerator is either a generator which introduces new variables, or it is a filter.

What is faster than list comprehension Python?

For loops are faster than list comprehensions to run functions.

Which is faster lambda or list comprehension?

Actually, list comprehension is much clearer and faster than filter+lambda, but you can use whichever you find easier. The first thing is the function call overhead: as soon as you use a Python function (whether created by def or lambda) it is likely that the filter will be slower than the list comprehension.

What is the difference between list comprehension and lambda?

The difference between Lambda and List Comprehension. List Comprehension is used to create lists, Lambda is function that can process like other functions and thus return values or lists.


1 Answers

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) 
like image 176
Chris Martin Avatar answered Oct 07 '22 07:10

Chris Martin