-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path08-lists.tex
More file actions
1417 lines (1148 loc) · 34.3 KB
/
08-lists.tex
File metadata and controls
1417 lines (1148 loc) · 34.3 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
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
% LaTeX source for ``Python for Informatics: Exploring Information''
% Copyright (c) 2010- Charles R. Severance, All Rights Reserved
\chapter{Lists}
\index{list}
\index{type!list}
\section{A list is a sequence}
Like a string, a {\bf list} 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 {\bf elements} or sometimes {\bf items}.
\index{element}
\index{sequence}
\index{item}
There are several ways to create a new list; the simplest is to
enclose the elements in square brackets (\verb"[" and \verb"]"):
\beforeverb
\begin{verbatim}
[10, 20, 30, 40]
['crunchy frog', 'ram bladder', 'lark vomit']
\end{verbatim}
\afterverb
%
The first example is a list of four integers. The second is a list of
three strings. We can depict these as:
\beforefig
\centerline{\includegraphics[height=.5 in]{figs2/list-unnamed-numbers.eps}}
\afterfig
\beforefig
\centerline{\includegraphics[height=.5 in]{figs2/list-unnamed-strings.eps}}
\afterfig
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:
\beforeverb
\begin{verbatim}
['spam', 2.0, 5, [10, 20]]
\end{verbatim}
\afterverb
%
A list within another list is {\bf nested}.
\index{nested list}
\index{list!nested}
A list that contains no elements is
called an empty list; you can create one with empty
brackets, \verb"[]".
\index{empty list}
\index{list!empty}
As you might expect, you can assign list values to variables:
\beforeverb
\begin{verbatim}
>>> cheeses = ['Cheddar', 'Edam', 'Gouda']
>>> numbers = [17, 123]
>>> empty = []
>>> print(cheeses, numbers, empty)
['Cheddar', 'Edam', 'Gouda'] [17, 123] []
\end{verbatim}
\afterverb
%
\index{assignment}
\beforefig
{\includegraphics[height=.7 in\hspace{.5 in}]{figs2/list-cheeses.eps}}
\afterfig
\beforefig
{\includegraphics[height=.7 in\hspace{.5 in}]{figs2/list-numbers.eps}}
\afterfig
\beforefig
{\includegraphics[height=.7 in\hspace{.5 in}]{figs2/list-empty.eps}}
\afterfig
\section{Lists are mutable}
\index{list!element}
\index{access}
\index{index}
\index{bracket operator}
\index{operator!bracket}
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:
\beforeverb
\begin{verbatim}
>>> print(cheeses[0])
Cheddar
\end{verbatim}
\afterverb
%
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.
\index{mutability}
\beforeverb
\begin{verbatim}
>>> numbers = [17, 123]
>>> numbers[1] = 5
>>> print(numbers)
[17, 5]
\end{verbatim}
\afterverb
%
The one-eth element of {\tt numbers}, which
used to be 123, is now 5.
\index{index!starting at zero}
\index{zero, index starting at}
You can think of a list as a relationship between indices and
elements. This relationship is called a {\bf mapping}; each index
``maps to'' one of the elements.
\index{item assignment}
\index{assignment!item}
List indices work the same way as string indices:
\begin{itemize}
\item Any integer expression can be used as an index.
\item If you try to read or write an element that does not exist, you
get an {\tt IndexError}.
\index{exception!IndexError}
\index{IndexError}
\item If an index has a negative value, it counts backward from the
end of the list.
\end{itemize}
\index{list!index}
\beforeverb
\begin{verbatim}
>>> cheeses = ['Cheddar', 'Edam', 'Gouda']
>>> print(cheeses[2])
Gouda
>>> print(cheeses[-1])
Gouda
>>> print(cheeses[0])
Cheddar
>>> print(cheeses[-3])
Cheddar
\end{verbatim}
\afterverb
%
\beforefig
\centerline{\includegraphics[height=.7 in]{figs2/list-cheeses-negindices.eps}}
\afterfig
\index{list!membership}
\index{membership!list}
\index{in operator}
\index{operator!in}
The {\tt in} operator also works on lists.
\beforeverb
\begin{verbatim}
>>> cheeses = ['Cheddar', 'Edam', 'Gouda']
>>> 'Edam' in cheeses
True
>>> 'Brie' in cheeses
False
\end{verbatim}
\afterverb
\section{Traversing a list}
\index{list!traversal}
\index{traversal!list}
\index{for loop}
\index{loop!for}
\index{statement!for}
The most common way to traverse the elements of a list is
with a {\tt for} loop. The syntax is the same as for strings:
\beforeverb
\begin{verbatim}
for cheese in cheeses:
print(cheese)
\end{verbatim}
\afterverb
%
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 {\tt range} and {\tt len}:
\index{looping!with indices}
\index{index!looping with}
\index{function!len}
\index{len function}
\index{function!range}
\index{range function}
\beforeverb
\begin{verbatim}
for i in range(len(numbers)):
numbers[i] = numbers[i] * 2
\end{verbatim}
\afterverb
%
This loop traverses the list and updates each element. {\tt len}
returns the number of elements in the list. {\tt range} returns
a list of indices from 0 to $n-1$, where $n$ is the length of
the list. Each time through the loop, {\tt i} gets the index
of the next element. The assignment statement in the body uses
{\tt i} to read the old value of the element and to assign the
new value.
\index{item update}
\index{update!item}
A {\tt for} loop over an empty list never executes the body:
\beforeverb
\begin{verbatim}
for x in empty:
print('This never happens.')
\end{verbatim}
\afterverb
%
Although a list can contain another list, the nested
list still counts as a single element. The length of this list is
four:
\index{nested list}
\index{list!nested}
\beforeverb
\begin{verbatim}
['spam', 1, ['Brie', 'Roquefort', 'Pol le Veq'], [1, 2, 3]]
\end{verbatim}
\afterverb
\beforefig
\centerline{\includegraphics[height=.8 in]{figs2/list-2dimensional.eps}}
\afterfig
You may get the length of a nested list by using the \texttt{len()} function with the element containing the nested list You may use additional square brackets to access specific elements of a nested list.
\beforeverb
\begin{verbatim}
>>> nested = ['spam', 1, ['Brie', 'Roquefort', 'Pol le Veq'], [1, 2, 3]]
>>> print(len(nested))
4
>>> print(nested[0])
spam
>>> print(nested[2])
['Brie', 'Roquefort', 'Pol le Veq']
>>> print(len(nested[2]))
3
>>> print(nested[2][1])
Roquefort
\end{verbatim}
\afterverb
\section{List operations}
\index{list!operation}
The {\tt +} operator concatenates lists:
\index{concatenation!list}
\index{list!concatenation}
\beforeverb
\begin{verbatim}
>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> c = a + b
>>> print(c)
[1, 2, 3, 4, 5, 6]
\end{verbatim}
\afterverb
%
Similarly, the {\tt *} operator repeats a list a given number of times:
\index{repetition!list}
\index{list!repetition}
\beforeverb
\begin{verbatim}
>>> [0] * 4
[0, 0, 0, 0]
>>> [1, 2, 3] * 3
[1, 2, 3, 1, 2, 3, 1, 2, 3]
\end{verbatim}
\afterverb
%
The first example repeats {\tt [0]} four times. The second example
repeats the list {\tt [1, 2, 3]} three times.
\section{List slices}
\index{slice operator}
\index{operator!slice}
\index{index!slice}
\index{list!slice}
\index{slice!list}
The slice operator also works on lists:
\beforeverb
\begin{verbatim}
>>> t = ['a', 'b', 'c', 'd', 'e', 'f']
>>> t[1:3]
['b', 'c']
>>> t[:4]
['a', 'b', 'c', 'd']
>>> t[3:]
['d', 'e', 'f']
\end{verbatim}
\afterverb
%
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.
\index{list!copy}
\index{slice!copy}
\index{copy!slice}
\beforeverb
\begin{verbatim}
>>> t[:]
['a', 'b', 'c', 'd', 'e', 'f']
\end{verbatim}
\afterverb
%
Since lists are mutable, it is often useful to make a copy
before performing operations that fold, spindle, or mutilate
lists.
\index{mutability}
A slice operator on the left side of an assignment
can update multiple elements:
\index{slice!update}
\index{update!slice}
\beforeverb
\begin{verbatim}
>>> t = ['a', 'b', 'c', 'd', 'e', 'f']
>>> t[1:3] = ['x', 'y']
>>> print(t)
['a', 'x', 'y', 'd', 'e', 'f']
\end{verbatim}
\afterverb
%
\section{List methods}
\index{list!method}
\index{method, list}
Python provides methods that operate on lists. For example,
{\tt append} adds a new element to the end of a list:
\index{append method}
\index{method!append}
\beforeverb
\begin{verbatim}
>>> t = ['a', 'b', 'c']
>>> t.append('d')
>>> print(t)
['a', 'b', 'c', 'd']
\end{verbatim}
\afterverb
%
{\tt extend} takes a list as an argument and appends all of
the elements:
\index{extend method}
\index{method!extend}
\beforeverb
\begin{verbatim}
>>> t1 = ['a', 'b', 'c']
>>> t2 = ['d', 'e']
>>> t1.extend(t2)
>>> print(t1)
['a', 'b', 'c', 'd', 'e']
\end{verbatim}
\afterverb
%
This example leaves {\tt t2} unmodified.
{\tt sort} arranges the elements of the list from low to high:
\index{sort method}
\index{method!sort}
\beforeverb
\begin{verbatim}
>>> t = ['d', 'c', 'e', 'b', 'a']
>>> t.sort()
>>> print(t)
['a', 'b', 'c', 'd', 'e']
\end{verbatim}
\afterverb
%
Most list methods are void; they modify the list and return {\tt None}.
If you accidentally write {\tt t = t.sort()}, you will be disappointed
with the result.
\index{void method}
\index{method!void}
\index{None special value}
\index{special value!None}
\section{Deleting elements}
\index{element deletion}
\index{deletion, element of list}
There are several ways to delete elements from a list. If you
know the index of the element you want, you can use
{\tt pop}:
\index{pop method}
\index{method!pop}
\beforeverb
\begin{verbatim}
>>> t = ['a', 'b', 'c']
>>> x = t.pop(1)
>>> print(t)
['a', 'c']
>>> print(x)
b
\end{verbatim}
\afterverb
%
{\tt pop} modifies the list and returns the element that was removed.
If you don't provide an index, it deletes and returns the
last element.
If you don't need the removed value, you can use the {\tt del}
operator:
\index{del operator}
\index{operator!del}
\beforeverb
\begin{verbatim}
>>> t = ['a', 'b', 'c']
>>> del t[1]
>>> print(t)
['a', 'c']
\end{verbatim}
\afterverb
%
If you know the element you want to remove (but not the index), you
can use {\tt remove}:
\index{remove method}
\index{method!remove}
\beforeverb
\begin{verbatim}
>>> t = ['a', 'b', 'c']
>>> t.remove('b')
>>> print(t)
['a', 'c']
\end{verbatim}
\afterverb
%
The return value from {\tt remove} is {\tt None}.
\index{None special value}
\index{special value!None}
To remove more than one element, you can use {\tt del} with
a slice index:
\beforeverb
\begin{verbatim}
>>> t = ['a', 'b', 'c', 'd', 'e', 'f']
>>> del t[1:5]
>>> print(t)
['a', 'f']
\end{verbatim}
\afterverb
%
As usual, the slice selects all the elements up to, \textbf{but not
including}, the second index.
\section{Lists and functions}
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:
\beforeverb
\begin{verbatim}
>>> 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.666666666666668
\end{verbatim}
\afterverb
%
The {\tt sum()} function only works when the list elements are numbers.
The other functions ({\tt max()}, {\tt len()}, etc.) work with lists of
strings and other types that can be comparable.
We could rewrite an earlier program that computed the average of
a list of numbers entered by the user using a list.
First, the program to compute an average without a list:
\beforeverb
\begin{verbatim}
total = 0
count = 0
while ( True ) :
inp = input('Enter a number: ')
if inp == 'done' : break
value = float(inp)
total = total + value
count = count + 1
average = total / count
print('Average:', average)
\end{verbatim}
\afterverb
%
In this program, we have {\tt count} and {\tt total} variables to
keep the number and running total of the user's numbers as
we repeatedly prompt the user for a number.
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.
\beforeverb
\begin{verbatim}
numlist = list()
while ( True ) :
inp = input('Enter a number: ')
if inp == 'done' : break
value = float(inp)
numlist.append(value)
average = sum(numlist) / len(numlist)
print('Average:', average)
\end{verbatim}
\afterverb
%
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.
\section{Lists and strings}
\index{list}
\index{string}
\index{sequence}
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 {\tt list}:
\index{list!function}
\index{function!list}
\beforeverb
\begin{verbatim}
>>> s = 'spam'
>>> t = list(s)
>>> print(t)
['s', 'p', 'a', 'm']
\end{verbatim}
\afterverb
%
Because {\tt list} is the name of a built-in function, you should
avoid using it as a variable name. I also avoid the letter {\tt l} because
it looks too much like the number {\tt 1}. So that's why I use {\tt t}.
The {\tt list} function breaks a string into individual letters. If
you want to break a string into words, you can use the {\tt split}
method:
\index{split method}
\index{method!split}
\beforeverb
\begin{verbatim}
>>> s = 'pining for the fjords'
>>> t = s.split()
>>> print(t)
['pining', 'for', 'the', 'fjords']
>>> print(t[2])
the
\end{verbatim}
\afterverb
%
Once you have used {\tt split} to break the string into
a list of words, you can use the index operator (square
bracket) to look at a particular word in the list.
You can call {\tt split} with
an optional argument called a {\bf delimiter} that
specifies which characters to use as word boundaries.
The following example uses a hyphen as a delimiter:
\index{optional argument}
\index{argument!optional}
\index{delimiter}
\beforeverb
\begin{verbatim}
>>> s = 'spam-spam-spam'
>>> delimiter = '-'
>>> s.split(delimiter)
['spam', 'spam', 'spam']
\end{verbatim}
\afterverb
%
{\tt join} is the inverse of {\tt split}. It
takes a list of strings and
concatenates the elements. \textbf{Note that {\tt join} is a string method},
so you have to invoke it on the delimiter and pass the
list as a parameter:
\index{join method}
\index{method!join}
\index{concatenation}
\beforeverb
\begin{verbatim}
>>> t = ['pining', 'for', 'the', 'fjords']
>>> delimiter = ' '
>>> delimiter.join(t)
'pining for the fjords'
\end{verbatim}
\afterverb
%
In this case the delimiter is a space character, so
{\tt join} puts a space between words. To concatenate
strings without spaces, you can use the empty string,
\verb"''", as a delimiter.
\index{empty string}
\index{string!empty}
\section{Parsing lines}
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 {\bf parse} the line to find some interesting
\emph{part} of the line. What if we wanted to print out the day of the
week from those lines that start with ``From ''?
\beforeverb
\begin{alltt}
From stephen.marquard@uct.ac.za {\bf Sat} Jan 5 09:14:16 2008
\end{alltt}
\afterverb
The {\tt split} method is very effective when faced with this
kind of problem.
We can write a small program that looks for lines starting with ``From '', using {\tt startswith}), next we can {\tt split} those lines,
and finally print out the third word in the line.
Here are a few lines from the mbox-short.txt\footnote{You may download the \texttt{mbox-short.txt} \url{https://www.monead.com/introcompsci/mbox-short.txt}, which should be stored in the same folder that you are in when you start Python.} file that the program uses:
\beforeverb
\begin{verbatim}
From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008
Return-Path: <postmaster@collab.sakaiproject.org>
From louis@media.berkeley.edu Fri Jan 4 18:10:48 2008
Return-Path: <postmaster@collab.sakaiproject.org>
From zqian@umich.edu Fri Jan 4 16:10:39 2008
Return-Path: <postmaster@collab.sakaiproject.org>
From rjlowe@iupui.edu Fri Jan 4 15:46:24 2008
Return-Path: <postmaster@collab.sakaiproject.org>
\end{verbatim}
\afterverb
Here is the program that uses {\tt startswith} and {\tt split} as described above:
\beforeverb
\begin{verbatim}
fhand = open('mbox-short.txt')
for line in fhand:
line = line.rstrip()
if not line.startswith('From '): continue
words = line.split()
print(words[2])
\end{verbatim}
\afterverb
%
Here we also use the contracted form of the {\tt if}
statement where we put the {\tt continue } on the
same line as the {\tt if}. This contracted form
of the {\tt if} functions the same as if the
{\tt continue} were on the next line and indented.
The program produces output that starts like this:
\beforeverb
\begin{verbatim}
Sat
Fri
Fri
Fri
...
\end{verbatim}
\afterverb
%
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.
\section{Objects and values}
\index{object}
\index{value}
If we execute these assignment statements:
\beforeverb
\begin{verbatim}
a = 'banana'
b = 'banana'
\end{verbatim}
\afterverb
%
we know that {\tt a} and {\tt b} both refer to a
string, but we don't know whether they refer to the
\emph{same} string. There are two possible states:
\index{aliasing}
\beforefig
\centerline{\includegraphics{figs2/list1.eps}}
\afterfig
In one case, {\tt a} and {\tt b} refer to two different objects that
have the same value. In the second case, they refer to the same
object.
\index{is operator}
\index{operator!is}
To check whether two variables refer to the same object, you can
use the {\tt is} operator.
\beforeverb
\begin{verbatim}
>>> a = 'banana'
>>> b = 'banana'
>>> a is b
True
\end{verbatim}
\afterverb
%
In this example, Python only created one string object,
and both {\tt a} and {\tt b} refer to it.
But when you create two lists, you get two objects:
\beforeverb
\begin{verbatim}
>>> a = [1, 2, 3]
>>> b = [1, 2, 3]
>>> a is b
False
\end{verbatim}
\afterverb
%
In this case we would say that the two lists are {\bf equivalent},
because they have the same elements, but not {\bf identical}, 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.
\index{equivalence}
\index{identity}
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 {\tt a = [1,2,3]}, {\tt a} 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.
\index{object}
\index{value}
\section{Aliasing}
\index{aliasing}
\index{reference!aliasing}
If {\tt a} refers to an object and you assign {\tt b = a},
then both variables refer to the same object:
\beforeverb
\begin{verbatim}
>>> a = [1, 2, 3]
>>> b = a
>>> b is a
True
\end{verbatim}
\afterverb
%
The association of a variable with an object is called a {\bf
reference}. In this example, there are two references to the same
object.
\index{reference}
An object with more than one reference has more
than one name, so we say that the object is {\bf aliased}.
\index{mutability}
If the aliased object is mutable,
changes made with one alias affect
the other:
\beforeverb
\begin{verbatim}
>>> b[0] = 17
>>> print(a)
[17, 2, 3]
\end{verbatim}
\afterverb
%
Although this behavior can be useful, it is error-prone. In general,
\textbf{it is safer to avoid aliasing when you are working with mutable
objects}.
\index{immutability}
For immutable objects like strings, aliasing is not as much of a
problem. In this example:
\beforeverb
\begin{verbatim}
a = 'banana'
b = 'banana'
\end{verbatim}
\afterverb
%
it almost never makes a difference whether {\tt a} and {\tt b} refer
to the same string or not.
\section{List arguments}
\index{list!as argument}
\index{argument}
\index{argument!list}
\index{reference}
\index{parameter}
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, \verb"delete_head" removes the first element from a list:
\beforeverb
\begin{verbatim}
def delete_head(t):
del t[0]
\end{verbatim}
\afterverb
%
Here's how it is used:
\beforeverb
\begin{verbatim}
>>> letters = ['a', 'b', 'c']
>>> delete_head(letters)
>>> print(letters)
['b', 'c']
\end{verbatim}
\afterverb
%
The parameter {\tt t} and the variable {\tt letters} are
aliases for the same object.
It is important to distinguish between operations that
modify lists and operations that create new lists. For
example, the {\tt append} method modifies a list, but the
{\tt +} operator creates a new list:
\index{append method}
\index{method!append}
\index{list!concatenation}
\index{concatenation!list}
% corrected the second part of this example to continue using t1 as
% it is modified in the first part of the example.
\beforeverb
\begin{verbatim}
>>> t1 = [1, 2]
>>> t2 = t1.append(3)
>>> print(t1)
[1, 2, 3]
>>> print(t2)
None
>>> t3 = t1 + [4]
>>> print(t3)
[1, 2, 3, 4]
>>> t1 is t3
False
\end{verbatim}
\afterverb
This difference is important when you write functions that
are supposed to modify lists. For example, this function
\emph{does not} delete the head of a list:
\beforeverb
\begin{verbatim}
def bad_delete_head(t):
t = t[1:] # WRONG!
\end{verbatim}
\afterverb
\textbf{The slice operator creates a new list} and the assignment
makes {\tt t} refer to it, but none of that has any effect
on the list that was passed as an argument.
\index{slice operator}
\index{operator!slice}
An alternative is to write a function that creates and
returns a new list. For
example, {\tt tail} returns all but the first
element of a list:
\beforeverb
\begin{verbatim}
def tail(t):
return t[1:]
\end{verbatim}
\afterverb
%
This function leaves the original list unmodified.
Here's how it is used:
\beforeverb
\begin{verbatim}
>>> letters = ['a', 'b', 'c']
>>> rest = tail(letters)