0

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?

Jamiu S.
  • 5,257
  • 5
  • 12
  • 34
lin0258
  • 1
  • 1
  • 1
    0 is not a class. There is no such statement as "different instances of 0". And they are even the same object according to Python's small integer pool optimization. – Mechanic Pig Oct 01 '22 at 07:00
  • 1
    It sounds like you want to compare indexes, not values at those indexes. – quamrana Oct 01 '22 at 07:18
  • You can use `is` to check whether it is the same object; but in this case, both occurrences of `0` **actually are** the same object. Please see the linked duplicates. – Karl Knechtel Oct 07 '22 at 21:36

3 Answers3

1

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

JacekK
  • 623
  • 6
  • 11
0

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”)   
Olga
  • 146
  • 2
  • 6
0

It sounds like you want to compare indexes and not the values at those indexes.

This code does this by ignoring the container:

def compare(container, index1, index2):
    return index1 == index2

mylist = [0,1,2,0]
print(compare(mylist, 0, -1))

Output:

False

quamrana
  • 37,849
  • 12
  • 53
  • 71