Online Book Reader

Home Category

Learning Python - Mark Lutz [128]

By Root 1566 0
L[0:2] = ['eat', 'more'] # Slice assignment: delete+insert

>>> L # Replaces items 0,1

['eat', 'more', 'SPAM!']

Both index and slice assignments are in-place changes—they modify the subject list directly, rather than generating a new list object for the result. Index assignment in Python works much as it does in C and most other languages: Python replaces the object reference at the designated offset with a new one.

Slice assignment, the last operation in the preceding example, replaces an entire section of a list in a single step. Because it can be a bit complex, it is perhaps best thought of as a combination of two steps:

Deletion. The slice you specify to the left of the = is deleted.

Insertion. The new items contained in the object to the right of the = are inserted into the list on the left, at the place where the old slice was deleted.[22]

This isn’t what really happens, but it tends to help clarify why the number of items inserted doesn’t have to match the number of items deleted. For instance, given a list L that has the value [1,2,3], the assignment L[1:2]=[4,5] sets L to the list [1,4,5,3]. Python first deletes the 2 (a one-item slice), then inserts the 4 and 5 where the deleted 2 used to be. This also explains why L[1:2]=[] is really a deletion operation—Python deletes the slice (the item at offset 1), and then inserts nothing.

In effect, slice assignment replaces an entire section, or “column,” all at once. Because the length of the sequence being assigned does not have to match the length of the slice being assigned to, slice assignment can be used to replace (by overwriting), expand (by inserting), or shrink (by deleting) the subject list. It’s a powerful operation, but frankly, one that you may not see very often in practice. There are usually more straightforward ways to replace, insert, and delete (concatenation and the insert, pop, and remove list methods, for example), which Python programmers tend to prefer in practice.

List method calls

Like strings, Python list objects also support type-specific method calls, many of which change the subject list in-place:

>>> L.append('please') # Append method call: add item at end

>>> L

['eat', 'more', 'SPAM!', 'please']

>>> L.sort() # Sort list items ('S' < 'e')

>>> L

['SPAM!', 'eat', 'more', 'please']

Methods were introduced in Chapter 7. In brief, they are functions (really, attributes that reference functions) that are associated with particular objects. Methods provide type-specific tools; the list methods presented here, for instance, are generally available only for lists.

Perhaps the most commonly used list method is append, which simply tacks a single item (object reference) onto the end of the list. Unlike concatenation, append expects you to pass in a single object, not a list. The effect of L.append(X) is similar to L+[X], but while the former changes L in-place, the latter makes a new list.[23]

Another commonly seen method, sort, orders a list in-place; it uses Python standard comparison tests (here, string comparisons), and by default sorts in ascending order. You can modify sort behavior by passing in keyword arguments—a special “name=value” syntax in function calls that specifies passing by name and is often used for giving configuration options. In sorts, the key argument gives a one-argument function that returns the value to be used in sorting, and the reverse argument allows sorts to be made in descending instead of ascending order:

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

>>> L.sort() # Sort with mixed case

>>> L

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

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

>>> L.sort(key=str.lower) # Normalize to lowercase

>>> L

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

>>>

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

>>> L.sort(key=str.lower, reverse=True) # Change sort order

>>> L

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

The sort key argument might also be useful when sorting lists of dictionaries, to pick out a sort key by indexing each dictionary. We’ll study dictionaries later in this chapter, and you’ll learn more about keyword function arguments in Part IV.

Return Main Page Previous Page Next Page

®Online Book Reader