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.
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.
In other words, two lists are defined to be equal if they contain the same elements in the same order.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With