Home > Blockchain >  How to refer to a specific object in a list, not all the objects that are the same value but differe
How to refer to a specific object in a list, not all the objects that are the same value but differe

Time:10-01

For example, mylist = [0,1,2,0] I want mylist[0] == mylist[-1] to output False as it is a different instance of 0, but it is true because they are both zeroes. Is there a way to do this?

CodePudding user response:

In your case the mylist[0] and mylist[-1] are not only equal but also the same (same object in memory)

>>> mylist = [0,1,2,0]
>>> mylist[0] == mylist[-1]
True
>>> mylist[0] is mylist[-1]
True
>>> id(mylist[0])
140736735811200
>>> id(mylist[-1])
140736735811200
>>> 

You should not receive a False.

You can read these articles to better understand this topic: https://realpython.com/python-is-identity-vs-equality/, https://anvil.works/articles/pointers-in-my-python-1

CodePudding user response:

I guess you want to compare values and their indexes.

mylist = [0,1,2,3,0]
if mylist[0] == mylist[-1] and mylist.index(mylist[0]) == mylist.index(mylist[-1]):
    print(“True”)
else:
    print(“False”)   
  • Related