Online Book Reader

Home Category

Learning Python - Mark Lutz [129]

By Root 1607 0

* * *

Note


Comparison and sorts in 3.0: In Python 2.6 and earlier, comparisons of differently typed objects (e.g., a string and a list) work—the language defines a fixed ordering among different types, which is deterministic, if not aesthetically pleasing. That is, the ordering is based on the names of the types involved: all integers are less than all strings, for example, because "int" is less than "str". Comparisons never automatically convert types, except when comparing numeric type objects.

In Python 3.0, this has changed: comparison of mixed types raises an exception instead of falling back on the fixed cross-type ordering. Because sorting uses comparisons internally, this means that [1, 2, 'spam'].sort() succeeds in Python 2.X but will raise an exception in Python 3.0 and later.

Python 3.0 also no longer supports passing in an arbitrary comparison function to sorts, to implement different orderings. The suggested workaround is to use the key=func keyword argument to code value transformations during the sort, and use the reverse=True keyword argument to change the sort order to descending. These were the typical uses of comparison functions in the past.

* * *

One warning here: beware that append and sort change the associated list object in-place, but don’t return the list as a result (technically, they both return a value called None). If you say something like L=L.append(X), you won’t get the modified value of L (in fact, you’ll lose the reference to the list altogether!). When you use attributes such as append and sort, objects are changed as a side effect, so there’s no reason to reassign.

Partly because of such constraints, sorting is also available in recent Pythons as a built-in function, which sorts any collection (not just lists) and returns a new list for the result (instead of in-place changes):

>>> L = ['abc', 'ABD', 'aBe']

>>> sorted(L, key=str.lower, reverse=True) # Sorting built-in

['aBe', 'ABD', 'abc']

>>> L = ['abc', 'ABD', 'aBe']

>>> sorted([x.lower() for x in L], reverse=True) # Pretransform items: differs!

['abe', 'abd', 'abc']

Notice the last example here—we can convert to lowercase prior to the sort with a list comprehension, but the result does not contain the original list’s values as it does with the key argument. The latter is applied temporarily during the sort, instead of changing the values to be sorted. As we move along, we’ll see contexts in which the sorted built-in can sometimes be more useful than the sort method.

Like strings, lists have other methods that perform other specialized operations. For instance, reverse reverses the list in-place, and the extend and pop methods insert multiple items at the end of and delete an item from the end of the list, respectively. There is also a reversed built-in function that works much like sorted, but it must be wrapped in a list call because it’s an iterator (more on iterators later):

>>> L = [1, 2]

>>> L.extend([3,4,5]) # Add many items at end

>>> L

[1, 2, 3, 4, 5]

>>> L.pop() # Delete and return last item

5

>>> L

[1, 2, 3, 4]

>>> L.reverse() # In-place reversal method

>>> L

[4, 3, 2, 1]

>>> list(reversed(L)) # Reversal built-in with a result

[1, 2, 3, 4]

In some types of programs, the list pop method used here is often used in conjunction with append to implement a quick last-in-first-out (LIFO) stack structure. The end of the list serves as the top of the stack:

>>> L = []

>>> L.append(1) # Push onto stack

>>> L.append(2)

>>> L

[1, 2]

>>> L.pop() # Pop off stack

2

>>> L

[1]

The pop method also accepts an optional offset of the item to be deleted and returned (the default is the last item). Other list methods remove an item by value (remove), insert an item at an offset (insert), search for an item’s offset (index), and more:

>>> L = ['spam', 'eggs', 'ham']

>>> L.index('eggs') # Index of an object

1

>>> L.insert(1, 'toast') # Insert at position

>>> L

['spam', 'toast', 'eggs', 'ham']

>>> L.remove('eggs') # Delete by value

>>> L

['spam', 'toast', 'ham']

>>> L.pop(1) #

Return Main Page Previous Page Next Page

®Online Book Reader