Home > Net >  Why below code works when 2 conditions "==" but give empty list same code has 2 conditions
Why below code works when 2 conditions "==" but give empty list same code has 2 conditions

Time:12-19

d1 = [{"name": "a", "author": "b", "read": False},
      {"name": "c", "author": "b", "read": False},
      {"name": "b", "author": "b", "read": False}]

temp = []

for i in range(len(d1)):
    if d1[i]['name'] != "a" and d1[i]['author'] != "b":
        temp.append(d1[i])

print(temp) # RESULT []
d1 = [{"name": "a", "author": "b", "read": False},
      {"name": "c", "author": "b", "read": False},
      {"name": "b", "author": "b", "read": False}]

temp = []

for i in range(len(d1)):
    if d1[i]['name'] == "a" and d1[i]['author'] == "b":
        temp.append(d1[i])

print(temp) # RESULT [{'name': 'a', 'author': 'b', 'read': False}]

In this case: if d1[i]['name'] != "a" and d1[i]['author'] != "b" I expect it should append only those lists that doesn't match condition.

CodePudding user response:

The way you have written the code gives the expected results. You are naturally interpreting the code as it is written. So if name is NOT "a" AND author is NOT "b" then do the next step. Both logical statements need to be True to continue.. however because author is always "b" the condition will always be false.

Consider the following evaluation of Boolean operations and conditions

What you currently have

>>> (not False) and (not True)

Result False - The code block doesnt run

What I think you are expecting

>>> not ( False and True)

Result True

Or written in the context of your code:

if not ( d1[i]['name'] == "a" and d1[i]['author'] == "b" ) :

  • Related