Text
stringlengths
1
9.41k
The former may make the method appear simpler to beginners at first glance (“format” may be easier to parse than multiple “%” characters), though this is too subjective to call. The latter difference might be more significant—with the format expression, a single value can be given by itself, but multiple values must b...
In fact, because a single item can be given either by itself or within a tuple, a tuple to be formatted must be provided as nested tuples: ``` >>> '%s' % 1.23 '1.23' >>> '%s' % (1.23,) '1.23' >>> '%s' % ((1.23,),) '(1.23,)' ``` The formatting method, on the other hand, tightens this up by accepting general...
This is still a fairly minor issue, though—if you always enclose values in a tuple and ignore the nontupled option, the expression is essentially the same as the method call here.
Moreover, the method incurs an extra price in inflated code size to achieve its limited flexibility.
Given that the expression has been used extensively throughout Python’s history, it’s not clear that this point justifies breaking existing code for a new tool that is so similar, as the next section argues. ###### Possible future deprecation? As mentioned earlier, there is some risk that Python developers may deprec...
In fact, there is a note to this effect in Python 3.0’s manuals. This has not yet occurred, of course, and both formatting techniques are fully available and reasonable to use in Python 2.6 and 3.0 (the versions of Python this book covers). Both techniques are supported in the upcoming Python 3.1 release as well, so d...
Moreover, because formatting expressions are used extensively in almost all existing Python code written to date, most programmers will benefit from being familiar with both techniques for many years to come. If this deprecation ever does occur, though, you may need to recode all your % expressions as format methods, ...
At the risk of editorializing here, I hope that such a change will be based upon the future common practice of actual Python programmers, not the whims of a handful of core developers—particularly given that the window for Python 3.0’s many incompatible changes is now closed.
Frankly, this deprecation would seem like trading one complicated thing for another complicated thing—one that is largely equivalent to the tool it would replace!
If you care about migrating to future Python releases, though, be sure to watch for developments on this front over time. ###### General Type Categories Now that we’ve explored the first of Python’s collection objects, the string, let’s pause to define a few general type concepts that will apply to most of the types ...
With regard to built-in types, it turns out that operations work the same for all the types in the same category, so we’ll only need to define most of these ideas once.
We’ve only examined numbers and strings so far, but because they are representative of two of the three major type categories in Python, you already know more about several other types than you might think. **|** ----- ###### Types Share Operation Sets by Categories As you’ve learned, strings are immutable sequenc...
Now, it so happens that all the sequences we’ll study in this part of the book respond to the same sequence operations shown in this chapter at work on strings—concatenation, indexing, iteration, and so on.
More formally, there are three major type (and operation) categories in Python: _Numbers (integer, floating-point, decimal, fraction, others)_ Support addition, multiplication, etc. _Sequences (strings, lists, tuples)_ Support indexing, slicing, concatenation, etc. _Mappings (dictionaries)_ Support indexing by key, et...
However, many of the other types we will encounter will be similar to numbers and strings.
For example, for any sequence objects X and Y: - X + Y makes a new sequence object with the contents of both operands. - X * N makes a new sequence object with N copies of the sequence operand X. In other words, these operations work the same way on any kind of sequence, including strings, lists, tuples, and some ...
The only difference is that the new result object you get back is of the same type as the operands `X and` `Y—if you` concatenate lists, you get back a new list, not a string.
Indexing, slicing, and other sequence operations work the same on all sequences, too; the type of the objects being processed tells Python which flavor of the task to perform. ###### Mutable Types Can Be Changed In-Place The immutable classification is an important constraint to be aware of, yet it tends to trip up n...
If an object type is immutable, you cannot change its value in-place; Python raises an error if you try. Instead, you must run code to make a new object containing the new value.
The major core types in Python break down as follows: _Immutables (numbers, strings, tuples, frozensets)_ None of the object types in the immutable category support in-place changes, though we can always run expressions to make new objects and assign their results to variables as needed. **|** ----- _Mutables (lis...
Although such objects can be copied, in-place changes support direct modification. Generally, immutable types give some degree of integrity by guaranteeing that an object won’t be changed by another part of a program.
For a refresher on why this matters, see the discussion of shared object references in Chapter 6.
To see how lists, dictionaries, and tuples participate in type categories, we need to move ahead to the next chapter. ###### Chapter Summary In this chapter, we took an in-depth tour of the string object type.
We learned about coding string literals, and we explored string operations, including sequence expressions, string method calls, and string formatting with both expressions and method calls.
Along the way, we studied a variety of concepts in depth, such as slicing, method call syntax, and triple-quoted block strings.
We also defined some core ideas common to a variety of types: sequences, for example, share an entire set of operations. In the next chapter, we’ll continue our types tour with a look at the most general object collections in Python—lists and dictionaries.
As you’ll find, much of what you’ve learned here will apply to those types as well.
And as mentioned earlier, in the final part of this book we’ll return to Python’s string model to flesh out the details of Unicode text and binary data, which are of interest to some, but not all, Python programmers. Before moving on, though, here’s another chapter quiz to review the material covered here. ###### Test...
Can the string find method be used to search a list? 2. Can a string slice expression be used on a list? 3. How would you convert a character to its ASCII integer code?
How would you convert the other way, from an integer to a character? 4. How might you go about changing a string in Python? 5.
Given a string S with the value "s,pa,m", name two ways to extract the two characters in the middle. 6. How many characters are there in the string "a\nb\x1f\000d"? 7.
Why might you use the string module instead of string method calls? **|** ----- ###### Test Your Knowledge: Answers 1.
No, because methods are always type-specific; that is, they only work on a single data type.
Expressions like `X+Y and built-in functions like` `len(X) are generic,` though, and may work on a variety of types.
In this case, for instance, the in membership expression has a similar effect as the string find, but it can be used to search both strings and lists.
In Python 3.0, there is some attempt to group methods by categories (for example, the mutable sequence types list and bytearray have similar method sets), but methods are still more type-specific than other operation sets. 2.
Yes. Unlike methods, expressions are generic and apply to many types.
In this case, the slice expression is really a sequence operation—it works on any type of sequence object, including strings, lists, and tuples.
The only difference is that when you slice a list, you get back a new list. 3.
The built-in `ord(S) function converts from a one-character string to an integer` character code; chr(I) converts from the integer code back to a string. 4.
Strings cannot be changed; they are immutable.
However, you can achieve a similar effect by creating a new string—by concatenating, slicing, running formatting expressions, or using a method call like replace—and then assigning the result back to the original variable name. 5.
You can slice the string using S[2:4], or split on the comma and index the string using S.split(',')[1]. Try these interactively to see for yourself. 6. Six.
The string "a\nb\x1f\000d" contains the bytes a, newline (\n), b, binary 31 (a hex escape \x1f), binary 0 (an octal escape \000), and d.
Pass the string to the builtin len function to verify this, and print each of its character’s ord results to see the actual byte values. See Table 7-2 for more details. 7.
You should never use the `string module instead of string object method calls` today—it’s deprecated, and its calls are removed completely in Python 3.0.
The only reason for using the string module at all is for its other tools, such as predefined constants.
You might also see it appear in what is now very old and dusty Python code. **|** ----- ###### CHAPTER 8 ### Lists and Dictionaries This chapter presents the list and dictionary object types, both of which are collections of other objects.
These two types are the main workhorses in almost all Python scripts. As you’ll see, both types are remarkably flexible: they can be changed in-place, can grow and shrink on demand, and may contain and be nested in any other kind of object. By leveraging these types, you can build up and process arbitrarily rich inform...
Lists are Python’s most flexible ordered collection object type. Unlike strings, lists can contain any sort of object: numbers, strings, and even other lists.
Also, unlike strings, lists may be changed in-place by assignment to offsets and slices, list method calls, deletion statements, and more—they are mutable objects. Python lists do the work of most of the collection data structures you might have to implement manually in lower-level languages such as C.
Here is a quick look at their main properties.
Python lists are: _Ordered collections of arbitrary objects_ From a functional view, lists are just places to collect other objects so you can treat them as groups.
Lists also maintain a left-to-right positional ordering among the items they contain (i.e., they are sequences). _Accessed by offset_ Just as with strings, you can fetch a component object out of a list by indexing the list on the object’s offset.
Because items in lists are ordered by their positions, you can also do tasks such as slicing and concatenation. ----- _Variable-length, heterogeneous, and arbitrarily nestable_ Unlike strings, lists can grow and shrink in-place (their lengths can vary), and they can contain any sort of object, not just one-character...
Because lists can contain other complex objects, they also support arbitrary nesting; you can create lists of lists of lists, and so on. _Of the category “mutable sequence”_ In terms of our type category qualifiers, lists are mutable (i.e., can be changed inplace) and can respond to all the sequence operations used wit...
In fact, sequence operations work the same on lists as they do on strings; the only difference is that sequence operations such as concatenation and slicing return new lists instead of new strings when applied to lists.
Because lists are mutable, however, they also support other operations that strings don’t (such as deletion and index assignment operations, which change the lists in-place). _Arrays of object references_ Technically, Python lists contain zero or more references to other objects.
Lists might remind you of arrays of pointers (addresses) if you have a background in some other languages.
Fetching an item from a Python list is about as fast as indexing a C array; in fact, lists really are arrays inside the standard Python interpreter, not linked structures.
As we learned in Chapter 6, though, Python always follows a reference to an object whenever the reference is used, so your program deals only with objects.
Whenever you assign an object to a data structure component or variable name, Python always stores a reference to that same object, not a copy of it (unless you request a copy explicitly). Table 8-1 summarizes common and representative list object operations.
As usual, for the full story see the Python standard library manual, or run a `help(list) or` ``` dir(list) call interactively for a complete list of list methods—you can pass in a real ``` list, or the word list, which is the name of the list data type. _Table 8-1.
Common list literals and operations_ **Operation** **Interpretation** `L = []` An empty list `L = [0, 1, 2, 3]` Four items: indexes 0..3 `L = ['abc', ['def', 'ghi']]` Nested sublists ``` L = list('spam') L = list(range(-4, 4)) L[i] L[i][j] L[i:j] len(L) ``` **|** Lists of an iterable’s items, list of successi...
For instance, the second row in Table 8-1 assigns the variable L to a four-item list.
A nested list is coded as a nested square-bracketed series (row 3), and the empty list is just a squarebracket pair with nothing inside (row 1).[*] Many of the operations in Table 8-1 should look familiar, as they are the same sequence operations we put to work on strings—indexing, concatenation, iteration, and so on....
Lists have these tools for change operations because they are a mutable object type. - In practice, you won’t see many lists written out like this in list-processing programs.
It’s more common to see code that processes lists constructed dynamically (at runtime).
In fact, although it’s important to master literal syntax, most data structures in Python are built by running program code at runtime. **|** ----- ###### Lists in Action Perhaps the best way to understand lists is to see them at work.
Let’s once again turn to some simple interpreter interactions to illustrate the operations in Table 8-1. ###### Basic List Operations Because they are sequences, lists support many of the same operations as strings.
For example, lists respond to the + and * operators much like strings—they mean concatenation and repetition here too, except that the result is a new list, not a string: ``` % python ``` `>>> len([1, 2, 3])` _# Length_ ``` 3 ``` `>>> [1, 2, 3] + [4, 5, 6]` _# Concatenation_ ``` [1, 2, 3, 4, 5, 6] ``` `>>> ['N...
For instance, you cannot concatenate a list and a string unless you first convert the list to a string (using tools such as str or % formatting) or convert the string to a list (the list built-in function does the trick): `>>> str([1, 2]) + "34"` _# Same as "[1, 2]" + "34"_ ``` '[1, 2]34' ``` `>>> [1, 2] + list("34...
print(x, end=' ')` _# Iteration_ ``` ... 1 2 3 ``` We will talk more formally about for iteration and the range built-ins in Chapter 13, because they are related to statement syntax.
In short, for loops step through items in any sequence from left to right, executing one or more statements for each item. The last items in Table 8-1, list comprehensions and map calls, are covered in more detail in Chapter 14 and expanded on in Chapter 20.
Their basic operation is straightforward, though—as introduced in Chapter 4, list comprehensions are a way to build a new list **|** ----- by applying an expression to each item in a sequence, and are close relatives to for loops: `>>> res =` `[c * 4 for c in 'SPAM']` _# List comprehensions_ ``` >>> res ['SSSS...
res.append(c * 4) ... >>> res ['SSSS', 'PPPP', 'AAAA', 'MMMM'] ``` As also introduced in Chapter 4, the map built-in function does similar work, but applies a function to items in a sequence and collects all the results in a new list: `>>> list(map(abs, [−1, −2, 0, 1, 2]))` _# map function across sequence_ ``` ...
However, the result of indexing a list is whatever type of object lives at the offset you specify, while slicing a list always returns a new list: ``` >>> L = ['spam', 'Spam', 'SPAM!'] ``` `>>> L[2]` _# Offsets start at zero_ ``` 'SPAM!' ``` `>>> L[−2]` _# Negative: count from the right_ ``` 'Spam' ``` `>>> L[...
Here’s a basic 3 × 3 two-dimensional list-based array: ``` >>> matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] ``` With one index, you get an entire row (really, a nested sublist), and with two, you get an item within the row: **|** ----- ``` >>> matrix[1] [4, 5, 6] >>> matrix[1][1] 5 >>> matrix[2][0] 7 ...
[4, 5, 6], ...
[7, 8, 9]] >>> matrix[1][1] 5 ``` Notice in the preceding interaction that lists can naturally span multiple lines if you want them to because they are contained by a pair of brackets (more on syntax in the next part of the book).
Later in this chapter, you’ll also see a dictionary-based matrix representation.
For high-powered numeric work, the NumPy extension mentioned in Chapter 5 provides other ways to handle matrixes. ###### Changing Lists In-Place Because lists are mutable, they support operations that change a list object in-place. That is, the operations in this section all modify the list object directly, without r...
Because Python deals only in object references, this distinction between changing an object in-place and creating a new object matters—as discussed in Chapter 6, if you change an object in-place, you might impact more than one reference to it at the same time. ###### Index and slice assignments When using a list, you...
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: **|** ----- 1. Deletion. The slice you specify to the left of the = is deleted. 2. 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.[†] 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 c...
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.[‡] 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. † This description needs ela...
You can also mimic ``` append with clever slice assignments: L[len(L):]=[X] is like L.append(X), and L[:0]=[X] is like appending at ``` the front of a list.
Both delete an empty slice and insert X, changing L in-place quickly, like append. **|** ----- 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 =...
We’ll study dictionaries later in this chapter, and you’ll learn more about keyword function arguments in Part IV. _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 de...
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".