Is comparing numbers a Python bug?

Deep inside my code, nested, if inside a nested inside a class method, I compare a specific index value to the length of a specific list to check if I can access that index. The code looks something like this:

if t.index_value < len(work_list):
    ... do stuff ...
else:
    ... print some error ...

      

For clarification, it index_value

is at least null (confirmed elsewhere). To my surprise, although I know the data is index_value

valid, the code continues to jump to the else: clause. I added ad-hoc debug code:

print('Checking whether '+str(t.index_value)+"<"+str(len(work_list)))

x = t.index_value
y = len(work_list)

print(x)
print(y)
print(x<y)

if t.index_value < len(work_list):
    ... do stuff ...
else:
    ... print some error ...

      

Below is the output:

>> Checking whether 3<4
>> 3
>> 4
>> False

      

Can anyone help me understand what's going on here?

Additional explanations:

  • work_list is a local variable created within the method
  • t - an instance of the class created within the method ( t = SomeClass()

    )

Update: The problem was that the type t.index_value

was UNICODE and not int. The reason was that I had deserialized the t content from a text file where the index_value is represented by a digit with a character. After I extracted it from the text, I immediately assigned it index_value

without passing it through the int () it should have done and that solved the problem.

I decided to keep the "controversial" title, even though this is clearly my fault and not Python, because people with the same problem can find it using this title.

+1


a source to share


2 answers


In my experience, what's the type of "t.index_value"? Maybe it's line "3".



>>> print '3' < 4
False

      

+8


a source


To display values ​​that can be of different types than you expect (e.g. a string, not a number as kcwu suggests), use repr(x)

etc.



+2


a source







All Articles