0

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?

Cardstdani
  • 4,999
  • 3
  • 12
  • 31
  • 1
    To expand on answer by @aberkb - it will work if instead of `.sort()` method you use `sorted()` function, e.g. `sorted(list1) == sorted(list2)`. – buran Oct 31 '21 at 11:36
  • Python `sort` is in-place sorting. Same question has been asked many times here: https://stackoverflow.com/questions/22442378/what-is-the-difference-between-sortedlist-vs-list-sort – Daniel Hao Oct 31 '21 at 12:35

3 Answers3

8

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

aberkb
  • 664
  • 6
  • 12
0

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

ddor254
  • 1,570
  • 1
  • 12
  • 28
-1

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))
Cardstdani
  • 4,999
  • 3
  • 12
  • 31