Reputation: 413
For some reason I am getting the lists to always be equal, even though when printed, you can see that they are not always equal.
It is returning True when the previous_list = [1,0,0,0,0] and the current_list = [0,0,0,0,0]
There are many questions regarding comparing lists, but I have tried many different answers like the cmp(), but it returns 0 as well. So why does it say its the same but when printed, you can see they are different?
while True:
previous_status_list = current_status_list
print str(previous_status_list) + " PREVIOUS"
if door_status == 'closed' and status_for_loop == 'closed':
overall_status_list[0] = 0
else:
overall_status_list[0] = 1
if door_locked_status == False:
overall_status_list[1] = 0
else:
overall_status_list[1] = 1
if door_breached_status == False:
overall_status_list[2] = 0
else:
overall_status_list[2] = 1
if door_propped_status == False:
overall_status_list[3] = 0
else:
overall_status_list[3] = 1
if egress_status == False:
overall_status_list[4] = 0
else:
overall_status_list[4] = 1
current_status_list = overall_status_list
if current_status_list == previous_status_list:
print 'TRUE'
else:
print 'False'
print str(current_status_list) + " CURRENT"
sleeptime.sleep(3)
Upvotes: 1
Views: 65
Reputation: 1121834
You are not comparing two different lists, as you didn't make a copy:
previous_status_list = current_status_list
previous_status_list
and current_status_list
reference the same object. Altering the list through one reference alters the other:
Create a (shallow) copy instead:
previous_status_list = current_status_list[:]
Demo:
>>> current_status_list = ['foo', 'bar', 'baz']
>>> previous_status_list = current_status_list
>>> current_status_list is previous_status_list
True
>>> current_status_list.append('spam')
>>> previous_status_list
['foo', 'bar', 'baz', 'spam']
>>> previous_status_list = current_status_list[:] # shallow copy
>>> current_status_list is previous_status_list
False
>>> current_status_list.append('ham')
>>> current_status_list
['foo', 'bar', 'baz', 'spam', 'ham']
>>> previous_status_list
['foo', 'bar', 'baz', 'spam']
Note how the is
identity operator shows that the two names refer to the same object, until a copy is created. Also, changes to the list through current_status_list
show up in previous_status_list
until such time that a copy is created.
Upvotes: 4