Text stringlengths 1 9.41k |
|---|
x += 1
...
>>> L
[1, 2, 3, 4, 5]
>>> x
6
```
This doesn’t quite work—it changes the loop variable x, not the list L. The reason is
somewhat subtle. |
Each time through the loop, x refers to the next integer already pulled
out of the list. In the first iteration, for example, x is integer 1. |
In the next iteration, the
loop body sets x to a different object, integer 2, but it does not update the list where 1
originally came from.
To really change the list as we march across it, we need to use indexes so we can assign
an updated value to each position as we go. |
The range/len combination can produce
the required indexes for us:
```
>>> L = [1, 2, 3, 4, 5]
```
`>>> for i in range(len(L)):` _# Add one to each item in L_
`... |
L[i] += 1` _# Or L[i] = L[i] + 1_
```
...
>>> L
[2, 3, 4, 5, 6]
```
When coded this way, the list is changed as we proceed through the loop. |
There is no
way to do the same with a simple for x in L:-style loop, because such a loop iterates
through actual items, not list positions. But what about the equivalent while loop? |
Such
a loop requires a bit more work on our part, and likely runs more slowly:
```
>>> i = 0
>>> while i < len(L):
... L[i] += 1
```
**|** **f**
-----
```
... |
i += 1
...
>>> L
[3, 4, 5, 6, 7]
```
Here again, though, the range solution may not be ideal either. |
A list comprehension
expression of the form:
```
[x+1 for x in L]
```
would do similar work, albeit without changing the original list in-place (we could
assign the expression’s new list object result back to L, but this would not update any
other references to the original list). |
Because this is such a central looping concept, we’ll
save a complete exploration of list comprehensions for the next chapter.
###### Parallel Traversals: zip and map
As we’ve seen, the range built-in allows us to traverse sequences with for in a nonexhaustive fashion. |
In the same spirit, the built-in zip function allows us to use for loops
to visit multiple sequences in parallel. |
In basic operation, zip takes one or more sequences as arguments and returns a series of tuples that pair up parallel items taken
from those sequences. |
For example, suppose we’re working with two lists:
```
>>> L1 = [1,2,3,4]
>>> L2 = [5,6,7,8]
```
To combine the items in these lists, we can use zip to create a list of tuple pairs (like
```
range, zip is an iterable object in 3.0, so we must wrap it in a list call to display all its
```
results at once—more on i... |
print(x, y, '--', x+y)
...
1 5 -- 6
2 6 -- 8
3 7 -- 10
4 8 -- 12
```
Here, we step over the result of the zip call—that is, the pairs of items pulled from the
two lists. |
Notice that this for loop again uses the tuple assignment form we met earlier
to unpack each tuple in the zip result. |
The first time through, it’s as though we ran the
assignment statement (x, y) = (1, 5).
**|**
-----
The net effect is that we scan both L1 _and_ `L2 in our loop. |
We could achieve a similar`
effect with a while loop that handles indexing manually, but it would require more
typing and would likely run more slowly than the for/zip approach.
Strictly speaking, the zip function is more general than this example suggests. |
For instance, it accepts any type of sequence (really, any iterable object, including files), and
it accepts more than two arguments. |
With three arguments, as in the following example, it builds a list of three-item tuples with items from each sequence, essentially projecting by columns (technically, we get an N-ary tuple for N arguments):
```
>>> T1, T2, T3 = (1,2,3), (4,5,6), (7,8,9)
>>> T3
(7, 8, 9)
>>> list(zip(T1, T2, T3))
[(1, 4, 7), ... |
In the following, we zip together two strings to pick out characters in parallel, but the result has only as many tuples as the length of the shortest
sequence:
```
>>> S1 = 'abc'
>>> S2 = 'xyz123'
>>>
>>> list(zip(S1, S2))
[('a', 'x'), ('b', 'y'), ('c', 'z')]
###### map equivalence in Python 2.6
```
In Pyt... |
Normally, map takes a function and one or more sequence arguments and collects
the results of calling the function with parallel items taken from the sequence(s). |
We’ll
study map in detail in Chapters 19 and 20, but as a brief example, the following maps
the built-in ord function across each item in a string and collects the results (like zip,
```
map is a value generator in 3.0 and so must be passed to list to collect all its results at
```
once):
```
>>> list(map(ord, 'spam... |
In 3.0, either use zip or write loop code to pad
results yourself. |
We’ll see how to do this in Chapter 20, after we’ve had
a chance to study some additional iteration concepts.
###### Dictionary construction with zip
In Chapter 8, I suggested that the zip call used here can also be handy for generating
dictionaries when the sets of keys and values must be computed at runtime. |
Now that
we’re becoming proficient with zip, I’ll explain how it relates to dictionary construction. |
As you’ve learned, you can always create a dictionary by coding a dictionary literal,
or by assigning to keys over time:
```
>>> D1 = {'spam':1, 'eggs':3, 'toast':5}
>>> D1
{'toast': 5, 'eggs': 3, 'spam': 1}
>>> D1 = {}
>>> D1['spam'] = 1
>>> D1['eggs'] = 3
>>> D1['toast'] = 5
```
What to do, though, if ... |
For example, say you had the following keys
and values lists:
```
>>> keys = ['spam', 'eggs', 'toast']
>>> vals = [1, 3, 5]
```
One solution for turning those lists into a dictionary would be to zip the lists and step
through them in parallel with a for loop:
```
>>> list(zip(keys, vals))
[('spam', 1), ('eggs'... |
Calling it achieves something like a listto-dictionary conversion, but it’s really an object construction request. |
In the next
chapter we’ll explore a related but richer concept, the list comprehension, which builds
lists in a single expression; we’ll also revisit 3.0 dictionary comprehensions an alternative
to the dict cal for zipped key/value pairs.
###### Generating Both Offsets and Items: enumerate
Earlier, we discussed using... |
In some programs, though, we need both: the item to use,
plus an offset as we go. |
Traditionally, this was coded with a simple for loop that also
kept a counter of the current offset:
```
>>> S = 'spam'
>>> offset = 0
>>> for item in S:
... |
print(item, 'appears at offset', offset)
... |
offset += 1
...
s appears at offset 0
p appears at offset 1
a appears at offset 2
m appears at offset 3
```
This works, but in recent Python releases a new built-in named enumerate does the job
for us:
```
>>> S = 'spam'
>>> for (offset, item) in enumerate(S):
... |
print(item, 'appears at offset', offset)
...
s appears at offset 0
p appears at offset 1
a appears at offset 2
m appears at offset 3
```
The enumerate function returns a generator object—a kind of object that supports the
iteration protocol that we will study in the next chapter and will discuss in more deta... |
In short, it has a __next__ method called by the next builtin function, which returns an (index, `value) tuple each time through the loop. |
We can`
unpack these tuples with tuple assignment in the for loop (much like using zip):
**|** **f**
-----
```
>>> E = enumerate(S)
>>> E
<enumerate object at 0x02765AA8>
>>> next(E)
(0, 's')
>>> next(E)
(1, 'p')
>>> next(E)
(2, 'a')
```
As usual, we don’t normally see this machinery because iter... |
We looked at the while and for loop statements in depth,
and we learned about their associated `else clauses. |
We also studied the` `break and`
```
continue statements, which have meaning only inside loops, and met several built-in
```
tools commonly used in for loops, including range, zip, map, and enumerate (although
their roles as iterators in Python 3.0 won’t be fully uncovered until the next chapter).
In the next chapter... |
There,
we’ll also explain some of the subtleties of iterable tools we met here, such as range and
```
zip. |
As always, though, before moving on let’s exercise what you’ve picked up here
```
with a quiz.
###### Test Your Knowledge: Quiz
1. |
What are the main functional differences between a while and a for?
2. What’s the difference between break and continue?
3. When is a loop’s else clause executed?
4. |
How can you code a counter-based loop in Python?
5. What can a range be used for in a for loop?
**|**
-----
###### Test Your Knowledge: Answers
1. |
The while loop is a general looping statement, but the for is designed to iterate
across items in a sequence (really, iterable). |
Although the `while can imitate the`
```
for with counter loops, it takes more code and might run slower.
```
2. |
The `break statement exits a loop immediately (you wind up below the entire`
```
while or for loop statement), and continue jumps back to the top of the loop (you
```
wind up positioned just before the test in while or the next item fetch in for).
3. |
The else clause in a while or for loop will be run once as the loop is exiting, if the
loop exits normally (without running into a break statement). |
A break exits the
loop immediately, skipping the else part on the way out (if there is one).
4. |
Counter loops can be coded with a while statement that keeps track of the index
manually, or with a for loop that uses the range built-in function to generate successive integer offsets. |
Neither is the preferred way to work in Python, if you need
to simply step across all the items in a sequence. |
Instead, use a simple for loop
instead, without range or counters, whenever possible; it will be easier to code and
usually quicker to run.
5. |
The range built-in can be used in a for to implement a fixed number of repetitions,
to scan by offsets instead of items at offsets, to skip successive items as you go, and
to change a list while stepping across it. |
None of these roles requires range, and
most have alternatives—scanning actual items, three-limit slices, and list comprehensions are often better solutions today (despite the natural inclinations of ex-C
programmers to want to count things!).
**|** **f**
-----
###### CHAPTER 14
### Iterations and Comprehensions, P... |
Although
they can handle most repetitive tasks programs need to perform, the need to iterate
over sequences is so common and pervasive that Python provides additional tools to
make it simpler and more efficient. |
This chapter begins our exploration of these tools.
Specifically, it presents the related concepts of Python’s iteration protocol—a methodcall model used by the for loop—and fills in some details on list comprehensions—a
close cousin to the for loop that applies an expression to items in an iterable.
Because both of t... |
With practice, though, you’ll find that these tools are useful and
powerful. |
Although never strictly required, because they’ve become commonplace in
Python code, a basic understanding can also help if you must read programs written
by others.
###### Iterators: A First Look
In the preceding chapter, I mentioned that the for loop can work on any sequence type
in Python, including lists, tuples,... |
In fact, this is true of all iteration tools that scan objects from left to right_
in Python, including for loops, the list comprehensions we’ll study in this chapter, in
membership tests, the map built-in function, and more.
The concept of “iterable objects” is relatively recent in Python, but it has come to
permeate... |
It’s essentially a generalization of the notion of sequences—an object is considered iterable if it is either a physically stored sequence or
an object that produces one result at a time in the context of an iteration tool like a
`for loop. |
In a sense, iterable objects include both physical sequences and` _virtual_
_sequences computed on demand.[*]_
###### The Iteration Protocol: File Iterators
One of the easiest ways to understand what this means is to look at how it works with
a built-in type such as the file. |
Recall from Chapter 9 that open file objects have a
method called readline, which reads one line of text from a file at a time—each time
we call the readline method, we advance to the next line. |
At the end of the file, an
empty string is returned, which we can detect to break out of the loop:
`>>> f = open('script1.py')` _# Read a 4-line script file in this directory_
`>>> f.readline()` _# readline loads one line on each call_
```
'import sys\n'
>>> f.readline()
'print(sys.path)\n'
>>> f.readline()
... |
The only noticeable difference
is that __next__ raises a built-in StopIteration exception at end-of-file instead of returning an empty string:
`>>> f = open('script1.py')` _# __next__ loads one line on each call too_
`>>> f.__next__()` _# But raises an exception at end-of-file_
```
'import sys\n'
>>> f.__next__()
... |
This text uses the terms “iterable” and “iterator”
interchangeably to refer to an object that supports iteration in general. |
Sometimes the term “iterable” refers
to an object that supports iter and “iterator” refers to an object return by iter that supports next(I), but
that convention is not universal in either the Python world or this book.
**|**
-----
```
>>> f.__next__()
'x = 2\n'
>>> f.__next__()
'print(2 ** 33)\n'
>>> f._... |
Any object with
a __next__ method to advance to a next result, which raises StopIteration at the end
of the series of results, is considered iterable in Python. |
Any such object may also be
stepped through with a for loop or other iteration tool, because all iteration tools normally work internally by calling `__next__ on each iteration and catching the`
```
StopIteration exception to determine when to exit.
```
The net effect of this magic is that, as mentioned in Chapter 9, ... |
The file object’s
iterator will do the work of automatically loading lines as you go. |
The following, for
example, reads a file line by line, printing the uppercase version of each line along the
way, without ever explicitly reading from the file at all:
`>>> for line in open('script1.py'):` _# Use file iterators to read by lines_
`... |
print(line.upper(), end='')` _# Calls __next__, catches StopIteration_
```
...
IMPORT SYS
PRINT(SYS.PATH)
X = 2
PRINT(2 ** 33)
```
Notice that the print uses end='' here to suppress adding a \n, because line strings
already have one (without this, our output would be double-spaced). |
This is considered
the best way to read text files line by line today, for three reasons: it’s the simplest to
code, might be the quickest to run, and is the best in terms of memory usage. |
The older,
original way to achieve the same effect with a for loop is to call the file readlines method
to load the file’s content into memory as a list of line strings:
```
>>> for line in open('script1.py').readlines():
... |
print(line.upper(), end='')
...
IMPORT SYS
PRINT(SYS.PATH)
X = 2
PRINT(2 ** 33)
```
This readlines technique still works, but it is not considered the best practice today
and performs poorly in terms of memory usage. |
In fact, because this version really does
load the entire file into memory all at once, it will not even work for files too big to fit
into the memory space available on your computer. |
By contrast, because it reads one
line at a time, the iterator-based version is immune to such memory-explosion issues.
**|**
-----
The iterator version might run quicker too, though this can vary per release (Python
3.0 made this advantage less clear-cut by rewriting I/O libraries to support Unicode
text and be le... |
line = f.readline()
... if not line: break
... |
print(line.upper(), end='')
...
...same output...
```
However, this may run slower than the iterator-based for loop version, because iterators run at C language speed inside Python, whereas the while loop version runs Python
byte code through the Python virtual machine. |
Any time we trade Python code for C
code, speed tends to increase. |
This is not an absolute truth, though, especially in Python
3.0; we’ll see timing techniques later in this book for measuring the relative speed of
alternatives like these.
###### Manual Iteration: iter and next
To support manual iteration code (with less typing), Python 3.0 also provides a builtin function, next, th... |
Given an iterable object X, the call next(X) is the same as X.__next__(), but noticeably simpler. |
With
files, for instance, either form may be used:
```
>>> f = open('script1.py')
```
`>>> f.__next__()` _# Call iteration method directly_
```
'import sys\n'
>>> f.__next__()
'print(sys.path)\n'
>>> f = open('script1.py')
```
`>>> next(f)` _# next built-in calls __next___
```
'import sys\n'
>>> next(f)... |
When the for loop begins,
it obtains an iterator from the iterable object by passing it to the iter built-in function;
the object returned by iter has the required next method. |
This becomes obvious if we
look at how for loops internally process built-in sequence types such as lists:
```
>>> L = [1, 2, 3]
```
`>>> I = iter(L)` _# Obtain an iterator object_
`>>> I.next()` _# Call next to advance to next item_
```
1
>>> I.next()
2
```
**|**
-----
```
>>> I.next()
3
>>> I.next(... |
That
is, files have their own __next__ method and so do not need to return a different object
that does:
```
>>> f = open('script1.py')
>>> iter(f) is f
True
>>> f.__next__()
'import sys\n'
```
Lists, and many other built-in objects, are not their own iterators because they support
multiple open iterations. |
For such objects, we must call iter to start iterating:
```
>>> L = [1, 2, 3]
>>> iter(L) is L
False
>>> L.__next__()
AttributeError: 'list' object has no attribute '__next__'
>>> I = iter(L)
>>> I.__next__()
1
```
`>>> next(I)` _# Same as I.__next__()_
```
2
```
Although Python iteration tools call... |
The following interaction demonstrates the
equivalence between automatic and manual iteration:[†]
```
>>> L = [1, 2, 3]
>>>
```
`>>> for X in L:` _# Automatic iteration_
`... |
print(X ** 2, end=' ')` _# Obtains iter, calls __next__, catches exceptions_
```
...
1 4 9
```
`>>> I = iter(L)` _# Manual iteration: what for loops usually do_
† Technically speaking, the for loop calls the internal equivalent of I.__next__, instead of the next(I) used
here. |
There is rarely any difference between the two, but as we’ll see in the next section, there are some builtin objects in 3.0 (such as os.popen results) that support the former and not the latter, but may be still be
iterated across in for loops. |
Your manual iterations can generally use either call scheme. |
If you care for the
full story, in 3.0 os.popen results have been reimplemented with the subprocess module and a wrapper class,
whose __getattr__ method is no longer called in 3.0 for implicit __next__ fetches made by the next built-in,
but is called for explicit fetches by name—a 3.0 change issue we’ll confront in Cha... |
Also in 3.0, the related 2.6 calls os.popen2/3/4 are no longer
available; use subprocess.Popen with appropriate arguments instead (see the Python 3.0 library manual for
the new required code).
**|**
-----
```
>>> while True:
```
`... |
try:` _# try statement catches exceptions_
`... X = next(I)` _# Or call I.__next___
```
... except StopIteration:
... break
... |
print(X ** 2, end=' ')
...
1 4 9
```
To understand this code, you need to know that try statements run an action and catch
exceptions that occur while the action runs (we’ll explore exceptions in depth in
Part VII). |
I should also note that for loops and other iteration contexts can sometimes
work differently for user-defined classes, repeatedly indexing an object instead of running the iteration protocol. |
We’ll defer that story until we study class operator overloading in Chapter 29.
_Version skew note: In Python 2.6, the iteration method is named_
```
X.next() instead of X.__next__(). |
For portability, the next(X) built-in
```
function is available in Python 2.6 too (but not earlier), and calls 2.6’s
```
X.next() instead of 3.0’s X.__next__(). |
Iteration works the same in 2.6
```
in all other ways, though; simply use X.next() or next(X) for manual
iterations, instead of 3.0’s `X.__next__(). |
Prior to 2.6, use manual`
```
X.next() calls instead of next(X).
###### Other Built-in Type Iterators
```
Besides files and physical sequences like lists, other types have useful iterators as well.
The classic way to step through the keys of a dictionary, for example, is to request its
keys list explicitly:
``... |
print(key, D[key])
...
a 1
c 3
b 2
```
In recent versions of Python, though, dictionaries have an iterator that automatically
returns one key at a time in an iteration context:
```
>>> I = iter(D)
>>> next(I)
'a'
>>> next(I)
'c'
>>> next(I)
'b'
>>> next(I)
Traceback (most recent call last):
... |
print(key, D[key])
...
a 1
c 3
b 2
```
We can’t delve into their details here, but other Python object types also support the
iterator protocol and thus may be used in for loops too. |
For instance, shelves (an accessby-key filesystem for Python objects) and the results from os.popen (a tool for reading
the output of shell commands) are iterable as well:
```
>>> import os
>>> P = os.popen('dir')
>>> P.__next__()
' Volume in drive C is SQ004828V03\n'
>>> P.__next__()
' Volume Serial Number... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.