ragardner
ragardner

Reputation: 1975

Python 3 if not condition simplification

Are these two condition checks the same? I can't think of how to check if they are the same

l1 = []
l2 = []

if not l1 and not l2:
    print ('y')

if not (l1 and l2):
    print ('y')

thanks to all who replied, I have done some basic timing to see which is faster

import time
l1 = []
l2 = []

st = time.time()
for i in range(100000000):
    if not l1 and not l2:
        pass
end = time.time()
print ('if not l1 and not l2: '+str(end-st))

st = time.time()
for i in range(100000000):
    if not (l1 or l2):
        pass
end = time.time()
print ('if not (l1 or l2): '+str(end-st))

prints:

if not l1 and not l2: 8.533874750137329
if not (l1 or l2): 7.91820216178894

Upvotes: 2

Views: 239

Answers (3)

developer_hatch
developer_hatch

Reputation: 16224

If you want to be the same, use or operation:

l1 = []
l2 = []

if not l1 and not l2:
    print ('y')

equivalent:

if not (l1 or l2):
    print ('y')

Upvotes: 1

Miriam Farber
Miriam Farber

Reputation: 19634

They are not the same. You need to modify the second condition as follows, so that they would be equivalent:

l1 = []
l2 = []

if not l1 and not l2:
    print ('y')

if not (l1 or l2):
    print ('y')

Upvotes: 2

wim
wim

Reputation: 362478

No, they are not the same. See De Morgan's laws.

A counter-example is:

l1 = [0]
l2 = []

Upvotes: 7

Related Questions