1

I am not sure where to find the reference to explain the following

>>> 3<range(3)
True
>>> [1,2]<range(3)
False
>>> [1]<range(3)
False
>>> [4]<range(3)
False
>>> [4,1,2,3]<range(3)
False

Thank you!

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Qiang Li
  • 10,593
  • 21
  • 77
  • 148

1 Answers1

3

In Python 2, range() produces a list object. The first test compares two different types, at which point numbers always come before other types:

>>> range(3)
[0, 1, 2]
>>> 3 < []
True

The rest is just comparing lists against [0, 1, 2]; lists are compared lexicographically and 0 is lower than any of the first values in all your other tests.

Your initial value should be lower than 0:

>>> [-1] < range(3)
True

or, if it is equal, the next value should be lower than 1:

>>> [0, 0] < range(3)
True

etc.

See the Comparisons section of the expressions documentation:

Tuples and lists are compared lexicographically using comparison of corresponding elements. This means that to compare equal, each element must compare equal and the two sequences must be of the same type and have the same length.

Community
  • 1
  • 1
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343