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.

(4, True, 5)<br />

>>> (4, 2) < (3, 5) # tuple comparison<br />

False<br />

In the first example, the less than ( < ) operator took precedence over the comma delimiter intended<br />

for the tuples on each side of the less than sign. The result of the evaluation of 2 < 3 became the second<br />

element of a tuple. Properly enclosing the tuples enables the desired result.<br />

6.18.4. Single-Element Tuples<br />

Ever try to create a tuple with a single element? You tried it with lists, and it worked, but then you tried<br />

and tried with tuples, but you cannot seem to do it.<br />

>>> ['abc']<br />

['abc']<br />

>>> type(['abc']) # a list<br />

<br />

>>><br />

>>> ('xyz')<br />

'xyz'<br />

>>> type(('xyz')) # a string, not a tuple<br />

<br />

It probably does not help your case that the parentheses are also overloaded as the expression grouping<br />

operator. Parentheses around a single element take on that binding role rather than serving as a<br />

delimiter for tuples. The workaround is to place a trailing comma (,) after the first element to indicate<br />

that this is a tuple and not a grouping.<br />

>>> ('xyz',)<br />

('xyz',)<br />

6.18.5. Dictionary Keys<br />

Immutable objects have values that cannot be changed. That means that they will always hash to the<br />

same value. That is the requirement for an object being a valid dictionary key. As we will find out in the<br />

next chapter, keys must be hashable objects, and tuples meet that criteria. Lists are not eligible.<br />

<strong>Core</strong> Note: Lists versus Tuples

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

Saved successfully!

Ooh no, something went wrong!