Better way to do this dict comprehesion

Peter Otten __peter__ at web.de
Wed Mar 8 05:36:46 EST 2017


Sayth Renshaw wrote:

> Peter I really like this
> 
> The complete code:
> 
>>>> from collections import Counter
>>>> def find_it(seq):
> ...     [result] = [k for k, v in Counter(seq).items() if v % 3 == 0]
> ...     return result
> ...
>>>> test_seq = [20,1,-1,2,-2,3,3,5,5,1,2,4,20,4,-1,-2,5]
>>>> find_it(test_seq)
> 
> But what may be the smallest thing in this i had no idea I could do
> [result] = blah and get a generator on the return variable that seems
> insane.

Usually this is done with tuples

>>> left, sep, right = "foo.bar".partition(".")  # looks familiar?

rather than the alternative spelling

>>> [left, sep, right] = "foo.bar".partition(".")

However, a 1-tuple is just a trailing comma and easy to overlook, so i 
prefer

>>> items = [42]
>>> [foo] = items
>>> foo
42

over

>>> bar, = items
>>> bar
42





More information about the Python-list mailing list