What's your favorite Python idiom?

twitter logo github logo ・1 min read

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:
    print(x)

Or:

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

What's the one you most love? 💖🐍

twitter logo DISCUSS (5)
markdown guide
 
# 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.

 

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

 

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

 

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.

 

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

[x for y in z if -1 < y < 1]
Classic DEV Post from Apr 15

The Many Flavors of Technical Presentations

Learn about various technical presentation formats to choose the best one for you

Jonatas Baldin profile image
a human being

dev.to is where software developers stay in the loop and avoid career stagnation.

Sign up (for free)