forked from csev/py4e
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbook009.html
More file actions
638 lines (632 loc) · 45.4 KB
/
book009.html
File metadata and controls
638 lines (632 loc) · 45.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="generator" content="hevea 2.09" />
<link rel="stylesheet" type="text/css" href="book.css" />
<title>Lists</title>
</head>
<body>
<a href="book008.html"><img src="previous_motif.gif" alt="Previous" /></a>
<a href="index.html"><img src="contents_motif.gif" alt="Up" /></a>
<a href="book010.html"><img src="next_motif.gif" alt="Next" /></a>
<hr />
<h1 class="chapter" id="sec100"><span class="c006">Chapter 8  Lists</span></h1>
<p><a id="hevea_default446"></a><span class="c005">
</span><a id="hevea_default447"></a></p><span class="c005">
</span><h2 class="section" id="sec101"><span class="c006">8.1  A list is a sequence</span></h2>
<p><span class="c006">Like a string, a <span class="c009">list</span> is a sequence of values. In a string, the
values are characters; in a list, they can be any type. The values in
list are called <span class="c009">elements</span> or sometimes <span class="c009">items</span>.</span></p><p><a id="hevea_default448"></a><span class="c005">
</span><a id="hevea_default449"></a><span class="c005">
</span><a id="hevea_default450"></a></p><p><span class="c006">There are several ways to create a new list; the simplest is to
enclose the elements in square brackets (<code>[</code> and <code>]</code>):</span></p><pre class="verbatim"><span class="c004">[10, 20, 30, 40]
['crunchy frog', 'ram bladder', 'lark vomit']
</span></pre><p><span class="c006">The first example is a list of four integers. The second is a list of
three strings. The elements of a list don’t have to be the same type.
The following list contains a string, a float, an integer, and
(lo!) another list:</span></p><pre class="verbatim"><span class="c004">['spam', 2.0, 5, [10, 20]]
</span></pre><p><span class="c006">A list within another list is <span class="c009">nested</span>.</span></p><p><a id="hevea_default451"></a><span class="c005">
</span><a id="hevea_default452"></a></p><p><span class="c006">A list that contains no elements is
called an empty list; you can create one with empty
brackets, <code>[]</code>.</span></p><p><a id="hevea_default453"></a><span class="c005">
</span><a id="hevea_default454"></a></p><p><span class="c006">As you might expect, you can assign list values to variables:</span></p><pre class="verbatim"><span class="c004">>>> cheeses = ['Cheddar', 'Edam', 'Gouda']
>>> numbers = [17, 123]
>>> empty = []
>>> print cheeses, numbers, empty
['Cheddar', 'Edam', 'Gouda'] [17, 123] []
</span></pre><p><a id="hevea_default455"></a></p><span class="c005">
</span><h2 class="section" id="sec102"><span class="c006">8.2  Lists are mutable</span></h2>
<p><a id="hevea_default456"></a><span class="c005">
</span><a id="hevea_default457"></a><span class="c005">
</span><a id="hevea_default458"></a><span class="c005">
</span><a id="hevea_default459"></a><span class="c005">
</span><a id="hevea_default460"></a></p><p><span class="c006">The syntax for accessing the elements of a list is the same as for
accessing the characters of a string—the bracket operator. The
expression inside the brackets specifies the index. Remember that the
indices start at 0:</span></p><pre class="verbatim"><span class="c004">>>> print cheeses[0]
Cheddar
</span></pre><p><span class="c006">Unlike strings, lists are mutable because you can change the order
of items in a list or reassign an item in a list.
When the bracket operator appears on the left side of an assignment,
it identifies the element of the list that will be assigned.</span></p><p><a id="hevea_default461"></a></p><pre class="verbatim"><span class="c004">>>> numbers = [17, 123]
>>> numbers[1] = 5
>>> print numbers
[17, 5]
</span></pre><p><span class="c006">The one-eth element of <span class="c001">numbers</span>, which
used to be 123, is now 5.</span></p><p><a id="hevea_default462"></a><span class="c005">
</span><a id="hevea_default463"></a></p><p><span class="c006">You can think of a list as a relationship between indices and
elements. This relationship is called a <span class="c009">mapping</span>; each index
“maps to” one of the elements. </span></p><p><a id="hevea_default464"></a><span class="c005">
</span><a id="hevea_default465"></a></p><p><span class="c006">List indices work the same way as string indices:</span></p><ul class="itemize"><li class="li-itemize"><span class="c006">Any integer expression can be used as an index.</span></li><li class="li-itemize"><span class="c006">If you try to read or write an element that does not exist, you
get an <span class="c001">IndexError</span>.</span><p><a id="hevea_default466"></a><span class="c005">
</span><a id="hevea_default467"></a></p></li><li class="li-itemize"><span class="c006">If an index has a negative value, it counts backward from the
end of the list.</span></li></ul><p><a id="hevea_default468"></a></p><p><a id="hevea_default469"></a><span class="c005">
</span><a id="hevea_default470"></a><span class="c005">
</span><a id="hevea_default471"></a><span class="c005">
</span><a id="hevea_default472"></a></p><p><span class="c006">The <span class="c001">in</span> operator also works on lists.</span></p><pre class="verbatim"><span class="c004">>>> cheeses = ['Cheddar', 'Edam', 'Gouda']
>>> 'Edam' in cheeses
True
>>> 'Brie' in cheeses
False
</span></pre><span class="c005">
</span><h2 class="section" id="sec103"><span class="c006">8.3  Traversing a list</span></h2>
<p><span class="c005">
</span><a id="hevea_default473"></a><span class="c005">
</span><a id="hevea_default474"></a><span class="c005">
</span><a id="hevea_default475"></a><span class="c005">
</span><a id="hevea_default476"></a><span class="c005">
</span><a id="hevea_default477"></a></p><p><span class="c006">The most common way to traverse the elements of a list is
with a <span class="c001">for</span> loop. The syntax is the same as for strings:</span></p><pre class="verbatim"><span class="c004">for cheese in cheeses:
print cheese
</span></pre><p><span class="c006">This works well if you only need to read the elements of the
list. But if you want to write or update the elements, you
need the indices. A common way to do that is to combine
the functions <span class="c001">range</span> and <span class="c001">len</span>:</span></p><p><a id="hevea_default478"></a><span class="c005">
</span><a id="hevea_default479"></a></p><pre class="verbatim"><span class="c004">for i in range(len(numbers)):
numbers[i] = numbers[i] * 2
</span></pre><p><span class="c006">This loop traverses the list and updates each element. <span class="c001">len</span>
returns the number of elements in the list. <span class="c001">range</span> returns
a list of indices from 0 to <span class="c007">n</span>−1, where <span class="c007">n</span> is the length of
the list. Each time through the loop <span class="c001">i</span> gets the index
of the next element. The assignment statement in the body uses
<span class="c001">i</span> to read the old value of the element and to assign the
new value.</span></p><p><a id="hevea_default480"></a><span class="c005">
</span><a id="hevea_default481"></a></p><p><span class="c006">A <span class="c001">for</span> loop over an empty list never executes the body:</span></p><pre class="verbatim"><span class="c004">for x in empty:
print 'This never happens.'
</span></pre><p><span class="c006">Although a list can contain another list, the nested
list still counts as a single element. The length of this list is
four:</span></p><p><a id="hevea_default482"></a><span class="c005">
</span><a id="hevea_default483"></a></p><pre class="verbatim"><span class="c004">['spam', 1, ['Brie', 'Roquefort', 'Pol le Veq'], [1, 2, 3]]
</span></pre><span class="c005">
</span><h2 class="section" id="sec104"><span class="c006">8.4  List operations</span></h2>
<p><span class="c005">
</span><a id="hevea_default484"></a></p><p><span class="c006">The <span class="c001">+</span> operator concatenates lists:</span></p><p><a id="hevea_default485"></a><span class="c005">
</span><a id="hevea_default486"></a></p><pre class="verbatim"><span class="c004">>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> c = a + b
>>> print c
[1, 2, 3, 4, 5, 6]
</span></pre><p><span class="c006">Similarly, the <span class="c001">*</span> operator repeats a list a given number of times:</span></p><p><a id="hevea_default487"></a><span class="c005">
</span><a id="hevea_default488"></a></p><pre class="verbatim"><span class="c004">>>> [0] * 4
[0, 0, 0, 0]
>>> [1, 2, 3] * 3
[1, 2, 3, 1, 2, 3, 1, 2, 3]
</span></pre><p><span class="c006">The first example repeats <span class="c001">[0]</span> four times. The second example
repeats the list <span class="c001">[1, 2, 3]</span> three times.</span></p><span class="c005">
</span><h2 class="section" id="sec105"><span class="c006">8.5  List slices</span></h2>
<p><a id="hevea_default489"></a><span class="c005">
</span><a id="hevea_default490"></a><span class="c005">
</span><a id="hevea_default491"></a><span class="c005">
</span><a id="hevea_default492"></a><span class="c005">
</span><a id="hevea_default493"></a></p><p><span class="c006">The slice operator also works on lists:</span></p><pre class="verbatim"><span class="c004">>>> t = ['a', 'b', 'c', 'd', 'e', 'f']
>>> t[1:3]
['b', 'c']
>>> t[:4]
['a', 'b', 'c', 'd']
>>> t[3:]
['d', 'e', 'f']
</span></pre><p><span class="c006">If you omit the first index, the slice starts at the beginning.
If you omit the second, the slice goes to the end. So if you
omit both, the slice is a copy of the whole list.</span></p><p><a id="hevea_default494"></a><span class="c005">
</span><a id="hevea_default495"></a><span class="c005">
</span><a id="hevea_default496"></a></p><pre class="verbatim"><span class="c004">>>> t[:]
['a', 'b', 'c', 'd', 'e', 'f']
</span></pre><p><span class="c006">Since lists are mutable, it is often useful to make a copy
before performing operations that fold, spindle or mutilate
lists.</span></p><p><a id="hevea_default497"></a></p><p><span class="c006">A slice operator on the left side of an assignment
can update multiple elements:</span></p><p><a id="hevea_default498"></a><span class="c005">
</span><a id="hevea_default499"></a></p><pre class="verbatim"><span class="c004">>>> t = ['a', 'b', 'c', 'd', 'e', 'f']
>>> t[1:3] = ['x', 'y']
>>> print t
['a', 'x', 'y', 'd', 'e', 'f']
</span></pre><span class="c005">
</span><h2 class="section" id="sec106"><span class="c006">8.6  List methods</span></h2>
<p><a id="hevea_default500"></a><span class="c005">
</span><a id="hevea_default501"></a></p><p><span class="c006">Python provides methods that operate on lists. For example,
<span class="c001">append</span> adds a new element to the end of a list:</span></p><p><a id="hevea_default502"></a><span class="c005">
</span><a id="hevea_default503"></a></p><pre class="verbatim"><span class="c004">>>> t = ['a', 'b', 'c']
>>> t.append('d')
>>> print t
['a', 'b', 'c', 'd']
</span></pre><p><span class="c006"><span class="c001">extend</span> takes a list as an argument and appends all of
the elements:</span></p><p><a id="hevea_default504"></a><span class="c005">
</span><a id="hevea_default505"></a></p><pre class="verbatim"><span class="c004">>>> t1 = ['a', 'b', 'c']
>>> t2 = ['d', 'e']
>>> t1.extend(t2)
>>> print t1
['a', 'b', 'c', 'd', 'e']
</span></pre><p><span class="c006">This example leaves <span class="c001">t2</span> unmodified.</span></p><p><span class="c006"><span class="c001">sort</span> arranges the elements of the list from low to high:</span></p><p><a id="hevea_default506"></a><span class="c005">
</span><a id="hevea_default507"></a></p><pre class="verbatim"><span class="c004">>>> t = ['d', 'c', 'e', 'b', 'a']
>>> t.sort()
>>> print t
['a', 'b', 'c', 'd', 'e']
</span></pre><p><span class="c006">Most list methods are void; they modify the list and return <span class="c001">None</span>.
If you accidentally write <span class="c001">t = t.sort()</span>, you will be disappointed
with the result.</span></p><p><a id="hevea_default508"></a><span class="c005">
</span><a id="hevea_default509"></a><span class="c005">
</span><a id="hevea_default510"></a><span class="c005">
</span><a id="hevea_default511"></a></p><span class="c005">
</span><h2 class="section" id="sec107"><span class="c006">8.7  Deleting elements</span></h2>
<p><a id="hevea_default512"></a><span class="c005">
</span><a id="hevea_default513"></a></p><p><span class="c006">There are several ways to delete elements from a list. If you
know the index of the element you want, you can use
<span class="c001">pop</span>:</span></p><p><a id="hevea_default514"></a><span class="c005">
</span><a id="hevea_default515"></a></p><pre class="verbatim"><span class="c004">>>> t = ['a', 'b', 'c']
>>> x = t.pop(1)
>>> print t
['a', 'c']
>>> print x
b
</span></pre><p><span class="c006"><span class="c001">pop</span> modifies the list and returns the element that was removed.
If you don’t provide an index, it deletes and returns the
last element.</span></p><p><span class="c006">If you don’t need the removed value, you can use the <span class="c001">del</span>
operator:</span></p><p><a id="hevea_default516"></a><span class="c005">
</span><a id="hevea_default517"></a></p><pre class="verbatim"><span class="c004">>>> t = ['a', 'b', 'c']
>>> del t[1]
>>> print t
['a', 'c']
</span></pre><p><span class="c006">If you know the element you want to remove (but not the index), you
can use <span class="c001">remove</span>:</span></p><p><a id="hevea_default518"></a><span class="c005">
</span><a id="hevea_default519"></a></p><pre class="verbatim"><span class="c004">>>> t = ['a', 'b', 'c']
>>> t.remove('b')
>>> print t
['a', 'c']
</span></pre><p><span class="c006">The return value from <span class="c001">remove</span> is <span class="c001">None</span>.</span></p><p><a id="hevea_default520"></a><span class="c005">
</span><a id="hevea_default521"></a></p><p><span class="c006">To remove more than one element, you can use <span class="c001">del</span> with
a slice index:</span></p><pre class="verbatim"><span class="c004">>>> t = ['a', 'b', 'c', 'd', 'e', 'f']
>>> del t[1:5]
>>> print t
['a', 'f']
</span></pre><p><span class="c006">As usual, the slice selects all the elements up to, but not
including, the second index.</span></p><span class="c005">
</span><h2 class="section" id="sec108"><span class="c006">8.8  Lists and functions</span></h2>
<p><span class="c006">There are a number of built-in functions that can be used on lists
that allow you to quickly look through a list without
writing your own loops:</span></p><pre class="verbatim"><span class="c004">>>> nums = [3, 41, 12, 9, 74, 15]
>>> print len(nums)
6
>>> print max(nums)
74
>>> print min(nums)
3
>>> print sum(nums)
154
>>> print sum(nums)/len(nums)
25
</span></pre><p><span class="c006">The <span class="c001">sum()</span> function only works when the list elements are numbers.
The other functions (<span class="c001">max()</span>, <span class="c001">len()</span>, etc.) work with lists of
strings and other types that can be comparable.</span></p><p><span class="c006">We could rewrite an earlier program that computed the average of
a list of numbers entered by the user using a list.</span></p><p><span class="c006">First, the program to compute an average without a list:</span></p><pre class="verbatim"><span class="c004">total = 0
count = 0
while ( True ) :
inp = raw_input('Enter a number: ')
if inp == 'done' : break
value = float(inp)
total = total + value
count = count + 1
average = total / count
print 'Average:', average
</span></pre><p><span class="c006">In this program, we have <span class="c001">count</span> and <span class="c001">sum</span> variables to
keep the number and running total of the user’s numbers as
we repeatedly prompt the user for a number.</span></p><p><span class="c006">We could simply remember each number as the user entered it
and use built-in functions to compute the sum and count at
the end.</span></p><pre class="verbatim"><span class="c004">numlist = list()
while ( True ) :
inp = raw_input('Enter a number: ')
if inp == 'done' : break
value = float(inp)
numlist.append(value)
average = sum(numlist) / len(numlist)
print 'Average:', average
</span></pre><p><span class="c006">We make an empty list before the loop starts, and then each time we have
a number, we append it to the list. At the end of
the program, we simply compute the sum of the numbers in the
list and divide it by the count of the numbers in the
list to come up with the average.</span></p><span class="c005">
</span><h2 class="section" id="sec109"><span class="c006">8.9  Lists and strings</span></h2>
<p><a id="hevea_default522"></a><span class="c005">
</span><a id="hevea_default523"></a><span class="c005">
</span><a id="hevea_default524"></a></p><p><span class="c006">A string is a sequence of characters and a list is a sequence
of values, but a list of characters is not the same as a
string. To convert from a string to a list of characters,
you can use <span class="c001">list</span>:</span></p><p><a id="hevea_default525"></a><span class="c005">
</span><a id="hevea_default526"></a></p><pre class="verbatim"><span class="c004">>>> s = 'spam'
>>> t = list(s)
>>> print t
['s', 'p', 'a', 'm']
</span></pre><p><span class="c006">Because <span class="c001">list</span> is the name of a built-in function, you should
avoid using it as a variable name. I also avoid <span class="c001">l</span> because
it looks too much like <span class="c001">1</span>. So that’s why I use <span class="c001">t</span>.</span></p><p><span class="c006">The <span class="c001">list</span> function breaks a string into individual letters. If
you want to break a string into words, you can use the <span class="c001">split</span>
method:</span></p><p><a id="hevea_default527"></a><span class="c005">
</span><a id="hevea_default528"></a></p><pre class="verbatim"><span class="c004">>>> s = 'pining for the fjords'
>>> t = s.split()
>>> print t
['pining', 'for', 'the', 'fjords']
>>> print t[2]
the
</span></pre><p><span class="c006">Once you have used <span class="c001">split</span> to break the string into
a list of tokens, you can use the index operator (square
bracket) to look at a particular word in the list.</span></p><p><span class="c006">You can call <span class="c001">split</span> with
an optional argument called a <span class="c009">delimiter</span> specifies which
characters to use as word boundaries.
The following example
uses a hyphen as a delimiter:</span></p><p><a id="hevea_default529"></a><span class="c005">
</span><a id="hevea_default530"></a><span class="c005">
</span><a id="hevea_default531"></a></p><pre class="verbatim"><span class="c004">>>> s = 'spam-spam-spam'
>>> delimiter = '-'
>>> s.split(delimiter)
['spam', 'spam', 'spam']
</span></pre><p><span class="c006"><span class="c001">join</span> is the inverse of <span class="c001">split</span>. It
takes a list of strings and
concatenates the elements. <span class="c001">join</span> is a string method,
so you have to invoke it on the delimiter and pass the
list as a parameter:</span></p><p><a id="hevea_default532"></a><span class="c005">
</span><a id="hevea_default533"></a><span class="c005">
</span><a id="hevea_default534"></a></p><pre class="verbatim"><span class="c004">>>> t = ['pining', 'for', 'the', 'fjords']
>>> delimiter = ' '
>>> delimiter.join(t)
'pining for the fjords'
</span></pre><p><span class="c006">In this case the delimiter is a space character, so
<span class="c001">join</span> puts a space between words. To concatenate
strings without spaces, you can use the empty string,
<code>"</code>, as a delimiter. </span></p><p><a id="hevea_default535"></a><span class="c005">
</span><a id="hevea_default536"></a></p><span class="c005">
</span><h2 class="section" id="sec110"><span class="c006">8.10  Parsing lines</span></h2>
<p><span class="c006">Usually when we are reading a file
we want to do something to the lines other than just
printing the whole line. Often we want to find the “interesting
lines” and then <span class="c009">parse</span> the line to find some interesting
<em>part</em> of the line. What if we wanted to print out the day of the
week from those lines that start with “From ”.</span></p><pre><span class="c004">
From stephen.marquard@uct.ac.za <span class="c009"> Sat</span> Jan 5 09:14:16 2008
</span></pre><p><span class="c006">The <span class="c001">split</span> method is very effective when faced with this
kind of problem.
We can write a small program that looks for lines where the
line starts with “From ” and then <span class="c001">split</span> those lines
and then print out the third word in the line:</span></p><pre class="verbatim"><span class="c004">fhand = open('mbox-short.txt')
for line in fhand:
line = line.rstrip()
if not line.startswith('From ') : continue
words = line.split()
print words[2]
</span></pre><p><span class="c006">We also use the contracted form of the <span class="c001">if</span>
statement where we put the <span class="c001">continue </span> on the
same line as the <span class="c001">if</span>. This contracted form
of the <span class="c001">if</span> functions the same as if the
<span class="c001">continue</span> were on the next line and indented.</span></p><p><span class="c006">The program produces the following output:</span></p><pre class="verbatim"><span class="c004">Sat
Fri
Fri
Fri
...
</span></pre><p><span class="c006">Later, we will learn increasingly sophisticated techniques for
picking the lines to work on and how we pull those lines apart
to find the exact bit of information we are looking for.</span></p><span class="c005">
</span><h2 class="section" id="sec111"><span class="c006">8.11  Objects and values</span></h2>
<p><a id="hevea_default537"></a><span class="c005">
</span><a id="hevea_default538"></a></p><p><span class="c006">If we execute these assignment statements:</span></p><pre class="verbatim"><span class="c004">a = 'banana'
b = 'banana'
</span></pre><p><span class="c006">We know that <span class="c001">a</span> and <span class="c001">b</span> both refer to a
string, but we don’t
know whether they refer to the <em>same</em> string.
There are two possible states:</span></p><p><a id="hevea_default539"></a></p><div class="center"><span class="c006"><img src="book012.png" /></span></div><p><span class="c006">In one case, <span class="c001">a</span> and <span class="c001">b</span> refer to two different objects that
have the same value. In the second case, they refer to the same
object.</span></p><p><a id="hevea_default540"></a><span class="c005">
</span><a id="hevea_default541"></a></p><p><span class="c006">To check whether two variables refer to the same object, you can
use the <span class="c001">is</span> operator.</span></p><pre class="verbatim"><span class="c004">>>> a = 'banana'
>>> b = 'banana'
>>> a is b
True
</span></pre><p><span class="c006">In this example, Python only created one string object,
and both <span class="c001">a</span> and <span class="c001">b</span> refer to it.</span></p><p><span class="c006">But when you create two lists, you get two objects:</span></p><pre class="verbatim"><span class="c004">>>> a = [1, 2, 3]
>>> b = [1, 2, 3]
>>> a is b
False
</span></pre><p><span class="c006">In this case we would say that the two lists are <span class="c009">equivalent</span>,
because they have the same elements, but not <span class="c009">identical</span>, because
they are not the same object. If two objects are identical, they are
also equivalent, but if they are equivalent, they are not necessarily
identical.</span></p><p><a id="hevea_default542"></a><span class="c005">
</span><a id="hevea_default543"></a></p><p><span class="c006">Until now, we have been using “object” and “value”
interchangeably, but it is more precise to say that an object has a
value. If you execute <span class="c001">a = [1,2,3]</span>, <span class="c001">a</span> refers to a list
object whose value is a particular sequence of elements. If another
list has the same elements, we would say it has the same value.</span></p><p><a id="hevea_default544"></a><span class="c005">
</span><a id="hevea_default545"></a></p><span class="c005">
</span><h2 class="section" id="sec112"><span class="c006">8.12  Aliasing</span></h2>
<p><a id="hevea_default546"></a><span class="c005">
</span><a id="hevea_default547"></a></p><p><span class="c006">If <span class="c001">a</span> refers to an object and you assign <span class="c001">b = a</span>,
then both variables refer to the same object:</span></p><pre class="verbatim"><span class="c004">>>> a = [1, 2, 3]
>>> b = a
>>> b is a
True
</span></pre><p><span class="c006">The association of a variable with an object is called a <span class="c009">reference</span>. In this example, there are two references to the same
object.</span></p><p><a id="hevea_default548"></a></p><p><span class="c006">An object with more than one reference has more
than one name, so we say that the object is <span class="c009">aliased</span>.</span></p><p><a id="hevea_default549"></a></p><p><span class="c006">If the aliased object is mutable,
changes made with one alias affect
the other:</span></p><pre class="verbatim"><span class="c004">>>> b[0] = 17
>>> print a
[17, 2, 3]
</span></pre><p><span class="c006">Although this behavior can be useful, it is error-prone. In general,
it is safer to avoid aliasing when you are working with mutable
objects.</span></p><p><a id="hevea_default550"></a></p><p><span class="c006">For immutable objects like strings, aliasing is not as much of a
problem. In this example:</span></p><pre class="verbatim"><span class="c004">a = 'banana'
b = 'banana'
</span></pre><p><span class="c006">It almost never makes a difference whether <span class="c001">a</span> and <span class="c001">b</span> refer
to the same string or not.</span></p><span class="c005">
</span><h2 class="section" id="sec113"><span class="c006">8.13  List arguments</span></h2>
<p><a id="hevea_default551"></a><span class="c005">
</span><a id="hevea_default552"></a><span class="c005">
</span><a id="hevea_default553"></a><span class="c005">
</span><a id="hevea_default554"></a><span class="c005">
</span><a id="hevea_default555"></a></p><p><span class="c006">When you pass a list to a function, the function gets a reference
to the list.
If the function modifies a list parameter, the caller sees the change.
For example, <code>delete_head</code> removes the first element from a list:</span></p><pre class="verbatim"><span class="c004">def delete_head(t):
del t[0]
</span></pre><p><span class="c006">Here’s how it is used:</span></p><pre class="verbatim"><span class="c004">>>> letters = ['a', 'b', 'c']
>>> delete_head(letters)
>>> print letters
['b', 'c']
</span></pre><p><span class="c006">The parameter <span class="c001">t</span> and the variable <span class="c001">letters</span> are
aliases for the same object. </span></p><p><span class="c006">It is important to distinguish between operations that
modify lists and operations that create new lists. For
example, the <span class="c001">append</span> method modifies a list, but the
<span class="c001">+</span> operator creates a new list:</span></p><p><a id="hevea_default556"></a><span class="c005">
</span><a id="hevea_default557"></a><span class="c005">
</span><a id="hevea_default558"></a><span class="c005">
</span><a id="hevea_default559"></a></p><pre class="verbatim"><span class="c004">>>> t1 = [1, 2]
>>> t2 = t1.append(3)
>>> print t1
[1, 2, 3]
>>> print t2
None
>>> t3 = t1 + [3]
>>> print t3
[1, 2, 3]
>>> t2 is t3
False
</span></pre><p><span class="c006">This difference is important when you write functions that
are supposed to modify lists. For example, this function
<em>does not</em> delete the head of a list:</span></p><pre class="verbatim"><span class="c004">def bad_delete_head(t):
t = t[1:] # WRONG!
</span></pre><p><span class="c006">The slice operator creates a new list and the assignment
makes <span class="c001">t</span> refer to it, but none of that has any effect
on the list that was passed as an argument.</span></p><p><a id="hevea_default560"></a><span class="c005">
</span><a id="hevea_default561"></a></p><p><span class="c006">An alternative is to write a function that creates and
returns a new list. For
example, <span class="c001">tail</span> returns all but the first
element of a list:</span></p><pre class="verbatim"><span class="c004">def tail(t):
return t[1:]
</span></pre><p><span class="c006">This function leaves the original list unmodified.
Here’s how it is used:</span></p><pre class="verbatim"><span class="c004">>>> letters = ['a', 'b', 'c']
>>> rest = tail(letters)
>>> print rest
['b', 'c']
</span></pre><div class="theorem"><span class="c006"><span class="c009">Exercise 1</span>  </span><p><span class="c006"><em>Write a function called <span class="c001">chop</span> that takes a list and modifies
it, removing the first and last elements, and returns <span class="c001">None</span>.</em></span></p><p><span class="c006"><em>Then write a function called <span class="c001">middle</span> that takes a list and
returns a new list that contains all but the first and last
elements.</em></span></p></div><span class="c005">
</span><h2 class="section" id="sec114"><span class="c006">8.14  Debugging</span></h2>
<p><span class="c005">
</span><a id="hevea_default562"></a></p><p><span class="c006">Careless use of lists (and other mutable objects)
can lead to long hours of debugging. Here are some common
pitfalls and ways to avoid them:</span></p><ol class="enumerate" type="1"><li class="li-enumerate"><span class="c006">Don’t forget that most list methods modify the argument and
return <span class="c001">None</span>. This is the opposite of the string methods,
which return a new string and leave the original alone.</span><p><span class="c006">If you are used to writing string code like this:</span></p><pre class="verbatim"><span class="c004">word = word.strip()
</span></pre><p><span class="c006">It is tempting to write list code like this:</span></p><pre class="verbatim"><span class="c004">t = t.sort() # WRONG!
</span></pre><p><a id="hevea_default563"></a><span class="c005">
</span><a id="hevea_default564"></a></p><p><span class="c006">Because <span class="c001">sort</span> returns <span class="c001">None</span>, the
next operation you perform with <span class="c001">t</span> is likely to fail.</span></p><p><span class="c006">Before using list methods and operators, you should read the
documentation carefully and then test them in interactive mode. The
methods and operators that lists share with other sequences (like
strings) are documented at
<span class="c001">docs.python.org/lib/typesseq.html</span>. The
methods and operators that only apply to mutable sequences
are documented at <span class="c001">docs.python.org/lib/typesseq-mutable.html</span>.</span></p></li><li class="li-enumerate"><span class="c006">Pick an idiom and stick with it.
</span><a id="hevea_default565"></a><p><span class="c006">Part of the problem with lists is that there are too many
ways to do things. For example, to remove an element from
a list, you can use <span class="c001">pop</span>, <span class="c001">remove</span>, <span class="c001">del</span>,
or even a slice assignment.</span></p><p><span class="c006">To add an element, you can use the <span class="c001">append</span> method or
the <span class="c001">+</span> operator. But don’t forget that these are right: </span></p><pre class="verbatim"><span class="c004">t.append(x)
t = t + [x]
</span></pre><p><span class="c006">And these are wrong:</span></p><pre class="verbatim"><span class="c004">t.append([x]) # WRONG!
t = t.append(x) # WRONG!
t + [x] # WRONG!
t = t + x # WRONG!
</span></pre><p><span class="c006">Try out each of these examples in interactive mode to make sure
you understand what they do. Notice that only the last
one causes a runtime error; the other three are legal, but they
do the wrong thing.</span></p></li><li class="li-enumerate"><span class="c006">Make copies to avoid aliasing.</span><p><a id="hevea_default566"></a><span class="c005">
</span><a id="hevea_default567"></a></p><p><span class="c006">If you want to use a method like <span class="c001">sort</span> that modifies
the argument, but you need to keep the original list as
well, you can make a copy.</span></p><pre class="verbatim"><span class="c004">orig = t[:]
t.sort()
</span></pre><p><span class="c006">In this example you could also use the built-in function <span class="c001">sorted</span>,
which returns a new, sorted list and leaves the original alone.
But in that case you should avoid using <span class="c001">sorted</span> as a variable
name!</span></p></li><li class="li-enumerate"><span class="c006">Lists, <span class="c001">split</span>, and files</span><p><span class="c006">When we read and parse files, there are many opportunities
to encounter input that can crash our program so it is a good
idea to revisit the <span class="c009">guardian</span> pattern when it comes
writing programs that read through a file
and look for a “needle in the haystack”.</span></p><p><span class="c006">Let’s revisit our program that is looking for the day of the
week on the from lines of our file:</span></p><pre><span class="c004">
From stephen.marquard@uct.ac.za <span class="c009"> Sat</span> Jan 5 09:14:16 2008
</span></pre><p><span class="c006">Since we are breaking this line into words, we could dispense
with the use of <span class="c001">startswith</span> and simply look at the
first word of the line to determine if we are interested
in the line at all. We can use <span class="c001">continue</span> to skip lines
that don’t have “From” as the first word as follows:</span></p><pre class="verbatim"><span class="c004">fhand = open('mbox-short.txt')
for line in fhand:
words = line.split()
if words[0] != 'From' : continue
print words[2]
</span></pre><p><span class="c006">This looks much simpler and we don’t even need to do the
<span class="c001">rstrip</span> to remove the newline at the end of the file.
But is it better?</span></p><pre class="verbatim"><span class="c004">python search8.py
Sat
Traceback (most recent call last):
File "search8.py", line 5, in <module>
if words[0] != 'From' : continue
IndexError: list index out of range
</span></pre><p><span class="c006">It kind of works and we see the day from the first line
(Sat) but then the program fails with a traceback error.
What went wrong? What messed-up data caused our elegant,
clever and very Pythonic program to fail?</span></p><p><span class="c006">You could stare at it for a long time and puzzle through
it or ask someone for help, but the quicker and smarter
approach is to add a <span class="c001">print</span> statement. The best place
to add the print statement is right before the line where
the program failed and print out the data that seems to be causing
the failure.</span></p><p><span class="c006">Now this approach may generate a lot of lines of output but at
least you will immediately have some clue as to the
problem at hand. So we add a print of the variable
<span class="c001">words</span> right before line five. We even
add a prefix “Debug:” to the line so we can keep
our regular output separate from our debug output.</span></p><pre class="verbatim"><span class="c004">for line in fhand:
words = line.split()
print 'Debug:', words
if words[0] != 'From' : continue
print words[2]
</span></pre><p><span class="c006">When we run the program, a lot of output scrolls off the screen
but at the end, we see our debug output and the traceback so
we know what happened just before the traceback.</span></p><pre class="verbatim"><span class="c004">Debug: ['X-DSPAM-Confidence:', '0.8475']
Debug: ['X-DSPAM-Probability:', '0.0000']
Debug: []
Traceback (most recent call last):
File "search9.py", line 6, in <module>
if words[0] != 'From' : continue
IndexError: list index out of range
</span></pre><p><span class="c006">Each debug line is printing the list of words which we get
when we <span class="c001">split</span> the line into words. When the program fails
the list of words is empty <code>[]</code>. If we open the file in a text editor
and look at the file, at that point it looks as follows:</span></p><pre class="verbatim"><span class="c004">X-DSPAM-Result: Innocent
X-DSPAM-Processed: Sat Jan 5 09:14:16 2008
X-DSPAM-Confidence: 0.8475
X-DSPAM-Probability: 0.0000
Details: http://source.sakaiproject.org/viewsvn/?view=rev&rev=39772
</span></pre><p><span class="c006">The error occurs when our program encounters a blank line! Of course there
are “zero words” on a blank line. Why didn’t we think of that
when we were writing the code. When the code looks for the first
word (<code>word[0]</code>) to check to see if it matches “From”,
we get an “index out of range” error.</span></p><p><span class="c006">This of course is the perfect place to add some <span class="c009">guardian</span> code
to avoid checking the first word if the first word is not there.
There are many ways to protect this code, we will choose to
check the number of words we have before we look at the first word:</span></p><pre class="verbatim"><span class="c004">fhand = open('mbox-short.txt')
count = 0
for line in fhand:
words = line.split()
# print 'Debug:', words
if len(words) == 0 : continue
if words[0] != 'From' : continue
print words[2]
</span></pre><p><span class="c006">First we commented out the debug print statement instead of removing it
in case our modification fails and we need to debug again. Then we added
a guardian statement that checks to see if we have zero words, and if so,
we use <span class="c001">continue</span> to skip to the next line in the file.</span></p><p><span class="c006">We can think of the two <span class="c001">continue</span> statements as helping us refine
the set of lines which are “interesting” to us and which we want
to process some more. A line which has no words is “uninteresting” to
us so we skip to the next line. A line which does not have “From”
as its first word is uninteresting to us so we skip it.</span></p><p><span class="c006">The program as modified runs successfully so perhaps it is correct. Our
guardian statement does make sure that the <span class="c001">words[0]</span> will never fail,
but perhaps it is not enough. When we are programming, we must always be
thinking, “What might go wrong?”.</span></p><div class="theorem"><span class="c006"><span class="c009">Exercise 2</span>  <em>
Figure out which line of the above program is still not properly guarded.
See if you can construct a text file which causes the program to fail
and then modify the program so that the line is properly guarded and
test it to make sure it handles your new text file.
</em></span></div><div class="theorem"><span class="c006"><span class="c009">Exercise 3</span>  <em>
Rewrite the guardian code in the above example without two
<span class="c001">if</span> statements. Instead use a compound logical expression using the
<span class="c001">and</span> logical operator with a single <span class="c001">if</span> statement.
</em></span></div></li></ol><span class="c005">
</span><h2 class="section" id="sec115"><span class="c006">8.15  Glossary</span></h2>
<dl class="description"><dt class="dt-description"><span class="c010">aliasing:</span></dt><dd class="dd-description"><span class="c006"> A circumstance where two or more variables refer to the same
object.
</span><a id="hevea_default568"></a></dd><dt class="dt-description"><span class="c010">delimiter:</span></dt><dd class="dd-description"><span class="c006"> A character or string used to indicate where a
string should be split.
</span><a id="hevea_default569"></a></dd><dt class="dt-description"><span class="c010">element:</span></dt><dd class="dd-description"><span class="c006"> One of the values in a list (or other sequence),
also called items.
</span><a id="hevea_default570"></a></dd><dt class="dt-description"><span class="c010">equivalent:</span></dt><dd class="dd-description"><span class="c006"> Having the same value.
</span><a id="hevea_default571"></a></dd><dt class="dt-description"><span class="c010">index:</span></dt><dd class="dd-description"><span class="c006"> An integer value that indicates an element in a list.
</span><a id="hevea_default572"></a></dd><dt class="dt-description"><span class="c010">identical:</span></dt><dd class="dd-description"><span class="c006"> Being the same object (which implies equivalence).
</span><a id="hevea_default573"></a></dd><dt class="dt-description"><span class="c010">list:</span></dt><dd class="dd-description"><span class="c006"> A sequence of values.
</span><a id="hevea_default574"></a></dd><dt class="dt-description"><span class="c010">list traversal:</span></dt><dd class="dd-description"><span class="c006"> The sequential accessing of each element in a list.
</span><a id="hevea_default575"></a></dd><dt class="dt-description"><span class="c010">nested list:</span></dt><dd class="dd-description"><span class="c006"> A list that is an element of another list.
</span><a id="hevea_default576"></a></dd><dt class="dt-description"><span class="c010">object:</span></dt><dd class="dd-description"><span class="c006"> Something a variable can refer to. An object
has a type and a value.
</span><a id="hevea_default577"></a></dd><dt class="dt-description"><span class="c010">reference:</span></dt><dd class="dd-description"><span class="c006"> The association between a variable and its value.
</span><a id="hevea_default578"></a></dd></dl><span class="c005">
</span><h2 class="section" id="sec116"><span class="c006">8.16  Exercises</span></h2>
<div class="theorem"><span class="c006"><span class="c009">Exercise 4</span>  <em>
Download a copy of the file from
<span class="c001">www.py4inf.com/code/romeo.txt</span></em>
</span><a id="hevea_default579"></a><p><span class="c006"><em>Write a program to open the file <span class="c001">romeo.txt</span> and read it
line by line. For each line, split the line into a list of
words using the <span class="c001">split</span> function.</em></span></p><p><span class="c006"><em>For each word, check to see if the word is already in a list.
If the word is not in the list, add it to the list. </em></span></p><p><span class="c006"><em>When the program completes, sort and print the resulting words
in alphabetical order.</em></span></p><pre class="verbatim"><span class="c006"><em>Enter file: romeo.txt
['Arise', 'But', 'It', 'Juliet', 'Who', 'already',
'and', 'breaks', 'east', 'envious', 'fair', 'grief',
'is', 'kill', 'light', 'moon', 'pale', 'sick', 'soft',
'sun', 'the', 'through', 'what', 'window',
'with', 'yonder']
</em></span></pre></div><div class="theorem"><span class="c006"><span class="c009">Exercise 5</span>  <em>
Write a program to read through the mail box data and when you find
line that starts with “From”, you will split the line into
words using the <span class="c001">split</span> function. We are interested in
who sent the message which is the second word on the From line.</em></span><p><span class="c002"><em>From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008 </em></span></p><p><span class="c006"><em>You will parse the From line and print out the second word for
each From line and then you will also count the number of
From (not From:) lines and print out a count at the end.</em></span></p><p><span class="c006"><em>This is a good sample output with a few lines removed:</em></span></p><pre class="verbatim"><span class="c004"><em>python fromcount.py
Enter a file name: mbox-short.txt
stephen.marquard@uct.ac.za
louis@media.berkeley.edu
zqian@umich.edu
[...some output removed...]
ray@media.berkeley.edu
cwen@iupui.edu
cwen@iupui.edu
cwen@iupui.edu
There were 27 lines in the file with From as the first word
</em></span></pre></div><div class="theorem"><span class="c006"><span class="c009">Exercise 6</span>  <em>
Rewrite the program that prompts the user for a list of
numbers and prints out the maximum and minimum of the
numbers at the end when the user enters “done”. Write
the program to store the numbers the user enters in a list
and use the <span class="c001">max()</span> and <span class="c001">min()</span> functions to
compute the maximum and minimum numbers after the
loop completes.</em></span><pre class="verbatim"><span class="c004"><em>Enter a number: 6
Enter a number: 2
Enter a number: 9
Enter a number: 3
Enter a number: 5
Enter a number: done
Maximum: 9.0
Minimum: 2.0
</em></span></pre></div><span class="c005">
</span><hr />
<a href="book008.html"><img src="previous_motif.gif" alt="Previous" /></a>
<a href="index.html"><img src="contents_motif.gif" alt="Up" /></a>
<a href="book010.html"><img src="next_motif.gif" alt="Next" /></a>
</body>
</html>