15.04.2013 Views

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

'abc' > 'xyz'<br />

False<br />

>>> 'abc' < 'xyz'<br />

True<br />

>>> [3, 'abc'] == ['abc', 3]<br />

False<br />

>>> [3, 'abc'] == [3, 'abc']<br />

True<br />

Also, unlike many other languages, multiple comparisons can be made on the same line, evaluated in<br />

left-to-right order:<br />

>>> 3 < 4 < 7 # same as ( 3 < 4 ) and ( 4 < 7 )<br />

True<br />

>>> 4 > 3 == 3 # same as ( 4 > 3 ) and ( 3 == 3 )<br />

True<br />

>>> 4 < 3 < 5 != 2 < 7<br />

False<br />

We would like to note here that comparisons are strictly between object values, meaning that the<br />

comparisons are between the data values and not the actual data objects themselves. For the latter, we<br />

will defer to the object identity comparison operators described next.<br />

4.5.2. Object Identity Comparison<br />

In addition to value comparisons, <strong>Python</strong> also supports the notion of directly comparing objects<br />

themselves. Objects can be assigned to other variables (by reference). Because each variable points to<br />

the same (shared) data object, any change effected through one variable will change the object and<br />

hence be reflected through all references to the same object.<br />

In order to understand this, you will have to think of variables as linking to objects now and be less<br />

concerned with the values themselves. Let us take a look at three examples.<br />

Example 1: foo1 and foo2 reference the same object<br />

foo1 = foo2 = 4.3<br />

When you look at this statement from the value point of view, it appears that you are performing a<br />

multiple assignment and assigning the numeric value of 4.3 to both the foo1 and foo2 variables. This is<br />

true to a certain degree, but upon lifting the covers, you will find that a numeric object with the contents<br />

or value of 4.3 has been created. Then that object's reference is assigned to both foo1 and foo2,<br />

resulting in both foo1 and foo2 aliased to the same object. Figure 4-1 shows an object with two<br />

references.<br />

Figure 4-1. foo1 and foo2 reference the same object

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!