DEV Community

loading...

Discussion on: What's your favorite Python idiom?

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.