Section 6.13. Built-in Functions


6.13. Built-in Functions

6.13.1. Standard Type Functions

cmp()

In Section 4.6.1, we introduced the cmp() built-in function with examples of comparing numbers and strings. But how would cmp() work with other objects such as lists and tuples, which can contain not only numbers and strings, but other objects like lists, tuples, dictionaries, and even user-created objects?

>>> list1, list2 = [123, 'xyz'], [456, 'abc'] >>> cmp(list1, list2) -1 >>> >>> cmp(list2, list1) 1 >>> list3 = list2 + [789] >>> list3 [456, 'abc', 789] >>> >>> cmp(list2, list3) -1


Compares are straightforward if we are comparing two objects of the same type. For numbers and strings, the direct values are compared, which is trivial. For sequence types, comparisons are somewhat more complex, but similar in manner. Python tries its best to make a fair comparison when one cannot be made, i.e., when there is no relationship between the objects or when types do not even have compare functions, then all bets are off as far as obtaining a "logical" decision.

Before such a drastic state is arrived at, more safe-and-sane ways to determine an inequality are attempted. How does the algorithm start? As we mentioned briefly above, elements of lists are iterated over. If these elements are of the same type, the standard compare for that type is performed. As soon as an inequality is determined in an element compare, that result becomes the result of the list compare. Again, these element compares are for elements of the same type. As we explained earlier, when the objects are different, performing an accurate or true comparison becomes a risky proposition.

When we compare list1 with list2, both lists are iterated over. The first true comparison takes place between the first elements of both lists, i.e., 123 vs. 456. Since 123 < 456, list1 is deemed "smaller."

If both values are the same, then iteration through the sequences continues until either a mismatch is found, or the end of the shorter sequence is reached. In the latter case, the sequence with more elements is deemed "greater." That is the reason why we arrived above at list2 < list3. Tuples are compared using the same algorithm. We leave this section with a summary of the algorithm highlights:

  1. Compare elements of both lists.

  2. If elements are of the same type, perform the compare and return the result.

  3. If elements are different types, check to see if they are numbers.

    1. If numbers, perform numeric coercion if necessary and compare.

    2. If either element is a number, then the other element is "larger" (numbers are "smallest").

    3. Otherwise, types are sorted alphabetically by name.

  4. If we reach the end of one of the lists, the longer list is "larger."

  5. If we exhaust both lists and share the same data, the result is a tie, meaning that 0 is returned.

6.13.2. Sequence Type Functions

len()

For strings, len() gives the total length of the string, as in the number of characters. For lists (and tuples), it will not surprise you that len() returns the number of elements in the list (or tuple). Container objects found within count as a single item. Our examples below use some of the lists already defined above in previous sections.

>>> len(num_list) 4 >>> >>> len(num_list*2) 8


max() and min()

max() and min() did not have a significant amount of usage for strings since all they did was to find the "largest" and "smallest" characters (lexicographically) in the string. For lists (and tuples), their functionality is more defined. Given a list of like objects, i.e., numbers or strings only, max() and min() could come in quite handy. Again, the quality of return values diminishes as mixed objects come into play. However, more often than not, you will be using these functions in a situation where they will provide the results you are seeking. We present a few examples using some of our earlier-defined lists.

>>> max(str_list) 'park' >>> max(num_list) [65535L, 2e+30, (76.45-1.3j)] >>> min(str_list) 'candlestick' >>> min(num_list) -49


sorted() and reversed()

>>> s = ['They', 'stamp', 'them', 'when', "they're", 'small'] >>> for t in reversed(s): ...  print t, ... small they're when them stamp They >>> sorted(s) ['They', 'small', 'stamp', 'them', "they're", 'when']


For beginners using strings, notice how we are able to mix single and double quotes together in harmony with the contraction "they're." Also to those new to strings, this is a note reminding you that all string sorting is lexicographic and not alphabetic (the letter "T" comes before the letter "a" in the ASCII table.)

enumerate() and zip()

>>> albums = ['tales', 'robot', 'pyramid'] >>> for i, album in enumerate(albums): ...     print i, album ... 0 tales 1 robot 2 pyramid >>> >>> fn = ['ian', 'stuart', 'david'] >>> ln = ['bairnson', 'elliott', 'paton'] >>> >>> for i, j in zip(fn, ln): ...     print ('%s %s' % (i,j)).title() ... Ian Bairnson Stuart Elliott David Paton


sum()

>>> a = [6, 4, 5] >>> reduce(operator.add, a) 15 >>> sum(a) 15 >>> sum(a, 5) 20 >>> a = [6., 4., 5.] >>> sum(a) 15.0


list() and tuple()

The list() and tuple() factory functions take iterables like other sequences and make new lists and tuples, respectively, out of the (just shallow-copied) data. Although strings are also sequence types, they are not commonly used with list() and tuple(). These built-in functions are used more often to convert from one type to the other, i.e., when you have a tuple that you need to make a list (so that you can modify its elements) and vice versa.

>>> aList = ['tao', 93, 99, 'time'] >>> aTuple = tuple(aList) >>> aList, aTuple (['tao', 93, 99, 'time'], ('tao', 93, 99, 'time')) >>> aList == aTuple False >>> anotherList = list(aTuple) >>> aList == anotherList True >>> aList is anotherList False >>> [id(x) for x in aList, aTuple, anotherList] [10903800, 11794448, 11721544]


As we already discussed at the beginning of the chapter, neither list() nor tuple() performs true conversions (see also Section 6.1.2). In other words, the list you passed to tuple() does not turn into a list, and the tuple you give to list() does not really become a list. Although the data set for both (the original and new object) is the same (hence satisfying ==), neither variable points to the same object (thus failing is). Also notice that, even though their values are the same, a list cannot "equal" a tuple.

6.13.3. List Type Built-in Functions

There are currently no special list-only built-in functions in Python unless you consider range() as oneits sole function is to take numeric input and generate a list that matches the criteria. range() is covered in Chapter 8. Lists can be used with most object and sequence built-in functions. In addition, list objects have their own methods.



Core Python Programming
Core Python Programming (2nd Edition)
ISBN: 0132269937
EAN: 2147483647
Year: 2004
Pages: 334
Authors: Wesley J Chun

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net