Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why below code works when 2 conditions "==" but give empty list same code has 2 conditions "!="?

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.

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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" ) :

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading