user16713791
user16713791

Reputation: 129

Comparing two lists returns True even though it needs to return False

I'm trying to make a program that compares two lists and returns "True" if they're both have the same variables in it and "False" else.

The code is:

def are_lists_equall(list1, list2):
    if len(list1) == len(list2) and list1.sort() == list2.sort():
        return True
    else:
        return False

list1 = [0.6, 1, 2, 3]
list2 = [9, 0, 5, 10.5]
print(are_lists_equall(list1, list2))

And the output is:

True

Why is this happening?

Upvotes: 0

Views: 875

Answers (3)

aberkb
aberkb

Reputation: 674

their length is 4 so first one is true and The sort() method doesn't return any value. Rather, it changes the original list. its like

if 4 == 4 and None == None:

thats why its true and true

If you want to make sure that you compare those lists use sorted() method:

sorted(list1) == sorted(list2) will give you False

Upvotes: 8

Cardstdani
Cardstdani

Reputation: 5223

You should create temp variables with the values of both lists in order to sort and compare them:

def are_lists_equall(list1, list2):
    l1 = list1
    l1.sort()
    l2 = list2
    l2.sort()
    
    if l1 == l2:
        return True
    else:
        return False

list1 = [0.6, 1, 2, 3]
list2 = [9, 0, 5, 10.5]
print(are_lists_equall(list1, list2))

Upvotes: -1

ddor254
ddor254

Reputation: 1628

Hello and welcome to Stack overflow.

the sort method sort the list itself and does not return a sorted list, actually sort() return None.

so the length is equal and None == None -> therefore you are getting True.

you should write:

   def are_lists_equall(list1, list2):


    if len(list1) == len(list2):
       list1.sort()
       list2.sort()
       if list1 == list2:
          return True
       else:
          return False
    else:
       return False
   
   list1 = [1, 2, 3, 4]
   list2 = [2, 1, 3, 4] 
   print(are_lists_equall(list1, list2))

i suggest you read this great article as well : https://www.tutorialspoint.com/how-to-compare-two-lists-in-python

Upvotes: 0

Related Questions