g = [i for i in list if x == 3] -> g = []; for i in list: if x == 3: g.append(i);
How could that be improved? That's 3-4 LOC minimum in any other language
My main grip is python's ternary operators, since the True value is evaluated before the condition, if you are doing ternaries on things that might throw exceptions the False value has to come first
value = 0 if key not in dic else dic[key] * 5
rather than (throws indexerror if key isn't in dic)
value = dic[key] * 5 if key in dic else 0
dic = {k: v for k, v in dic.items() if k in other_dic and v == "bar"}
> "How could that be improved? That's 3-4 LOC minimum in any other language"If I'm understanding the comprehension correctly,
(into {} (filter (fn [[k v]] (and (get other-dic k) (= v "bar"))) dic))
Though, for readability, I'd likely write it as: (->> dic
(filter (fn [[k v]]
(and (get other-dic k)
(= v "bar"))))
(into {}))
Legibility is in the eye of the beholder.(for) k, v in dic.items()
which is just
k, v = (<key>, <value>) for every key value pair in the dictionary
I posted due to your claim regarding all other languages necessitating increased verbosity. I should have left it lie, as I didn't intend to promote a language war, just to post a counter example. My apologies.
dic = dic.where((k, v) => k in other_dic and v == "bar").todict()
dic.iter().filter(|k, v| other_dic.contains(k) && v == "bar").collect();
it's one line, though I'd format it as 3 for readability (list comprehension is hard to read and functional style composes better.
They seem to exist only to do lots of stuff in one single line of code. You end up with totally impenetrable unreadable perl-esq garbage write-once-read-never code that is too clever for its own good. And people say python is easy to learn and good for beginners...!
A better approach would be something like Java Streams/.net Lync/RxX pattern IMO. Explicit, clear, no magic, logical.