[Tutor] Sequence Comparison
Danny Yoo
dyoo at hkn.eecs.berkeley.edu
Mon Jan 12 13:41:01 EST 2004
On Mon, 12 Jan 2004, Hameed Khan wrote:
> i was reading the Sequence comparison section of python documentation.
> but i really did not understand from it. if anyne of you can explain it
> to me then it will be very kind of you. the below is the examples with
> the questions i have in mind.
>
> >>> (1, 2, 3) < (1, 2, 4)
> True
> # Q.1 why it returns True when 1 is not lower then 1
> and 2 is not lower then 2. only 3 is lower then 4
^^^^^^^^^^^^^^^^^^^^^^
Hi Hameed,
That's exactly right. *grin* Python is doing a lexicographical
"dictionary" based sort.
You should have already seen this kind of sort before, in a regular
English dictionary. Say that we have two words, like "abc" and "abd".
If those were real words, which one would come first in a dictionary?
And why?
A more concrete example: think about the words "account" and "accountant".
Which one would come first in a dictionary, and why?
The tuples above are being sorted for the same reason.
> >>> (1, 2, 3, 4) < (1, 2, 4)
> True
> # the above 2 question (Q.1 and Q.2) applies to this
> comparison because this tuples have different sizes
Imagine that the system has two arrows pointed to the first components of
each item:
(1, 2, 3, 4) (1, 2, 4)
^ ^
A B
Let's call them Arrow A and Arrow B. If Arrows A and B are pointed to the
same thing, they'll move to the right one place:
(1, 2, 3, 4) (1, 2, 4)
^ ^
A B
Again, they point to the same thing. Let's move Arrows A and B again:
(1, 2, 3, 4) (1, 2, 4)
^ ^
A B
3 is less than 4, so (1, 2, 3, 4) is less than (1, 2, 4).
Does this make sense so far?
> >>> (1, 2) < (1, 2, -1)
> True
Let's use the arrow notation again:
(1, 2) (1, 2, -1)
^ ^
A B
Equal. Move the arrows to the right one:
(1, 2) (1, 2, -1)
^ ^
A B
Equal again. Let's move the arrows to the right again:
(1, 2) (1, 2, -1)
^ ^
A B
Arrow A has fallen off! In this case, (1, 2) is less than (1, 2, -1)
because its arrow has fallen off first.
> # i understand it a little bit that the elements of second tuple
> converted to the type of elements of first tuple and then compared but
> what if we compare
>
> (1,"string",3) == (1.0,2.0,3.0)
Good question. The equality (==) comparison between a string and a number
is always False, according to the Python language spec. According to:
http://www.python.org/doc/current/ref/comparisons.html
"""The operators <, >, ==, >=, <=, and != compare the values of two
objects. The objects need not have the same type. If both are numbers,
they are converted to a common type. Otherwise, objects of different types
always compare unequal, and are ordered consistently but arbitrarily."""
So we will get a False value off:
"string" == 2.0
And that's what forces:
(1, "string", 3) == (1.0, 2.0, 3.0)
to evaluate to False.
Please feel free to ask more questions. Hope this helps!
More information about the Tutor
mailing list