Text stringlengths 1 9.41k |
|---|
In 3.0, they support
the P.__next__() method, but not the next(P) built-in; since the latter is defined to call
the former, it’s not clear if this behavior will endure in future releases (as described in
an earlier footnote, this appears to be an implementation issue). |
This is only an issue
for manual iteration, though; if you iterate over these objects automatically with for
loops and other iteration contexts (described in the next sections), they return successive lines in either Python version.
The iteration protocol also is the reason that we’ve had to wrap some results in a
```... |
Objects that are iterable return results one at a
```
time, not in a physical list:
```
>>> R = range(5)
```
`>>> R` _# Ranges are iterables in 3.0_
```
range(0, 5)
```
`>>> I = iter(R)` _# Use iteration protocol to produce results_
```
>>> next(I)
0
>>> next(I)
1
```
`>>> list(range(5))` _# Or use list... |
In fact, everything that scans left-to-right in Python employs the
iteration protocol in the same way—including the topic of the next section.
###### List Comprehensions: A First Look
Now that we’ve seen how the iteration protocol works, let’s turn to a very common use
case. |
Together with `for loops, list comprehensions are one of the most prominent`
contexts in which the iteration protocol is applied.
In the previous chapter, we learned how to use range to change a list as we step across
it:
```
>>> L = [1, 2, 3, 4, 5]
>>> for i in range(len(L)):
... |
L[i] += 10
...
>>> L
[11, 12, 13, 14, 15]
```
This works, but as I mentioned there, it may not be the optimal “best-practice” approach in Python. |
Today, the list comprehension expression makes many such prior
use cases obsolete. |
Here, for example, we can replace the loop with a single expression
that produces the desired result list:
```
>>> L = [x + 10 for x in L]
>>> L
[21, 22, 23, 24, 25]
```
The net result is the same, but it requires less coding on our part and is likely to run
substantially faster. |
The list comprehension isn’t exactly the same as the for loop statement version because it makes a new list object (which might matter if there are multiple
references to the original list), but it’s close enough for most applications and is a common and convenient enough approach to merit a closer look here.
**|**
... |
Syntactically, its syntax is derived
from a construct in set theory notation that applies an operation to each item in a set,
but you don’t have to know set theory to use this tool. |
In Python, most people find that
a list comprehension simply looks like a backward for loop.
To get a handle on the syntax, let’s dissect the prior section’s example in more detail:
```
>>> L = [x + 10 for x in L]
```
List comprehensions are written in square brackets because they are ultimately a way
to construct ... |
They begin with an arbitrary expression that we make up, which
uses a loop variable that we make up (x + 10). |
That is followed by what you should
now recognize as the header of a `for loop, which names the loop variable, and an`
iterable object (for x in L).
To run the expression, Python executes an iteration across `L inside the interpreter,`
assigning x to each item in turn, and collects the results of running the items thr... |
The result list we get back is exactly what the list comprehension says—a new list containing x + 10, for every x in L.
Technically speaking, list comprehensions are never really required because we can
always build up a list of expression results manually with for loops that append results
as we go:
```
>>> res = [... |
res.append(x + 10)
...
>>> res
[21, 22, 23, 24, 25]
```
In fact, this is exactly what the list comprehension does internally.
However, list comprehensions are more concise to write, and because this code pattern
of building up result lists is so common in Python work, they turn out to be very handy
in many cont... |
Moreover, list comprehensions can run much faster than manual
```
for loop statements (often roughly twice as fast) because their iterations are performed
```
at C language speed inside the interpreter, rather than with manual Python code; especially for larger data sets, there is a major performance advantage to usin... |
Recall that the file object has a readlines method that loads the file into
a list of line strings all at once:
```
>>> f = open('script1.py')
>>> lines = f.readlines()
```
**|**
-----
```
>>> lines
['import sys\n', 'print(sys.path)\n', 'x = 2\n', 'print(2 ** 33)\n']
```
This works, but the lines in the re... |
It would be nice if we could get rid of
these newlines all at once, wouldn’t it?
Any time we start thinking about performing an operation on each item in a sequence,
we’re in the realm of list comprehensions. |
For example, assuming the variable lines is
as it was in the prior interaction, the following code does the job by running each line
in the list through the string rstrip method to remove whitespace on the right side (a
```
line[:−1] slice would work, too, but only if we can be sure all lines are properly
```
terminat... |
Because list comprehensions are an iteration context just like
```
for loop statements, though, we don’t even have to open the file ahead of time. |
If we
```
open it inside the expression, the list comprehension will automatically use the iteration
protocol we met earlier in this chapter. |
That is, it will read one line from the file at a
time by calling the file’s next method, run the line through the rstrip expression, and
add it to the result list. |
Again, we get what we ask for—the rstrip result of a line, for
every line in the file:
```
>>> lines = [line.rstrip() for line in open('script1.py')]
>>> lines
['import sys', 'print(sys.path)', 'x = 2', 'print(2 ** 33)']
```
This expression does a lot implicitly, but we’re getting a lot of work for free here—
Py... |
It’s also an
efficient way to code this operation: because most of this work is done inside the Python
interpreter, it is likely much faster than an equivalent for statement. |
Again, especially
for large files, the speed advantages of list comprehensions can be significant.
Besides their efficiency, list comprehensions are also remarkably expressive. |
In our
example, we can run any string operation on a file’s lines as we iterate. |
Here’s the list
comprehension equivalent to the file iterator uppercase example we met earlier, along
with a few others (the method chaining in the second of these examples works because
string methods return a new string, to which we can apply another string method):
```
>>> [line.upper() for line in open('script1.p... |
As one particularly
useful extension, the for loop nested in the expression can have an associated if clause
to filter out of the result items for which the test is not true.
For example, suppose we want to repeat the prior section’s file-scanning example, but
we need to collect only lines that begin with the letter p... |
Adding an if filter clause to our expression
does the trick:
```
>>> lines = [line.rstrip() for line in open('script1.py') if line[0] == 'p']
>>> lines
['print(sys.path)', 'print(2 ** 33)']
```
Here, the if clause checks each line read from the file to see whether its first character
is p; if not, the line is om... |
This is a fairly big expression, but it’s
easy to understand if we translate it to its simple `for loop statement equivalent. |
In`
general, we can always translate a list comprehension to a for statement by appending
as we go and further indenting each successive part:
```
>>> res = []
>>> for line in open('script1.py'):
... |
if line[0] == 'p':
... |
res.append(line.rstrip())
...
>>> res
['print(sys.path)', 'print(2 ** 33)']
```
This `for statement equivalent works, but it takes up four lines instead of one and`
probably runs substantially slower.
List comprehensions can become even more complex if we need them to—for instance,
they may contain nested loops... |
In fact, their full syntax
allows for any number of for clauses, each of which can have an optional associated
```
if clause (we’ll be more formal about their syntax in Chapter 20).
```
For example, the following builds a list of the concatenation of x + y for every x in one
string and every y in another. |
It effectively collects the permutation of the characters in
two strings:
```
>>> [x + y for x in 'abc' for y in 'lmn']
['al', 'am', 'an', 'bl', 'bm', 'bn', 'cl', 'cm', 'cn']
```
**|**
-----
Again, one way to understand this expression is to convert it to statement form by
indenting its parts. |
The following is an equivalent, but likely slower, alternative way to
achieve the same effect:
```
>>> res = []
>>> for x in 'abc':
... for y in 'lmn':
... |
res.append(x + y)
...
>>> res
['al', 'am', 'an', 'bl', 'bm', 'bn', 'cl', 'cm', 'cn']
```
Beyond this complexity level, though, list comprehension expressions can often become too compact for their own good. |
In general, they are intended for simple types
of iterations; for more involved work, a simpler for statement structure will probably
be easier to understand and modify in the future. |
As usual in programming, if something
is difficult for you to understand, it’s probably not a good idea.
We’ll revisit list comprehensions in Chapter 20, in the context of functional programming tools; as we’ll see, they turn out to be just as related to functions as they are to
looping statements.
###### Other Itera... |
Because of this, it’s sometimes important to know which built-in tools make
use of it—any tool that employs the iteration protocol will automatically work on any
built-in type or user-defined class that provides it.
So far, I’ve been demonstrating iterators in the context of the for loop statement, because this part o... |
Keep in mind, though, that every
tool that scans from left to right across objects uses the iteration protocol. |
This includes
the for loops we’ve seen:
`>>> for line in open('script1.py'):` _# Use file iterators_
```
... |
print(line.upper(), end='')
...
IMPORT SYS
PRINT(SYS.PATH)
X = 2
PRINT(2 ** 33)
```
However, list comprehensions, the in membership test, the map built-in function, and
other built-ins such as the `sorted and` `zip calls also leverage the iteration protocol.`
When applied to a file, all of these use the file... |
map is similar to a list comprehension but is more limited because it requires a function instead of an arbitrary
expression. |
It also returns an iterable object itself in Python 3.0, so we must wrap it in
a list call to force it to give us all its values at once; more on this change later in this
chapter. |
Because `map, like the list comprehension, is related to both` `for loops and`
functions, we’ll also explore both again in Chapters 19 and 20.
Python includes various additional built-ins that process iterables, too: `sorted sorts`
items in an iterable, `zip combines items from iterables,` `enumerate pairs items in an... |
All of these accept iterables,
```
and zip, enumerate, and filter also return an iterable in Python 3.0, like map. |
Here they
are in action running the file’s iterator automatically to scan line by line:
```
>>> sorted(open('script1.py'))
['import sys\n', 'print(2 ** 33)\n', 'print(sys.path)\n', 'x = 2\n']
>>> list(zip(open('script1.py'), open('script1.py')))
[('import sys\n', 'import sys\n'), ('print(sys.path)\n', 'print(sy... |
We met zip and enumerate
in the prior chapter; filter and reduce are in Chapter 19’s functional programming
domain, so we’ll defer details for now.
We first saw the sorted function used here at work in Chapter 4, and we used it for
dictionaries in Chapter 8. |
sorted is a built-in that employs the iteration protocol—it’s
like the original list sort method, but it returns the new sorted list as a result and runs
**|**
-----
on any iterable object. |
Notice that, unlike `map and others,` `sorted returns an actual`
_list in Python 3.0 instead of an iterable._
Other built-in functions support the iteration protocol as well (but frankly, are harder
to cast in interesting examples related to files). |
For example, the sum call computes the
sum of all the numbers in any iterable; the any and all built-ins return True if any or
all items in an iterable are True, respectively; and max and min return the largest and
smallest item in an iterable, respectively. |
Like reduce, all of the tools in the following
examples accept any iterable as an argument and use the iteration protocol to scan it,
but return a single result:
`>>> sum([3, 2, 4, 1, 5, 0])` _# sum expects numbers only_
```
15
>>> any(['spam', '', 'ni'])
True
>>> all(['spam', '', 'ni'])
False
>>> max([3, ... |
Consequently, all of these will also work on an open file and automatically read one line at
a time:
```
>>> list(open('script1.py'))
['import sys\n', 'print(sys.path)\n', 'x = 2\n', 'print(2 ** 33)\n']
>>> tuple(open('script1.py'))
('import sys\n', 'print(sys.path)\n', 'x = 2\n', 'print(2 ** 33)\n')
>>> '&&'... |
For that
matter, so does the set call, as well as the new set and dictionary comprehension ex_pressions in Python 3.0, which we met in Chapters 4, 5, and 8:_
```
>>> set(open('script1.py'))
{'print(sys.path)\n', 'x = 2\n', 'print(2 ** 33)\n', 'import sys\n'}
>>> {line for line in open('script1.py')}
{'print(sys... |
As you can probably predict
by now, this accepts any iterable, too, including files (see Chapter 18 for more details
on the call syntax):
```
>>> def f(a, b, c, d): print(a, b, c, d, sep='&')
...
>>> f(1, 2, 3, 4)
1&2&3&4
```
`>>> f(*[1, 2, 3, 4])` _# Unpacks into arguments_
```
1&2&3&4
```
`>>> f(*open('sc... |
To see how these have been absorbed into the
iteration protocol in Python 3.0 as well, we need to move on to the next section.
###### New Iterables in Python 3.0
One of the fundamental changes in Python 3.0 is that it has a stronger emphasis on
iterators than 2.X. |
In addition to the iterators associated with built-in types such as files
and dictionaries, the dictionary methods keys, values, and items return iterable objects
in Python 3.0, as do the built-in functions range, map, zip, and filter. |
As shown in the
prior section, the last three of these functions both return iterators and process them.
All of these tools produce results on demand in Python 3.0, instead of constructing
result lists as they do in 2.6.
Although this saves memory space, it can impact your coding styles in some contexts.
In various pl... |
In 3.0,`
though, they return iterable objects, producing results on demand. |
This means extra
typing is required to display the results at the interactive prompt (and possibly in some
other contexts), but it’s an asset in larger programs—delayed evaluation like this conserves memory and avoids pauses while large result lists are computed. |
Let’s take a
quick look at some of the new 3.0 iterables in action.
**|**
-----
###### The range Iterator
We studied the range built-in’s basic behavior in the prior chapter. |
In 3.0, it returns an
iterator that generates numbers in the range on demand, instead of building the result
list in memory. |
This subsumes the older 2.X xrange (see the upcoming version skew
note), and you must use list(range(...)) to force an actual range list if one is needed
(e.g., to display results):
```
C:\\misc> c:\python30\python
```
`>>> R = range(10)` _# range returns an iterator, not a list_
```
>>> R
range(0, 10)
```
`>>>... |
They do not support any other sequence operations
(use list(...) if you require more list tools):
`>>> len(R)` _# range also does len and indexing, but no others_
```
10
>>> R[0]
0
>>> R[-1]
9
```
`>>> next(I)` _# Continue taking from iterator, where left off_
```
3
```
`>>> I.__next__()` _# .next() beco... |
Since this is exactly what the new iteratorbased range does in Python 3.0, xrange is no longer available in 3.0—it
has been subsumed. |
You may still see it in 2.X code, though, especially
since range builds result lists there and so is not as efficient in its memory
usage. |
As noted in a sidebar in the prior chapter, the `file.xread`
```
lines() method used to minimize memory use in 2.X has been dropped
```
in Python 3.0 for similar reasons, in favor of file iterators.
**|**
-----
###### The map, zip, and filter Iterators
Like range, the map, zip, and filter built-ins also be... |
All three not only
process iterables, as in 2.X, but also return iterable results in 3.0. |
Unlike range, though,
they are their own iterators—after you step through their results once, they are exhausted. |
In other words, you can’t have multiple iterators on their results that maintain
different positions in those results.
Here is the case for the map built-in we met in the prior chapter. |
As with other iterators,
you can force a list with list(...) if you really need one, but the default behavior can
save substantial space in memory for large result sets:
`>>> M = map(abs, (-1, 0, 1))` _# map returns an iterator, not a list_
```
>>> M
<map object at 0x0276B890>
```
`>>> next(M)` _# Use iterator ma... |
In Chapter 20, we’ll
```
also find that generator functions and expressions behave like map and zip instead of
```
range in this regard, supporting a single active iteration. |
In that chapter, we’ll see some
```
subtle implications of one-shot iterators in loops that attempt to scan multiple times.
###### Dictionary View Iterators
As we saw briefly in Chapter 8, in Python 3.0 the dictionary keys, values, and items
methods return iterable view objects that generate result items one at a ti... |
View items maintain the same physical
ordering as that of the dictionary and reflect changes made to the underlying dictionary.
Now that we know more about iterators, here’s the rest of the story:
```
>>> D = dict(a=1, b=2, c=3)
>>> D
{'a': 1, 'c': 3, 'b': 2}
```
`>>> K = D.keys()` _# A view object in 3.0, not a... |
However, this usually isn’t required except to display
results interactively or to apply list operations like indexing:
```
>>> K = D.keys()
```
`>>> list(K)` _# Can still force a real list if needed_
```
['a', 'c', 'b']
```
`>>> V = D.values()` _# Ditto for values() and items() views_
```
>>> V
<dict_values ... |
Thus, it’s not often necessary to call keys directly in this context:
`>>> D` _# Dictionaries still have own iterator_
```
{'a': 1, 'c': 3, 'b': 2} # Returns next key on each iteration
>>> I = iter(D)
>>> next(I)
'a'
>>> next(I)
'c'
```
`>>> for key in D: print(key, end=' ')` _# Still no need to c... |
# But keys is an iterator in 3.0 too!
a c b
```
Finally, remember again that because keys no longer returns a list, the traditional coding
pattern for scanning a dictionary by sorted keys won’t work in 3.0. |
Instead, convert
keys views first with a `list call, or use the` `sorted call on either a keys view or the`
dictionary itself, as follows:
```
>>> D
{'a': 1, 'c': 3, 'b': 2}
>>> for k in sorted(D.keys())): print(k, D[k], end=' ')
...
a 1 b 2 c 3
>>> D
{'a': 1, 'c': 3, 'b': 2}
```
`>>> for k in sorted(D):... |
As you’ll see
later:
- User-defined functions can be turned into iterable _generator functions, with_
```
yield statements.
```
- List comprehensions morph into iterable _generator expressions when coded in_
parentheses.
- User-defined classes are made iterable with `__iter__ or` `__getitem__` _operator_
_overl... |
We took our first
substantial look at the iteration protocol in Python—a way for nonsequence objects to
take part in iteration loops—and at list comprehensions. |
As we saw, a list comprehension is an expression similar to a for loop that applies another expression to all the
items in any iterable object. |
Along the way, we also saw other built-in iteration tools
at work and studied recent iteration additions in Python 3.0.
This wraps up our tour of specific procedural statements and related tools. |
The next
chapter closes out this part of the book by discussing documentation options for Python
code; documentation is also part of the general syntax model, and it’s an important
component of well-written programs. |
In the next chapter, we’ll also dig into a set of
exercises for this part of the book before we turn our attention to larger structures such
as functions. |
As usual, though, let’s first exercise what we’ve learned here with a quiz.
###### Test Your Knowledge: Quiz
1. How are for loops and iterators related?
2. |
How are for loops and list comprehensions related?
3. Name four iteration contexts in the Python language.
4. What is the best way to read line by line from a text file today?
5. |
What sort of weapons would you expect to see employed by the Spanish
Inquisition?
**|**
-----
###### Test Your Knowledge: Answers
1. |
The for loop uses the iteration protocol to step through items in the object across
which it is iterating. |
It calls the object’s __next__ method (run by the next built-in)
on each iteration and catches the StopIteration exception to determine when to
stop looping. |
Any object that supports this model works in a for loop and in other
iteration contexts.
2. Both are iteration tools. |
List comprehensions are a concise and efficient way to
perform a common for loop task: collecting the results of applying an expression
to all items in an iterable object. |
It’s always possible to translate a list comprehension to a for loop, and part of the list comprehension expression looks like the
header of a for loop syntactically.
3. |
Iteration contexts in Python include the `for loop; list comprehensions; the` `map`
built-in function; the in membership test expression; and the built-in functions
```
sorted, sum, any, and all. |
This category also includes the list and tuple built-ins,
```
string join methods, and sequence assignments, all of which use the iteration protocol (the __next__ method) to step across iterable objects one item at a time.
4. |
The best way to read lines from a text file today is to not read it explicitly at all:
instead, open the file within an iteration context such as a for loop or list comprehension, and let the iteration tool automatically scan one line at a time by
running the file’s next method on each iteration. |
This approach is generally best
in terms of coding simplicity, execution speed, and memory space requirements.
5. |
I’ll accept any of the following as correct answers: fear, intimidation, nice red uniforms, a comfy chair, and soft pillows.
**|**
-----
-----
###### CHAPTER 15
### The Documentation Interlude
This part of the book concludes with a look at techniques and tools used for
documenting Python code. |
Although Python code is designed to be readable, a few
well-placed human-readable comments can do much to help others understand the
workings of your programs. |
Python includes syntax and tools to make documentation
easier.
Although this is something of a tools-related concept, the topic is presented here partly
because it involves Python’s syntax model, and partly as a resource for readers struggling to understand Python’s toolset. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.