loading...

What's your favorite Python idiom?

jonatasbaldin profile image Jonatas Baldin ・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? πŸ’–πŸ

Discussion

pic
Editor guide
Collapse
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.

Collapse
jonatasbaldin profile image
Jonatas Baldin Author

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

Collapse
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.

Collapse
bctnry profile image
Sebastian Higgins

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.

Collapse
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]