DEV Community

Jonatas Baldin
Jonatas Baldin

Posted on

What's your favorite Python idiom?

Hey there, how are you doing?

I'm collecting people's favorite Python idioms: Pythonic, elegant, battle-tested snippets:

# the `in` operator!
if x in l:
Enter fullscreen mode Exit fullscreen mode


# list comprehensions!
numbers = [1, 2,, 3]
l = [n * 2 for n in numbers]
Enter fullscreen mode Exit fullscreen mode

What's the one you most love? 💖🐍

Discussion (5)

ahferroin7 profile image
Austin S. Hemmelgarn
# l is a list

if l:
   # If we got here, l is not empty.

In short, empty lists in Python evaluate to false, non-empty lists evaluate to true. So you can just treat the list like a boolean to check if it's empty or not. This isn't a common situation to need to check because of how for loops work in Python, but it's still useful on some occasions.

jonatasbaldin profile image
Jonatas Baldin Author

Love how data structures in Python have falsy/truthy evaluations ❤️

ahferroin7 profile image
Austin S. Hemmelgarn

Agreed. I've never understood dynamically typed languages where container types unconditionally evaluate to true when used like a boolean.

bctnry profile image
Sebastian René Higgins • Edited on

Dict comprehension:

{i: x for i, x in enumerate([1, 2, 3])}
# returns {0: 1, 1: 2, 2: 3}

if you happen to have a bunch of object with some kind of an id field (like I do) you can do this:

{x['id']: x for x in [{'id': 3}, {'id': 4}, {'id': 5}]}
# returns {3: {'id': 3}, 4: {'id': 4}, 5: {'id': 5}}

which is sometimes pretty neat I think.

moopet profile image
Ben Sinclair

I like conditions in comprehensions, and I like two-way conditions, so:

[x for y in z if -1 < y < 1]