Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I test to see if a defaultdict(set) is empty in Python

Tags:

python

set

I have a defaultdict fishparts = defaultdict(set) that has elements assigned to it but is periodically cleared using .clear() What I need is some way to test if the set is clear or not so I can do some other work in the function below.

def bandpassUniqReset5(player,x,epochtime):
    score = 0
    if lastplay[player] < (epochtime - 300):
        fishparts[player].clear()
    lastplay[player] = epochtime
    for e in x:
        # right here I want to do a check to see if the "if" conditional above has cleared fishparts[player] before I do the part below
        if e not in fishparts[player]:
            score += 1
        fishparts[player].add(e)
    return str(score)
like image 251
Mike Avatar asked Oct 17 '25 18:10

Mike


1 Answers

Sets, like all Python containers, are considered False when empty:

if not fishparts[player]:
    # this set is empty

See Truth Value Testing.

Demo:

>>> if not set(): print "I am empty"
... 
I am empty
>>> if set([1]): print "I am not empty"
... 
I am not empty
like image 112
Martijn Pieters Avatar answered Oct 20 '25 07:10

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!