hundred_or_less_even_seconds = [
timedelta(seconds=it)
for it in range(1, 1001)
if it <= 100 and it % 2 == 0
]
Also, I don't know Kotlin well enough, but is what you wrote going to be efficient? The Python version iterates once and creates one list (and you can actually turn it into a generator and make zero lists just by swapping the square brackets for parens); to my untrained eye, it looks like the Kotlin version is going to do more iteration and make four separate lists, three of which are just garbage to be thrown away immediately. Here that probably doesn't matter, but in other cases it might be a big problem; is there an easy/idiomatic way to avoid that?Also the map function lets you perform any operations in it. It was a simple example but you could need to perform something slightly more complex than using another standard library function.
I particularly like Kotlin's scope functions:
I do prefer python over kotlin but IMHO semantically they're both beautiful and some of the least frictive languages I've ever used
.map(blah(x,y), |z|, if let (x,y) == conditional(z))
foos = (make_foo(bar) for bar in bars)
acceptable_foos = (foo for foo in foos if acceptable(foo))
...
Depending on your circumstances, this may or may not be awkward (coming up with temporary names can be hard), or may or may not be a good idea anyway (naming things can help make the code more self-documenting). I can't reckon how it could become unreadable, per se - what do you mean by that?Someone with kotlin experience could comment too, But I don't think it creates four separate lists. The last map function iterates and asks for element from previous function which asks for element from its parent function. So there is only one list.
import datetime
import pandas as pd
hundred_or_less_even_seconds = (
pd.Series(range(1, 1000))
.loc[lambda x: x <= 100]
.loc[lambda x: x % 2 == 0]
.map(lambda x: datetime.timedelta(seconds=x))
.to_list()
)The main difference imo is that kotlin uses more "syntax" while python uses more "English" to express the same thing. Also the half-open interval for range but that's an arbitrary decision that benefits some cases more than others (although my preference is the closed interval)
[2*x for x in range(n + 1) if x <= 100]
Here's set notation: {2*x | x in 0..n, x <= 100}
So it reads pretty easily for those of us used to set notation. Haskell is even more similar to set notation: [2*x | x <- [0..n], x <= 100]
As a simple example using only two collection functions I find it much easier to read
than But there are tons of helper functions in the collections library to express that in a variety of different ways. But not in a gross code golf way, with clearly named functionsTheres just so much built in https://kotlinlang.org/docs/collections-overview.html
Having lambdas built into the language from the start leads to a ton of expressibility I miss when using python