DEV Community

Discussion on: In Your Opinion, What Makes Code Pythonic?

Collapse
 
rhymes profile image
rhymes • Edited

Actually, if we want to be super strict, filter, map and lambda are few of those things that aren't considered really Pythonic. Guido van Rossum wanted to remove all of them in Python 3, but then backtracked and only removed reduce. See The fate of reduce() in Python 3000 (dated 2005!!).

A more "pythonic" way to write that would be:

[w for w in words if len(w) == max(len(x) for x in words)]

or with a generation expression to avoid consuming all items eagerly:

(w for w in words if len(w) == max(len(x) for x in words))

or with a set comprehension to remove duplicates automatically

>>> words = ["a", "ab", "abcd", "b", "abcd"]
>>> [w for w in words if len(w) == max(len(x) for x in words)]
['abcd', 'abcd']
>>> {w for w in words if len(w) == max(len(x) for x in words)}
{'abcd'}