Text
stringlengths
1
9.41k
For instance, the plus sign (+) performs addition, a star (*) is used for multiplication, and two stars (**) are used for exponentiation: **|** ----- `>>> 123 + 222` _# Integer addition_ ``` 345 ``` `>>> 1.5 * 4` _# Floating-point multiplication_ ``` 6.0 ``` `>>> 2 ** 100` _# 2 to the power 100_ ``` 1267650...
You can, for instance, compute 2 to the power 1,000,000 as an integer in Python, but you probably shouldn’t try to print the result—with more than 300,000 digits, you may be waiting awhile! `>>> len(str(2 ** 1000000))` _# How many digits in a really BIG number?_ ``` 301030 ``` Once you start experimenting with floa...
It turns out that there are two ways to print every object: with full precision (as in the first result shown here), and in a userfriendly form (as in the second).
Formally, the first form is known as an object’s ascode repr, and the second is its user-friendly str.
The difference can matter when we step up to using classes; for now, if something looks odd, try showing it with a print built-in call statement. Besides expressions, there are a handful of useful numeric modules that ship with Python—modules are just packages of additional tools that we import to use: ``` >>> impor...
We’ll defer discussion of these types until later in the book. So far, we’ve been using Python much like a simple calculator; to do better justice to its built-in types, let’s move on to explore strings. ###### Strings Strings are used to record textual information as well as arbitrary collections of bytes. They are...
Sequences maintain a left-to-right order among the items they contain: their items are stored and fetched by their relative position.
Strictly speaking, strings are sequences of one-character strings; other types of sequences include lists and tuples, covered later. ###### Sequence Operations As sequences, strings support operations that assume a positional ordering among items.
For example, if we have a four-character string, we can verify its length with the built-in len function and fetch its components with indexing expressions: ``` >>> S = 'Spam' ``` `>>> len(S)` _# Length_ ``` 4 ``` `>>> S[0]` _# The first item in S, indexing by zero-based position_ ``` 'S' ``` `>>> S[1]` _# The...
We’ll go into detail on how this works later (especially in Chapter 6), but Python variables never need to be declared ahead of time.
A variable is created when you assign it a value, may be assigned any type of object, and is replaced with its value when it shows up in an expression.
It must also have been previously assigned by the time you use its value.
For the purposes of this chapter, it’s enough to know that we need to assign an object to a variable in order to save it for later use. In Python, we can also index backward, from the end—positive indexes count from the left, and negative indexes count back from the right: `>>> S[-1]` _# The last item from the end in...
Python’s syntax is completely general this way. In addition to simple positional indexing, sequences also support a more general form of indexing known as slicing, which is a way to extract an entire section (slice) in a single step.
For example: `>>> S` _# A 4-character string_ ``` 'Spam' ``` `>>> S[1:3]` _# Slice of S from offsets 1 through 2 (not 3)_ ``` 'pa' ``` Probably the easiest way to think of slices is that they are a way to extract an entire _column from a string in a single step.
Their general form, X[I:J], means “give me ev-_ erything in X from offset I up to but not including offset J.” The result is returned in a new object.
The second of the preceding operations, for instance, gives us all the characters in string S from offsets 1 through 2 (that is, 3 – 1) as a new string.
The effect is to slice or “parse out” the two characters in the middle. In a slice, the left bound defaults to zero, and the right bound defaults to the length of the sequence being sliced.
This leads to some common usage variations: `>>> S[1:]` _# Everything past the first (1:len(S))_ ``` 'pam' ``` `>>> S` _# S itself hasn't changed_ ``` 'Spam' ``` `>>> S[0:3]` _# Everything but the last_ ``` 'Spa' ``` `>>> S[:3]` _# Same as S[0:3]_ ``` 'Spa' ``` `>>> S[:-1]` _# Everything but the last again...
As you’ll learn later, there is no reason to copy a string, but this form can be useful for sequences like lists. Finally, as sequences, strings also support concatenation with the plus sign (joining two strings into a new string) and repetition (making a new string by repeating another): ``` >>> S Spam' ``` `>>>...
This is a general property of Python that we’ll call polymorphism later in the book—in sum, the meaning of an operation depends on the objects being operated on.
As you’ll see when we study dynamic typing, this polymorphism property accounts for much of the conciseness and flexibility of Python code. Because types aren’t constrained, a Python-coded operation can normally work on many different types of objects automatically, as long as they support a compatible interface (like ...
This turns out to be a huge idea in Python; you’ll learn more about it later on our tour. ###### Immutability Notice that in the prior examples, we were not changing the original string with any of the operations we ran on it.
Every string operation is defined to produce a new string as its result, because strings are immutable in Python—they cannot be changed in-place after they are created.
For example, you can’t change a string by assigning to one of its positions, but you can always build a new one and assign it to the same name.
Because Python cleans up old objects as you go (as you’ll see later), this isn’t as inefficient as it may sound: ``` >>> S 'Spam' ``` `>>> S[0] = 'z'` _# Immutable objects cannot be changed_ ``` ...error text omitted... TypeError: 'str' object does not support item assignment ``` `>>> S = 'z' + S[1:]` _# But ...
In terms of the core types, numbers, strings, and tuples are immutable; lists and dictionaries are not (they can be changed in-place freely).
Among other things, immutability can be used to guarantee that an object remains constant throughout your program. ###### Type-Specific Methods Every string operation we’ve studied so far is really a sequence operation—that is, these operations will work on other sequences in Python as well, including lists and tuple...
String methods are the first line of text-processing tools in Python.
Other methods split a string into substrings on a delimiter (handy as a simple form of parsing), perform case conversions, test the content of the string (digits, letters, and so on), and strip whitespace characters off the ends of the string: ``` >>> line = 'aaa,bbb,ccccc,dd' ``` `>>> line.split(',')` _# Split on a...
As a rule of thumb, Python’s toolset is layered: generic operations that span multiple types show up as built-in functions or expressions (e.g., ``` len(X), X[0]), but type-specific operations are method calls (e.g., aString.upper()). ``` Finding the tools you need among all these categories will become more natural a...
In general, this book is not exhaustive in its look at object methods.
For more details, you can always call the built-in dir function, which returns a list of all the attributes available for a given object.
Because methods are function attributes, they will show up in this list.
Assuming S is still the string, here are its attributes on Python 3.0 (Python 2.6 varies slightly): ``` >>> dir(S) ['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__iter__...
In general, leading and trailing double underscores is the naming pattern Python uses for implementation details.
The names without the underscores in this list are the callable methods on string objects. The dir function simply gives the methods’ names.
To ask what they do, you can pass them to the help function: ``` >>> help(S.replace) Help on built-in function replace: replace(...) S.replace (old, new[, count]) -> str Return a copy of S with all occurrences of substring old replaced by new.
If the optional argument count is given, only the first count occurrences are replaced. help is one of a handful of interfaces to a system of code that ships with Python known ``` as PyDoc—a tool for extracting documentation from objects.
Later in the book, you’ll see that PyDoc can also render its reports in HTML format. You can also ask for help on an entire string (e.g., help(S)), but you may get more help than you want to see—i.e., information about every string method.
It’s generally better to ask about a specific method. **|** ----- For more details, you can also consult Python’s standard library reference manual or commercially published reference books, but dir and help are the first line of documentation in Python. ###### Other Ways to Code Strings So far, we’ve looked at t...
Python also provides a variety of ways for us to code strings, which we’ll explore in greater depth later.
For instance, special characters can be represented as backslash escape sequences: `>>> S = 'A\nB\tC'` _# \n is end-of-line, \t is tab_ `>>> len(S)` _# Each stands for just one character_ ``` 5 ``` `>>> ord('\n')` _# \n is a byte with the binary value 10 in ASCII_ ``` 10 ``` `>>> S = 'A\0B\0C'` _# \0, a binary z...
It also allows multiline string literals enclosed in triple quotes (single or double)—when this form is used, all the lines are concatenated together, and endof-line characters are added where line breaks appear.
This is a minor syntactic convenience, but it’s useful for embedding things like HTML and XML code in a Python script: ``` >>> msg = """ aaaaaaaaaaaaa bbb'''bbbbbbbbbb""bbbbbbb'bbbb cccccccccccccc""" >>> msg '\naaaaaaaaaaaaa\nbbb\'\'\'bbbbbbbbbb""bbbbbbb\'bbbb\ncccccccccccccc' ``` Python also supports a raw ...
In 3.0, the basic str string type handles Unicode too (which makes sense, given that ASCII text is a simple kind of Unicode), and a `bytes type` represents raw byte strings; in 2.6, Unicode is a separate type, and str handles both 8bit strings and binary data.
Files are also changed in 3.0 to return and accept str for text and bytes for binary data.
We’ll meet all these special string forms in later chapters. ###### Pattern Matching One point worth noting before we move on is that none of the string object’s methods support pattern-based text processing.
Text pattern matching is an advanced tool outside this book’s scope, but readers with backgrounds in other scripting languages may be interested to know that to do pattern matching in Python, we import a module called **|** ----- ``` re.
This module has analogous calls for searching, splitting, and replacement, but be ``` cause we can use patterns to specify substrings, we can be much more general: ``` >>> import re >>> match = re.match('Hello[ \t]*(.*)world', 'Hello Python world') >>> match.group(1) 'Python ' ``` This example searches for a ...
The following pattern, for example, picks out three groups separated by slashes: ``` >>> match = re.match('/(.*)/(.*)/(.*)', '/usr/home/lumberjack') >>> match.groups() ('usr', 'home', 'lumberjack') ``` Pattern matching is a fairly advanced text-processing tool by itself, but there is also support in Python for e...
I’ve already said enough about strings for this tutorial, though, so let’s move on to the next type. ###### Lists The Python list object is the most general sequence provided by the language.
Lists are positionally ordered collections of arbitrarily typed objects, and they have no fixed size. They are also mutable—unlike strings, lists can be modified in-place by assignment to offsets as well as a variety of list method calls. ###### Sequence Operations Because they are sequences, lists support all the se...
For instance, given a three-item list: `>>> L = [123, 'spam', 1.23]` _# A list of three different-type objects_ `>>> len(L)` _# Number of items in the list_ ``` 3 ``` we can index, slice, and so on, just as for strings: `>>> L[0]` _# Indexing by position_ ``` 123 ``` `>>> L[:-1]` _# Slicing a list returns a new...
Further, lists have no fixed size.
That is, they can grow and shrink on demand, in response to list-specific operations: `>>> L.append('NI')` _# Growing: add object at end of list_ ``` >>> L [123, 'spam', 1.23, 'NI'] ``` `>>> L.pop(2)` _# Shrinking: delete an item in the middle_ ``` 1.23 ``` `>>> L` _# "del L[2]" deletes from a list too_ ``` ...
Other list methods insert an item at an arbitrary position (insert), remove a given item by value (remove), and so on.
Because lists are mutable, most list methods also change the list object in-place, instead of creating a new one: ``` >>> M = ['bb', 'aa', 'cc'] >>> M.sort() >>> M ['aa', 'bb', 'cc'] >>> M.reverse() >>> M ['cc', 'bb', 'aa'] ``` The list sort method here, for example, orders the list in ascending fashion ...
Indexing off the end of a list is always a mistake, but so is assigning off the end: ``` >>> L [123, 'spam', 'NI'] >>> L[99] ...error text omitted... IndexError: list index out of range ``` **|** ----- ``` >>> L[99] = 1 ...error text omitted... IndexError: list assignment index out of range ``` Thi...
Rather than silently growing the list in response, Python reports an error.
To grow a list, we call list methods such as append instead. ###### Nesting One nice feature of Python’s core data types is that they support arbitrary nesting—we can nest them in any combination, and as deeply as we like (for example, we can have a list that contains a dictionary, which contains another list, and so...
One immediate application of this feature is to represent matrixes, or “multidimensional arrays” in Python.
A list with nested lists will do the job for basic applications: `>>> M = [[1, 2, 3],` _# A 3 × 3 matrix, as nested lists_ `[4, 5, 6],` _# Code can span lines if bracketed_ ``` [7, 8, 9]] >>> M [[1, 2, 3], [4, 5, 6], [7, 8, 9]] ``` Here, we’ve coded a list that contains three other lists.
The effect is to represent a 3 × 3 matrix of numbers.
Such a structure can be accessed in a variety of ways: `>>> M[1]` _# Get row 2_ ``` [4, 5, 6] ``` `>>> M[1][2]` _# Get row 2, then get item 3 within the row_ ``` 6 ``` The first operation here fetches the entire second row, and the second grabs the third item within that row.
Stringing together index operations takes us deeper and deeper into our nested-object structure.[†] ###### Comprehensions In addition to sequence operations and list methods, Python includes a more advanced operation known as a list comprehension expression, which turns out to be a powerful way to process structures ...
Suppose, for instance, that we need to extract the second column of our sample matrix.
It’s easy to grab rows by simple indexing † This matrix structure works for small-scale tasks, but for more serious number crunching you will probably want to use one of the numeric extensions to Python, such as the open source NumPy system.
Such tools can store and process large matrixes much more efficiently than our nested list structure.
NumPy has been said to turn Python into the equivalent of a free and more powerful version of the Matlab system, and organizations such as NASA, Los Alamos, and JPMorgan Chase use this tool for scientific and financial tasks.
Search the Web for more details. **|** ----- because the matrix is stored by rows, but it’s almost as easy to get a column with a list comprehension: `>>> col2 = [row[1] for row in M]` _# Collect the items in column 2_ ``` >>> col2 [2, 5, 8] ``` `>>> M` _# The matrix is unchanged_ ``` [[1, 2, 3], [4, 5, 6],...
List comprehensions are coded in square brackets (to tip you off to the fact that they make a list) and are composed of an expression and a looping construct that share a variable name (row, here).
The preceding list comprehension means basically what it says: “Give me row[1] for each row in matrix M, in a new list.” The result is a new list containing column 2 of the matrix. List comprehensions can be more complex in practice: `>>> [row[1] + 1 for row in M]` _# Add 1 to each item in column 2_ ``` [3, 6, 9] ...
List comprehensions make new lists of results, but they can be used to iterate over any iterable object.
Here, for instance, we use list comprehensions to step over a hardcoded list of coordinates and a string: `>>> diag = [M[i][i] for i in [0, 1, 2]]` _# Collect a diagonal from matrix_ ``` >>> diag [1, 5, 9] ``` `>>> doubles = [c * 2 for c in 'spam']` _# Repeat characters in a string_ ``` >>> doubles ['ss', 'pp...
The main point of this brief introduction is to illustrate that Python includes both simple and advanced tools in its arsenal.
List comprehensions are an optional feature, but they tend to be handy in practice and often provide a substantial processing speed advantage.
They also work on any type that is a sequence in Python, as well as some types that are not.
You’ll hear much more about them later in this book. As a preview, though, you’ll find that in recent Pythons, comprehension syntax in parentheses can also be used to create generators that produce results on demand (the ``` sum built-in, for instance, sums items in a sequence): ``` **|** ----- `>>> G = (sum(row) ...
Wrapping it in list forces it to return all its values in Python 3.0: `>>> list(map(sum, M))` _# Map sum over items in M_ ``` [6, 15, 24] ``` In Python 3.0, comprehension syntax can also be used to create sets and dictionaries: `>>> {sum(row) for row in M}` _# Create a set of row sums_ ``` {24, 6, 15} ``` `>>> ...
Mappings are also collections of other objects, but they store objects by key instead of by relative position.
In fact, mappings don’t maintain any reliable left-to-right order; they simply map keys to associated values.
Dictionaries, the only mapping type in Python’s core objects set, are also mutable: they may be changed in-place and can grow and shrink on demand, like lists. ###### Mapping Operations When written as literals, dictionaries are coded in curly braces and consist of a series of “key: value” pairs.
Dictionaries are useful anytime we need to associate a set of values with keys—to describe the properties of something, for instance.
As an example, consider the following three-item dictionary (with keys “food,” “quantity,” and “color”): ``` >>> D = {'food': 'Spam', 'quantity': 4, 'color': 'pink'} ``` **|** ----- We can index this dictionary by key to fetch and change the keys’ associated values. The dictionary index operation uses the same sy...
The following code, for example, starts with an empty dictionary and fills it out one key at a time.
Unlike out-of-bounds assignments in lists, which are forbidden, assignments to new dictionary keys create those keys: ``` >>> D = {} ``` `>>> D['name'] = 'Bob'` _# Create keys by assignment_ ``` >>> D['job'] = 'dev' >>> D['age'] = 40 >>> D {'age': 40, 'job': 'dev', 'name': 'Bob'} >>> print(D['name']) Bob...
In other applications, dictionaries can also be used to replace searching operations—indexing a dictionary by key is often the fastest way to code a search in Python. ###### Nesting Revisited In the prior example, we used a dictionary to describe a hypothetical person, with three keys.
Suppose, though, that the information is more complex. Perhaps we need to record a first name and a last name, along with multiple job titles.
This leads to another application of Python’s object nesting in action.
The following dictionary, coded all at once as a literal, captures more structured information: ``` >>> rec = {'name': {'first': 'Bob', 'last': 'Smith'}, 'job': ['dev', 'mgr'], 'age': 40.5} ``` Here, we again have a three-key dictionary at the top (keys “name,” “job,” and “age”), but the values have ...
We can access the components of this structure much as we did for our matrix earlier, but this time some of our indexes are dictionary keys, not list offsets: **|** ----- `>>> rec['name']` _# 'name' is a nested dictionary_ ``` {'last': 'Smith', 'first': 'Bob'} ``` `>>> rec['name']['last']` _# Index the nested di...
As you can see, nesting allows us to build up complex information structures directly and easily.
Building a similar structure in a low-level language like C would be tedious and require much more code: we would have to lay out and declare structures and arrays, fill out values, link everything together, and so on.
In Python, this is all automatic—running the expression creates the entire nested object structure for us.
In fact, this is one of the main benefits of scripting languages like Python. Just as importantly, in a lower-level language we would have to be careful to clean up all of the object’s space when we no longer need it.
In Python, when we lose the last reference to the object—by assigning its variable to something else, for example—all of the memory space occupied by that object’s structure is automatically cleaned up for us: `>>> rec = 0` _# Now the object's space is reclaimed_ Technically speaking, Python has a feature known as ga...
In Python, the space is reclaimed immediately, as soon as the last reference to an object is removed.
We’ll study how this works later in this book; for now, it’s enough to know that you can use objects freely, without worrying about creating their space or cleaning up as you go.[‡] ‡ Keep in mind that the rec record we just created really could be a database record, when we employ Python’s _object persistence system—...
We_ won’t go into details here, but watch for discussion of Python’s pickle and shelve modules later in this book. **|** ----- ###### Sorting Keys: for Loops As mappings, as we’ve already seen, dictionaries only support accessing items by key. However, they also support type-specific operations with method calls t...