How to check if tuple having a list or dictionary is empty
Asked Answered
U

2

5

I have a tuple:

details = ({}, [])

As there is no data in the following tuple I want to return a null response. For this I am writing:

 if not details:
      return Response({})
 else:
    print "Not null"

But this does not seem to work as it is always going in the else part and printing not null. I am new to python. Any help is appreciated.

Uniform answered 7/2, 2018 at 10:3 Comment(1)
if not any(details):Reclamation
C
11

Note: if you write:

if <expr>:
    pass

then Python will not check that <expr> == True, it will evaluate the truthiness of the <expr>. Objects have some sort of defined "truthiness" value. The truthiness of True and False are respectively True and False. For None, the truthiness is False, for numbers usually the truthiness is True if and only if the number is different from zero, for collections (tuples, sets, dictionaries, lists, etc.), the truthiness is True if the collection contains at least one element. By default custom classes have always True as truthiness, but by overriding the __bool__ (or __len__), one can define custom rules.

The truthiness of tuple is True given the tuple itself contains one or more items (and False otherwise). What these elements are, is irrelevant.

In case you want to check that at least one of the items of the tuple has truthiness True, we can use any(..):

if not any(details):  # all items are empty
    return Response({})
else:
    print "Not null"

So from the moment the list contains at least one element, or the dictonary, or both, the else case will fire, otherwise the if body will fire.

If we want to check that all elements in the tuple have truthiness True, we can use all(..):

if not all(details):  # one or more items are empty
    return Response({})
else:
    print "Not null"
Chiton answered 7/2, 2018 at 10:7 Comment(4)
Learned something new today. Thanks. Can you explain why details == True returns False, but if details: print('True') prints True in the prompt?Incredible
@MiniGunnR: because if <expr> does not check that <expr> == True, ut evaluates the truthiness.Chiton
Pretty detailed answerLemmy
Thank you.Great explanation.Uniform
A
0

The accepted answer implies that any does not perform a deep search for truth. This is demonstrated below:

not not [] # False (double negation as truthness detector).
not not ([],) # True
not not any(([],)) # False
not not any(([1],)) # True
not not any(([None],)) # Still True, as expected.
Antons answered 17/11, 2022 at 21:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.