Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lists are the same but not considered equal?

novice at Python encountering a problem testing for equality. I have a list of lists, states[]; each state contains x, in this specific case x=3, Boolean values. In my program, I generate a list of Boolean values, the first three of which correspond to a state[i]. I loop through the list of states testing for equality (one of them is certainly correct as all possible boolean permutations are in states, but equality is never detected. No clue why, here is some code I modified to test it:

 temp1 = []
 for boolean in aggregate:
     temp1.append(boolean)
 if len(temp1) == len(propositions):
    break
 print temp1
 print states[0]
 if temp1 == states[0]:
     print 'True'
 else:
     print 'False'

In this case, the length of propisitons is 3. The output I get from this code is:

[True, True, True]
(True, True, True)
False

I'm guessing this has to do with the difference in brackets? Something to do with the fact that states[0] is a list within a list? Cheers.

like image 372
Bergy24 Avatar asked Nov 19 '15 15:11

Bergy24


People also ask

How do you check if two lists are exactly the same?

Use == operator to check if two lists are exactly equal It is the easiest and quickest way to check if both the lists are exactly equal. But it is good to know some other options too.

Are two lists equal?

In other words, two lists are defined to be equal if they contain the same elements in the same order.

How do you compare two lists with the same value?

sort() and == operator. The list. sort() method sorts the two lists and the == operator compares the two lists item by item which means they have equal data items at equal positions. This checks if the list contains equal data item values but it does not take into account the order of elements in the list.

How do you check if all values in a list are equal Python?

You can convert the list to a set. A set cannot have duplicates. So if all the elements in the original list are identical, the set will have just one element. if len(set(input_list)) == 1: # input_list has all identical elements.


1 Answers

You are comparing a tuple (True, True, True) against a list [True, True, True]

Of course they're different.

Try casting your list to tuple on-the-go, to compare:

temp1 = []
for boolean in aggregate:
    temp1.append(boolean)
if len(temp1) == len(propositions):
   break
print temp1
print states[0]
if tuple(temp1) == states[0]:
    print 'True'
else:
    print 'False'

Or casting your tuple to list on-the-go, to compare:

temp1 = []
for boolean in aggregate:
    temp1.append(boolean)
if len(temp1) == len(propositions):
   break
print temp1
print states[0]
if temp1 == list(states[0]):
    print 'True'
else:
    print 'False'

Output:

[True, True, True]
(True, True, True)
True
like image 127
Andrés Pérez-Albela H. Avatar answered Oct 07 '22 15:10

Andrés Pérez-Albela H.