-3

What is the most pythonic way to return true if a list is not empty?

def fun(x):
    return x != []

Given some function called fun where we pass in a list x. List could look like [] or [1,3,4].

I want to return True if the list is not empty. Am I doing that in the most pythonic way?

The reason I ask is because when I do return x is not None instead of return x != [] I get a different answer. I guess this is because empty list is not considered null?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Dinero
  • 1,070
  • 2
  • 19
  • 44

1 Answers1

1

You can check the length of the list to see how many items are inside:

def fun(x):
    return len(x) > 0

Or you can cast bool to be more pythonic:

def fun(x):
    return bool(x)
creed
  • 1,409
  • 1
  • 9
  • 18