Text
stringlengths
1
9.41k
This means that if we make a dictionary and print it back, its keys may come back in a different order than that in which we typed them: ``` >>> D = {'a': 1, 'b': 2, 'c': 3} >>> D {'a': 1, 'c': 3, 'b': 2} ``` What do we do, though, if we do need to impose an ordering on a dictionary’s items? One common solution ...
The` ``` sorted call returns the result and sorts a variety of object types, in this case sorting ``` dictionary keys automatically: ``` >>> D {'a': 1, 'c': 3, 'b': 2} >>> for key in sorted(D): print(key, '=>', D[key]) a => 1 b => 2 c => 3 ``` Besides showcasing dictionaries, this use case serves to...
A user-defined loop variable (key, here) is used to reference the current item each time through.
The net effect in our example is to print the unordered dictionary’s keys and values, in sorted-key order. The for loop, and its more general cousin the while loop, are the main ways we code repetitive tasks as statements in our scripts.
Really, though, the for loop (like its relative the list comprehension, which we met earlier) is a sequence operation.
It works on any object that is a sequence and, like the list comprehension, even on some things that are not.
Here, for example, it is stepping across the characters in a string, printing the uppercase version of each as it goes: ``` >>> for c in 'spam': print(c.upper()) S P A M ``` Python’s while loop is a more general sort of looping tool, not limited to stepping across sequences: ``` >>> x = 4 >>> while...
In fact, both will work on any object that follows the iteration protocol—a pervasive idea in Python that essentially means a physically stored sequence in memory, or an object that generates one item at a time in the context of an iteration operation.
An object falls into the latter category if it responds to the iter built-in with an object that advances in response to next.
The _generator comprehension expression we saw earlier is such an object._ I’ll have more to say about the iteration protocol later in this book.
For now, keep in mind that every Python tool that scans an object from left to right uses the iteration protocol.
This is why the sorted call used in the prior section works on the dictionary directly—we don’t have to call the keys method to get a sequence because dictionaries are iterable objects, with a next that returns successive keys. **|** ----- This also means that any list comprehension expression, such as this one, wh...
Having said that, though, I should point out that performance measures are tricky business in Python because it optimizes so much, and performance can vary from release to release. A major rule of thumb in Python is to code for simplicity and readability first and worry about performance later, after your program is w...
More often than not, your code will be quick enough as it is.
If you do need to tweak code for performance, though, Python includes tools to help you out, including the time and timeit modules and the profile module. You’ll find more on these later in this book, and in the Python manuals. ###### Missing Keys: if Tests One other note about dictionaries before we move on.
Although we can assign to a new key to expand a dictionary, fetching a nonexistent key is still a mistake: ``` >>> D {'a': 1, 'c': 3, 'b': 2} ``` `>>> D['e'] = 99` _# Assigning new keys grows dictionaries_ ``` >>> D {'a': 1, 'c': 3, 'b': 2, 'e': 99} ``` `>>> D['f']` _# Referencing a nonexistent key is an erro...
But in some generic programs, we can’t always know what keys will be present when we write our code. How do we handle such cases and avoid errors? One trick is to test ahead of time.
The dictionary in membership expression allows us to **|** ----- query the existence of a key and branch on the result with a Python if statement (as with the for, be sure to press Enter twice to run the if interactively here): ``` >>> 'f' in D False >>> if not 'f' in D: print('missing') missing ``` ...
In its full form, the if statement can also have an else clause for a default case, and one or more elif (else if) clauses for other tests. It’s the main selection tool in Python, and it’s the way we code logic in our scripts. Still, there are other ways to create dictionaries and avoid accessing nonexistent keys: the...
Here are a few examples: `>>> value = D.get('x', 0)` _# Index but with a default_ ``` >>> value 0 ``` `>>> value = D['x'] if 'x' in D else 0` _# if/else expression form_ ``` >>> value 0 ``` We’ll save the details on such alternatives until a later chapter.
For now, let’s move on to tuples. ###### Tuples The tuple object (pronounced “toople” or “tuhple,” depending on who you ask) is roughly like a list that cannot be changed—tuples are sequences, like lists, but they are immutable, like strings.
Syntactically, they are coded in parentheses instead of square brackets, and they support arbitrary types, arbitrary nesting, and the usual sequence operations: `>>> T = (1, 2, 3, 4)` _# A 4-item tuple_ `>>> len(T)` _# Length_ ``` 4 ``` `>> T + (5, 6)` _# Concatenation_ ``` (1, 2, 3, 4, 5, 6) ``` `>>> T[0]` _# I...
That is, they are immutable sequences: `>>> T[0] = 2` _# Tuples are immutable_ ``` ...error text omitted... TypeError: 'tuple' object does not support item assignment ``` Like lists and dictionaries, tuples support mixed types and nesting, but they don’t grow and shrink because they are immutable: ``` >>> T = (...
Frankly, tuples are not generally used as often as lists in practice, but their immutability is the whole point.
If you pass a collection of objects around your program as a list, it can be changed anywhere; if you use a tuple, it cannot.
That is, tuples provide a sort of integrity constraint that is convenient in programs larger than those we’ll write here. We’ll talk more about tuples later in the book.
For now, though, let’s jump ahead to our last major core type: the file. ###### Files File objects are Python code’s main interface to external files on your computer.
Files are a core type, but they’re something of an oddball—there is no specific literal syntax for creating them.
Rather, to create a file object, you call the built-in open function, passing in an external filename and a processing mode as strings.
For example, to create a text output file, you would pass in its name and the 'w' processing mode string to write data: `>>> f = open('data.txt', 'w')` _# Make a new file in output mode_ `>>> f.write('Hello\n')` _# Write strings of bytes to it_ ``` 6 ``` `>>> f.write('world\n')` _# Returns number of bytes written i...
To read back what you just wrote, reopen the file in `'r' processing mode, for reading text` input—this is the default if you omit the mode in the call.
Then read the file’s content into a string, and display it.
A file’s contents are always a string in your script, regardless of the type of data the file contains: `>>> f = open('data.txt')` _# 'r' is the default processing mode_ `>>> text = f.read()` _# Read entire file into a string_ ``` >>> text 'Hello\nworld\n' ``` `>>> print(text)` _# print interprets control charact...
As we’ll see later, though, the best way to read a file today is to not read it at all—files provide an iterator that automatically reads line by line in for loops and other contexts. We’ll meet the full set of file methods later in this book, but if you want a quick preview now, run a dir call on any open file and a ...
Text files represent content as strings and perform Unicode encoding and decoding automatically, while binary files represent content as a special ``` bytes string type and allow you to access file content unaltered: ``` `>>> data = open('data.bin', 'rb').read()` _# Open binary file_ `>>> data` _# bytes string holds b...
For more advanced tasks, though, Python comes with additional file-like tools: pipes, FIFOs, sockets, keyed-access files, persistent object shelves, descriptor-based files, relational and object-oriented database interfaces, and more.
Descriptor files, for instance, support file locking and other low-level tools, and sockets provide an interface for networking and interprocess communication.
We won’t cover many of these topics in this book, but you’ll find them useful once you start programming Python in earnest. ###### Other Core Types Beyond the core types we’ve seen so far, there are others that may or may not qualify for membership in the set, depending on how broadly it is defined.
Sets, for example, are a recent addition to the language that are neither mappings nor sequences; rather, they are unordered collections of unique and immutable objects.
Sets are created by calling the built-in set function or using new set literals and expressions in 3.0, and they support the usual mathematical set operations (the choice of new {...} syntax for set literals in 3.0 makes sense, since sets are much like the keys of a valueless dictionary): `>>> X = set('spam')` _# Make...
Both can be used to work around the limitations and inherent inaccuracies of floating-point math: `>>> 1 / 3` _# Floating-point (use .0 in Python 2.6)_ ``` 0.33333333333333331 >>> (2/3) + (1/2) ``` **|** ----- ``` 1.1666666666666665 ``` `>>> import decimal` _# Decimals: fixed precision_ ``` >>> d = decima...
The type object, returned by the type built-in function, is an object that gives the type of another object; its result differs slightly in 3.0, because types have merged with classes completely (something we’ll explore in the context of “new-style” classes in Part VI).
Assuming L is still the list of the prior section: _# In Python 2.6:_ `>>> type(L)` _# Types: type of L is list type object_ ``` <type 'list'> ``` `>>> type(type(L))` _# Even types are objects_ ``` <type 'type'> ``` _# In Python 3.0:_ `>>> type(L)` _# 3.0: types are classes, and vice versa_ ``` <class 'list'...
In fact, there are at least three ways to do so in a Python script: `>>> if type(L) == type([]):` _# Type testing, if you must..._ ``` print('yes') yes ``` `>>> if type(L) == list:` _# Using the type name_ ``` print('yes') yes ``` `>>> if isinstance(L, list):` _# Object-oriented tests_ ``` prin...
The reason why won’t become completely clear until later in the book, when we start writing larger code units such as functions, but it’s a (perhaps the) core Python concept.
By checking for specific types in your code, you effectively break its flexibility—you limit it to working on just one type.
Without such tests, your code may be able to work on a whole range of types. This is related to the idea of polymorphism mentioned earlier, and it stems from Python’s lack of type declarations.
As you’ll learn, in Python, we code to object inter_faces (operations supported), not to types.
Not caring about specific types means that_ code is automatically applicable to many of them—any object with a compatible interface will work, regardless of its specific type.
Although type checking is supported— and even required, in some rare cases—you’ll see that it’s not usually the “Pythonic” way of thinking.
In fact, you’ll find that polymorphism is probably the key idea behind using Python well. ###### User-Defined Classes We’ll study object-oriented programming in Python—an optional but powerful feature of the language that cuts development time by supporting programming by customization—in depth later in this book.
In abstract terms, though, classes define new types of objects that extend the core set, so they merit a passing glance here.
Say, for example, that you wish to have a type of object that models employees.
Although there is no such specific core type in Python, the following user-defined class might fit the bill: ``` >>> class Worker: ``` `def __init__(self, name, pay):` _# Initialize when created_ `self.name = name` _# self is the new object_ **|** ----- ``` self.pay = pay def lastName(self): ```...
Calling the class like a function generates instances of our new type, and the class’s methods automatically receive the instance being processed by a given method call (in the self argument): `>>> bob = Worker('Bob Smith', 50000)` _# Make two instances_ `>>> sue = Worker('Sue Jones', 60000)` _# Each has name and pay ...
In a sense, though, the class-based type simply builds on and uses core types—a user-defined Worker object here, for example, is just a collection of a string and a number (name and pay, respectively), plus functions for processing those two built-in objects. The larger story of classes is that their inheritance mecha...
We extend software by writing new classes, not by changing what already works.
You should also know that classes are an optional feature of Python, and simpler built-in types such as lists and dictionaries are often better tools than user-coded classes.
This is all well beyond the bounds of our introductory object-type tutorial, though, so consider this just a preview; for full disclosure on user-defined types coded with classes, you’ll have to read on to Part VI. ###### And Everything Else As mentioned earlier, everything you can process in a Python script is a typ...
However, even though everything in Python is an “object,” only those types of objects we’ve met so far are considered part of Python’s core type set.
Other types in Python either are objects related to program execution (like functions, modules, classes, and compiled code), which we will study later, or are implemented by imported module functions, not language syntax.
The latter of these also tend to have application-specific roles—text patterns, database interfaces, network connections, and so on. **|** ----- Moreover, keep in mind that the objects we’ve met here are objects, but not necessarily _object-oriented—a concept that usually requires inheritance and the Python_ `class...
Still, Python’s core objects are the workhorses of almost every Python script you’re likely to meet, and they usually are the basis of larger noncore types. ###### Chapter Summary And that’s a wrap for our concise data type tour.
This chapter has offered a brief introduction to Python’s core object types and the sorts of operations we can apply to them.
We’ve studied generic operations that work on many object types (sequence operations such as indexing and slicing, for example), as well as type-specific operations available as method calls (for instance, string splits and list appends).
We’ve also defined some key terms, such as immutability, sequences, and polymorphism. Along the way, we’ve seen that Python’s core object types are more flexible and powerful than what is available in lower-level languages such as C.
For instance, Python’s lists and dictionaries obviate most of the work you do to support collections and searching in lower-level languages.
Lists are ordered collections of other objects, and dictionaries are collections of other objects that are indexed by key instead of by position.
Both dictionaries and lists may be nested, can grow and shrink on demand, and may contain objects of any type.
Moreover, their space is automatically cleaned up as you go. I’ve skipped most of the details here in order to provide a quick tour, so you shouldn’t expect all of this chapter to have made sense yet.
In the next few chapters, we’ll start to dig deeper, filling in details of Python’s core object types that were omitted here so you can gain a more complete understanding.
We’ll start off in the next chapter with an in-depth look at Python numbers.
First, though, another quiz to review. ###### Test Your Knowledge: Quiz We’ll explore the concepts introduced in this chapter in more detail in upcoming chapters, so we’ll just cover the big ideas here: 1.
Name four of Python’s core data types. 2. Why are they called “core” data types? 3. What does “immutable” mean, and which three of Python’s core types are considered immutable? 4.
What does “sequence” mean, and which three types fall into that category? **|** ----- 5. What does “mapping” mean, and which core type is a mapping? 6.
What is “polymorphism,” and why should you care? ###### Test Your Knowledge: Answers 1.
Numbers, strings, lists, dictionaries, tuples, files, and sets are generally considered to be the core object (data) types. Types, None, and Booleans are sometimes classified this way as well.
There are multiple number types (integer, floating point, complex, fraction, and decimal) and multiple string types (simple strings and Unicode strings in Python 2.X, and text strings and byte strings in Python 3.X). 2.
They are known as “core” types because they are part of the Python language itself and are always available; to create other objects, you generally must call functions in imported modules.
Most of the core types have specific syntax for generating the objects: 'spam', for example, is an expression that makes a string and determines the set of operations that can be applied to it.
Because of this, core types are hardwired into Python’s syntax. In contrast, you must call the built-in open function to create a file object. 3.
An “immutable” object is an object that cannot be changed after it is created. Numbers, strings, and tuples in Python fall into this category.
While you cannot change an immutable object in-place, you can always make a new one by running an expression. 4. A “sequence” is a positionally ordered collection of objects.
Strings, lists, and tuples are all sequences in Python. They share common sequence operations, such as indexing, concatenation, and slicing, but also have type-specific method calls. 5.
The term “mapping” denotes an object that maps keys to associated values. Python’s dictionary is the only mapping type in the core type set.
Mappings do not maintain any left-to-right positional ordering; they support access to data stored by key, plus type-specific method calls. 6.
“Polymorphism” means that the meaning of an operation (like a +) depends on the objects being operated on.
This turns out to be a key idea (perhaps the key idea) behind using Python well—not constraining code to specific types makes that code automatically applicable to many types. **|** ----- ###### CHAPTER 5 ### Numeric Types This chapter begins our in-depth tour of the Python language.
In Python, data takes the form of objects—either built-in objects that Python provides, or objects we create using Python tools and other languages such as C.
In fact, objects are the basis of every Python program you will ever write.
Because they are the most fundamental notion in Python programming, objects are also our first focus in this book. In the preceding chapter, we took a quick pass over Python’s core object types.
Although essential terms were introduced in that chapter, we avoided covering too many specifics in the interest of space.
Here, we’ll begin a more careful second look at data type concepts, to fill in details we glossed over earlier.
Let’s get started by exploring our first data type category: Python’s numeric types. ###### Numeric Type Basics Most of Python’s number types are fairly typical and will probably seem familiar if you’ve used almost any other programming language in the past.
They can be used to keep track of your bank balance, the distance to Mars, the number of visitors to your website, and just about any other numeric quantity. In Python, numbers are not really a single object type, but a category of similar types. Python supports the usual numeric types (integers and floating points), ...
In addition, Python provides more advanced numeric programming support and objects for more advanced work. A complete inventory of Python’s numeric toolbox includes: - Integers and floating-point numbers - Complex numbers - Fixed-precision decimal numbers ----- - Rational fraction numbers - Sets - Boolean...
Before we jump into code, though, the next few sections get us started with a brief overview of how we write and process numbers in our scripts. ###### Numeric Literals Among its basic types, Python provides integers (positive and negative whole numbers) and floating-point numbers (numbers with a fractional part, som...
Python also allows us to write integers using hexadecimal, octal, and binary literals; offers a complex number type; and allows integers to have unlimited precision (they can grow to have as many digits as your memory space allows).
Table 5-1 shows what Python’s numeric types look like when written out in a program, as literals. _Table 5-1.
Basic numeric literals_ **Literal** **Interpretation** `1234, −24, 0, 99999999999999` Integers (unlimited size) `1.23, 1., 3.14e-10, 4E210, 4.0e+210` Floating-point numbers `0177, 0x9ff, 0b101010` Octal, hex, and binary literals in 2.6 `0o177, 0x9ff, 0b101010` Octal, hex, and binary literals in 3.0 `3+4j, 3.0+4...