-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathliststuples.html
More file actions
executable file
·2736 lines (2187 loc) · 108 KB
/
liststuples.html
File metadata and controls
executable file
·2736 lines (2187 loc) · 108 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
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>8. Lists and Tuples — How to Think Like a Computer Scientist: Learning with Python 3 (AoPS Edition)</title>
<link rel="stylesheet" href="_static/style.css" type="text/css" />
<link rel="stylesheet" href="_static/pygments.css" type="text/css" />
<link rel="stylesheet" href="_static/codemirrorEdited.css" type="text/css" />
<script type="text/javascript">
var DOCUMENTATION_OPTIONS = {
URL_ROOT: './',
VERSION: '1.0',
COLLAPSE_INDEX: false,
FILE_SUFFIX: '.html',
HAS_SOURCE: true
};
</script>
<script type="text/javascript" src="_static/jquery.js"></script>
<script type="text/javascript" src="_static/underscore.js"></script>
<script type="text/javascript" src="_static/doctools.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script type="text/javascript" src="_static/pywindowCodemirrorC.js"></script>
<script type="text/javascript" src="_static/skulpt.min.js"></script>
<script type="text/javascript" src="_static/skulpt-stdlib.js"></script>
<script type="text/javascript" src="_static/aopsmods.js"></script>
<link rel="copyright" title="Copyright" href="copyright.html" />
<link rel="top" title="How to Think Like a Computer Scientist: Learning with Python 3 (AoPS Edition)" href="index.html" />
<link rel="next" title="9. Files" href="files.html" />
<link rel="prev" title="7. Strings" href="strings.html" />
</head>
<body>
<div class="related">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="genindex.html" title="General Index"
accesskey="I">index</a></li>
<li class="right" >
<a href="files.html" title="9. Files"
accesskey="N">next</a> |</li>
<li class="right" >
<a href="strings.html" title="7. Strings"
accesskey="P">previous</a> |</li>
<li><a href="index.html">How to Think Like a Computer Scientist: Learning with Python 3 (AoPS Edition)</a> »</li>
</ul>
</div>
<div class="document">
<div class="documentwrapper">
<div class="body">
<div class="section" id="lists-and-tuples">
<span id="index-0"></span><h1>8. Lists and Tuples<a class="headerlink" href="#lists-and-tuples" title="Permalink to this headline">¶</a></h1>
<p>A <strong>list</strong> or a <strong>tuple</strong> is an ordered collection of values. The values that make up a list or tuple
are called its <strong>elements</strong>, or its <strong>items</strong>.
We will use the term <cite>element</cite> or <cite>item</cite> to mean the same thing. Lists and tuples are
similar to strings, which are ordered collections of characters, except that the
elements of a list can be of any type. Lists, tuples, and strings — and other collections
that maintain the order of their items — are called <strong>sequences</strong>.</p>
<p>We’ve already seen lists in previous chapters, so we’ll start by looking at tuples.</p>
<div class="section" id="tuples-are-used-for-grouping-data">
<h2>8.1. Tuples are used for grouping data<a class="headerlink" href="#tuples-are-used-for-grouping-data" title="Permalink to this headline">¶</a></h2>
<p>We can group together pairs of values by
surrounding with parentheses. For example:</p>
<div id="tuplefirstexample" class="pywindow" >
<div id="tuplefirstexample_code_div" style="display: block">
<textarea rows="1" id="tuplefirstexample_code" class="active_code" prefixcode="undefined">
year_born = ("Isaac Newton", 1642)</textarea>
</div>
<script type="text/javascript">
pythonTool.lineNumberFlags['tuplefirstexample_code'] = false;
pythonTool.readOnlyFlags['tuplefirstexample_code'] = true;
</script>
<div id='tuplefirstexample_error'></div>
<pre id="tuplefirstexample_suffix" style="display:none">
</pre>
</div>
<p>This is an example of a <strong>data structure</strong> — a mechanism for grouping and
organizing data to make it easier to use.</p>
<p>The pair is an example of a <strong>tuple</strong>. Generalizing this, a tuple can
be used to group any number of items into a single compound value.
Syntactically, a tuple is a comma-separated sequence of values.
Although it is not necessary, it is conventional to enclose tuples in parentheses:</p>
<div id="tuplesecondexample" class="pywindow" >
<div id="tuplesecondexample_code_div" style="display: block">
<textarea rows="1" id="tuplesecondexample_code" class="active_code" prefixcode="undefined">
julia = ("Julia", "Roberts", 1967, "Duplicity", 2009, "Actress", "Atlanta, Georgia")</textarea>
</div>
<script type="text/javascript">
pythonTool.lineNumberFlags['tuplesecondexample_code'] = false;
pythonTool.readOnlyFlags['tuplesecondexample_code'] = true;
</script>
<div id='tuplesecondexample_error'></div>
<pre id="tuplesecondexample_suffix" style="display:none">
</pre>
</div>
<p>Tuples are useful for representing what other languages often call <em>records</em> —
some related information that belongs together, like your student record. There is
no description of what each of these fields means, but we can guess. A tuple
lets us “chunk” together related information and use it as a single thing.</p>
<p>Tuples support the same sequence operations as strings. The index operator
selects an element from a tuple.</p>
<div id="tuplesaccessexample" class="pywindow" >
<div id="tuplesaccessexample_code_div" style="display: block">
<textarea rows="2" id="tuplesaccessexample_code" class="active_code" prefixcode="undefined">
julia = ("Julia", "Roberts", 1967, "Duplicity", 2009, "Actress", "Atlanta, Georgia")
print(julia[2])</textarea>
</div>
<script type="text/javascript">
pythonTool.lineNumberFlags['tuplesaccessexample_code'] = true;
pythonTool.readOnlyFlags['tuplesaccessexample_code'] = false;
</script>
<div>
<button style="float:left" type='button' class='btn btn-run' id="tuplesaccessexample_runb">Run</button>
<button style="float:left; margin-left:150px;" type='button' class='btn' id="tuplesaccessexample_popb">Pop Out</button>
<button style="float:right" type="button" class='btn btn-reset' id="tuplesaccessexample_resetb">Reset</button>
<div style='clear:both'></div>
</div>
<div id='tuplesaccessexample_error'></div>
<div style="text-align: center">
<canvas id="tuplesaccessexample_canvas" class="ac-canvas" height="400" width="400" style="border-style: solid; display: none; text-align: center"></canvas>
</div>
<pre id="tuplesaccessexample_suffix" style="display:none">
</pre>
<pre id="tuplesaccessexample_pre" class="active_out">
</pre>
<div id="tuplesaccessexample_files" class="ac-files ac-files-hidden"></div>
</div>
<p>But if we try to use item assignment to modify one of the elements of the
tuple, we get an error:</p>
<div id="tuplesmutateexample" class="pywindow" >
<div id="tuplesmutateexample_code_div" style="display: block">
<textarea rows="2" id="tuplesmutateexample_code" class="active_code" prefixcode="undefined">
julia = ("Julia", "Roberts", 1967, "Duplicity", 2009, "Actress", "Atlanta, Georgia")
julia[0] = "X"</textarea>
</div>
<script type="text/javascript">
pythonTool.lineNumberFlags['tuplesmutateexample_code'] = true;
pythonTool.readOnlyFlags['tuplesmutateexample_code'] = false;
</script>
<div>
<button style="float:left" type='button' class='btn btn-run' id="tuplesmutateexample_runb">Run</button>
<button style="float:left; margin-left:150px;" type='button' class='btn' id="tuplesmutateexample_popb">Pop Out</button>
<button style="float:right" type="button" class='btn btn-reset' id="tuplesmutateexample_resetb">Reset</button>
<div style='clear:both'></div>
</div>
<div id='tuplesmutateexample_error'></div>
<div style="text-align: center">
<canvas id="tuplesmutateexample_canvas" class="ac-canvas" height="400" width="400" style="border-style: solid; display: none; text-align: center"></canvas>
</div>
<pre id="tuplesmutateexample_suffix" style="display:none">
</pre>
<pre id="tuplesmutateexample_pre" class="active_out">
</pre>
<div id="tuplesmutateexample_files" class="ac-files ac-files-hidden"></div>
</div>
<p>So like strings, tuples are immutable. Once Python has created a tuple
in memory, it cannot be changed.</p>
<p>Of course, even if we can’t modify the
elements of a tuple, we can always make the <tt class="docutils literal"><span class="pre">julia</span></tt> variable reference
a new tuple holding different information. To construct the new tuple,
it is convenient that we can slice parts of the old tuple and join up the
bits to make the new tuple. So if <tt class="docutils literal"><span class="pre">julia</span></tt> has a new recent film, we could
change her variable to reference a new tuple that used some information
from the old one:</p>
<div id="tuplesupdateexample" class="pywindow" >
<div id="tuplesupdateexample_code_div" style="display: block">
<textarea rows="3" id="tuplesupdateexample_code" class="active_code" prefixcode="undefined">
julia = ("Julia", "Roberts", 1967, "Duplicity", 2009, "Actress", "Atlanta, Georgia")
julia = julia[:3] + ("Eat Pray Love", 2010) + julia[5:]
print(julia)</textarea>
</div>
<script type="text/javascript">
pythonTool.lineNumberFlags['tuplesupdateexample_code'] = true;
pythonTool.readOnlyFlags['tuplesupdateexample_code'] = false;
</script>
<div>
<button style="float:left" type='button' class='btn btn-run' id="tuplesupdateexample_runb">Run</button>
<button style="float:left; margin-left:150px;" type='button' class='btn' id="tuplesupdateexample_popb">Pop Out</button>
<button style="float:right" type="button" class='btn btn-reset' id="tuplesupdateexample_resetb">Reset</button>
<div style='clear:both'></div>
</div>
<div id='tuplesupdateexample_error'></div>
<div style="text-align: center">
<canvas id="tuplesupdateexample_canvas" class="ac-canvas" height="400" width="400" style="border-style: solid; display: none; text-align: center"></canvas>
</div>
<pre id="tuplesupdateexample_suffix" style="display:none">
</pre>
<pre id="tuplesupdateexample_pre" class="active_out">
</pre>
<div id="tuplesupdateexample_files" class="ac-files ac-files-hidden"></div>
</div>
<p>To create a tuple with a single element (but you’re probably not likely
to do that too often), we have to include the final comma, because without
the final comma, Python treats the <tt class="docutils literal"><span class="pre">(5)</span></tt> below as an integer in parentheses:</p>
<blockquote>
<div><div class="highlight-none"><div class="highlight"><pre>>>> tup = (5,)
>>> type(tup)
<class 'tuple'>
>>> x = (5)
>>> type(x)
<class 'int'>
</pre></div>
</div>
</div></blockquote>
</div>
<div class="section" id="tuple-assignment">
<span id="index-1"></span><h2>8.2. Tuple assignment<a class="headerlink" href="#tuple-assignment" title="Permalink to this headline">¶</a></h2>
<p>Python has a very powerful <strong>tuple assignment</strong> feature that allows a tuple of variables
on the left of an assignment to be assigned values from a tuple
on the right of the assignment.</p>
<div id="tuplesassignexample" class="pywindow" >
<div id="tuplesassignexample_code_div" style="display: block">
<textarea rows="10" id="tuplesassignexample_code" class="active_code" prefixcode="undefined">
julia = ("Julia", "Roberts", 1967, "Duplicity", 2009, "Actress", "Atlanta, Georgia")
(name, surname, bYear, movie, mYear, profession, birthplace) = julia
print(name)
print(surname)
print(bYear)
print(movie)
print(mYear)
print(profession)
print(birthplace)</textarea>
</div>
<script type="text/javascript">
pythonTool.lineNumberFlags['tuplesassignexample_code'] = true;
pythonTool.readOnlyFlags['tuplesassignexample_code'] = false;
</script>
<div>
<button style="float:left" type='button' class='btn btn-run' id="tuplesassignexample_runb">Run</button>
<button style="float:left; margin-left:150px;" type='button' class='btn' id="tuplesassignexample_popb">Pop Out</button>
<button style="float:right" type="button" class='btn btn-reset' id="tuplesassignexample_resetb">Reset</button>
<div style='clear:both'></div>
</div>
<div id='tuplesassignexample_error'></div>
<div style="text-align: center">
<canvas id="tuplesassignexample_canvas" class="ac-canvas" height="400" width="400" style="border-style: solid; display: none; text-align: center"></canvas>
</div>
<pre id="tuplesassignexample_suffix" style="display:none">
</pre>
<pre id="tuplesassignexample_pre" class="active_out">
</pre>
<div id="tuplesassignexample_files" class="ac-files ac-files-hidden"></div>
</div>
<p>This does the equivalent of seven assignment statements, all on one easy line.
One requirement is that the number of variables on the left must match the number
of elements in the tuple.</p>
<p>One way to think of tuple assignment is as tuple packing/unpacking.
In tuple packing, the values are ‘packed’ together in a
tuple. In tuple unpacking, the values in a tuple are ‘unpacked’
into individual variables.</p>
<div id="tuplepacking" class="pywindow" >
<div id="tuplepacking_code_div" style="display: block">
<textarea rows="6" id="tuplepacking_code" class="active_code" prefixcode="undefined">
b = ("Bob", 19, "CS") # tuple packing
(name, age, studies) = b # tuple unpacking
print(name)
print(age)
print(studies)</textarea>
</div>
<script type="text/javascript">
pythonTool.lineNumberFlags['tuplepacking_code'] = true;
pythonTool.readOnlyFlags['tuplepacking_code'] = false;
</script>
<div>
<button style="float:left" type='button' class='btn btn-run' id="tuplepacking_runb">Run</button>
<button style="float:left; margin-left:150px;" type='button' class='btn' id="tuplepacking_popb">Pop Out</button>
<button style="float:right" type="button" class='btn btn-reset' id="tuplepacking_resetb">Reset</button>
<div style='clear:both'></div>
</div>
<div id='tuplepacking_error'></div>
<div style="text-align: center">
<canvas id="tuplepacking_canvas" class="ac-canvas" height="400" width="400" style="border-style: solid; display: none; text-align: center"></canvas>
</div>
<pre id="tuplepacking_suffix" style="display:none">
</pre>
<pre id="tuplepacking_pre" class="active_out">
</pre>
<div id="tuplepacking_files" class="ac-files ac-files-hidden"></div>
</div>
<p>Once in a while, it is useful to swap the values of two variables. With
conventional assignment statements, we have to use a temporary variable. For
example, to swap <tt class="docutils literal"><span class="pre">a</span></tt> and <tt class="docutils literal"><span class="pre">b</span></tt>:</p>
<div id="swapugly" class="pywindow" >
<div id="swapugly_code_div" style="display: block">
<textarea rows="9" id="swapugly_code" class="active_code" prefixcode="undefined">
a = 3
b = 5
# use a temporary variable to swap the values of a and b
temp = a
a = b
b = temp
print("a="+str(a)+" b="+str(b))</textarea>
</div>
<script type="text/javascript">
pythonTool.lineNumberFlags['swapugly_code'] = true;
pythonTool.readOnlyFlags['swapugly_code'] = false;
</script>
<div>
<button style="float:left" type='button' class='btn btn-run' id="swapugly_runb">Run</button>
<button style="float:left; margin-left:150px;" type='button' class='btn' id="swapugly_popb">Pop Out</button>
<button style="float:right" type="button" class='btn btn-reset' id="swapugly_resetb">Reset</button>
<div style='clear:both'></div>
</div>
<div id='swapugly_error'></div>
<div style="text-align: center">
<canvas id="swapugly_canvas" class="ac-canvas" height="400" width="400" style="border-style: solid; display: none; text-align: center"></canvas>
</div>
<pre id="swapugly_suffix" style="display:none">
</pre>
<pre id="swapugly_pre" class="active_out">
</pre>
<div id="swapugly_files" class="ac-files ac-files-hidden"></div>
</div>
<p>Tuple assignment solves this problem neatly:</p>
<div id="swapnice" class="pywindow" >
<div id="swapnice_code_div" style="display: block">
<textarea rows="7" id="swapnice_code" class="active_code" prefixcode="undefined">
a = 3
b = 5
# swap using tuples
(a,b) = (b,a)
print("a="+str(a)+" b="+str(b))</textarea>
</div>
<script type="text/javascript">
pythonTool.lineNumberFlags['swapnice_code'] = true;
pythonTool.readOnlyFlags['swapnice_code'] = false;
</script>
<div>
<button style="float:left" type='button' class='btn btn-run' id="swapnice_runb">Run</button>
<button style="float:left; margin-left:150px;" type='button' class='btn' id="swapnice_popb">Pop Out</button>
<button style="float:right" type="button" class='btn btn-reset' id="swapnice_resetb">Reset</button>
<div style='clear:both'></div>
</div>
<div id='swapnice_error'></div>
<div style="text-align: center">
<canvas id="swapnice_canvas" class="ac-canvas" height="400" width="400" style="border-style: solid; display: none; text-align: center"></canvas>
</div>
<pre id="swapnice_suffix" style="display:none">
</pre>
<pre id="swapnice_pre" class="active_out">
</pre>
<div id="swapnice_files" class="ac-files ac-files-hidden"></div>
</div>
<p>The left side is a tuple of variables; the right side is a tuple of values.
Each value is assigned to its respective variable. All the expressions on the
right side are evaluated before any of the assignments. This feature makes
tuple assignment quite versatile.</p>
<p>Naturally, the number of variables on the left and the number of values on the
right have to be the same — if you try to run the code below, you’ll get an error:</p>
<div id="tupleassignmenterror" class="pywindow" >
<div id="tupleassignmenterror_code_div" style="display: block">
<textarea rows="1" id="tupleassignmenterror_code" class="active_code" prefixcode="undefined">
(a,b,c,d) = (1,2,3)</textarea>
</div>
<script type="text/javascript">
pythonTool.lineNumberFlags['tupleassignmenterror_code'] = true;
pythonTool.readOnlyFlags['tupleassignmenterror_code'] = false;
</script>
<div>
<button style="float:left" type='button' class='btn btn-run' id="tupleassignmenterror_runb">Run</button>
<button style="float:left; margin-left:150px;" type='button' class='btn' id="tupleassignmenterror_popb">Pop Out</button>
<button style="float:right" type="button" class='btn btn-reset' id="tupleassignmenterror_resetb">Reset</button>
<div style='clear:both'></div>
</div>
<div id='tupleassignmenterror_error'></div>
<div style="text-align: center">
<canvas id="tupleassignmenterror_canvas" class="ac-canvas" height="400" width="400" style="border-style: solid; display: none; text-align: center"></canvas>
</div>
<pre id="tupleassignmenterror_suffix" style="display:none">
</pre>
<pre id="tupleassignmenterror_pre" class="active_out">
</pre>
<div id="tupleassignmenterror_files" class="ac-files ac-files-hidden"></div>
</div>
<span class="target" id="index-2"></span></div>
<div class="section" id="tuples-as-return-values">
<span id="index-3"></span><h2>8.3. Tuples as return values<a class="headerlink" href="#tuples-as-return-values" title="Permalink to this headline">¶</a></h2>
<p>Functions can always only return a single value, but by making that value a tuple,
we can effectively group together as many values
as we like, and return them together. This is very useful — we often want to
know some batsman’s highest and lowest score, or we want to find the mean and the standard
deviation, or we want to know the year, the month, and the day, or if we’re doing some
some ecological modeling we may want to know the number of rabbits and the number
of wolves on an island at a given time.</p>
<p>For example, we could write a function that returns both the area and the circumference
of a circle of radius r:</p>
<div id="circlecircumarea" class="pywindow" >
<div id="circlecircumarea_code_div" style="display: block">
<textarea rows="9" id="circlecircumarea_code" class="active_code" prefixcode="undefined">
import math
def circum_area(r):
""" Return (circumference, area) of a circle of radius r """
c = 2 * math.pi * r
a = math.pi * r * r
return (c, a)
print(circum_area(10))</textarea>
</div>
<script type="text/javascript">
pythonTool.lineNumberFlags['circlecircumarea_code'] = true;
pythonTool.readOnlyFlags['circlecircumarea_code'] = false;
</script>
<div>
<button style="float:left" type='button' class='btn btn-run' id="circlecircumarea_runb">Run</button>
<button style="float:left; margin-left:150px;" type='button' class='btn' id="circlecircumarea_popb">Pop Out</button>
<button style="float:right" type="button" class='btn btn-reset' id="circlecircumarea_resetb">Reset</button>
<div style='clear:both'></div>
</div>
<div id='circlecircumarea_error'></div>
<div style="text-align: center">
<canvas id="circlecircumarea_canvas" class="ac-canvas" height="400" width="400" style="border-style: solid; display: none; text-align: center"></canvas>
</div>
<pre id="circlecircumarea_suffix" style="display:none">
</pre>
<pre id="circlecircumarea_pre" class="active_out">
</pre>
<div id="circlecircumarea_files" class="ac-files ac-files-hidden"></div>
</div>
</div>
<div class="section" id="list-and-tuple-values">
<span id="index-4"></span><h2>8.4. List and Tuple values<a class="headerlink" href="#list-and-tuple-values" title="Permalink to this headline">¶</a></h2>
<p>There are several ways to create a new list; the simplest is to enclose the
elements in square brackets (<tt class="docutils literal"><span class="pre">[</span></tt> and <tt class="docutils literal"><span class="pre">]</span></tt>):</p>
<div id="listcreation1" class="pywindow" >
<div id="listcreation1_code_div" style="display: block">
<textarea rows="2" id="listcreation1_code" class="active_code" prefixcode="undefined">
ps = [10, 20, 30, 40]
qs = ["spam", "bungee", "swallow"]</textarea>
</div>
<script type="text/javascript">
pythonTool.lineNumberFlags['listcreation1_code'] = false;
pythonTool.readOnlyFlags['listcreation1_code'] = true;
</script>
<div id='listcreation1_error'></div>
<pre id="listcreation1_suffix" style="display:none">
</pre>
</div>
<p>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
(amazingly) another list:</p>
<div id="listcreation2" class="pywindow" >
<div id="listcreation2_code_div" style="display: block">
<textarea rows="1" id="listcreation2_code" class="active_code" prefixcode="undefined">
zs = ["hello", 2.0, 5, [10, 20]]</textarea>
</div>
<script type="text/javascript">
pythonTool.lineNumberFlags['listcreation2_code'] = false;
pythonTool.readOnlyFlags['listcreation2_code'] = true;
</script>
<div id='listcreation2_error'></div>
<pre id="listcreation2_suffix" style="display:none">
</pre>
</div>
<p>A list within another list is said to be <strong>nested</strong>.</p>
<p>Finally, a list with no elements is called an empty list,
and is denoted <tt class="docutils literal"><span class="pre">[]</span></tt>.</p>
<p>We can do more complicated things too. For example, we can make a list of tuples,
where one of the items in the tuple iss itself a list:</p>
<div id="listcreation3" class="pywindow" >
<div id="listcreation3_code_div" style="display: block">
<textarea rows="6" id="listcreation3_code" class="active_code" prefixcode="undefined">
students = [
("John", ["CompSci", "Physics"]),
("Vusi", ["Maths", "CompSci", "Stats"]),
("Jess", ["CompSci", "Accounting", "Economics", "Management"]),
("Sarah", ["InfSys", "Accounting", "Economics", "CommLaw"]),
("Zuki", ["Sociology", "Economics", "Law", "Stats", "Music"])]</textarea>
</div>
<script type="text/javascript">
pythonTool.lineNumberFlags['listcreation3_code'] = false;
pythonTool.readOnlyFlags['listcreation3_code'] = true;
</script>
<div id='listcreation3_error'></div>
<pre id="listcreation3_suffix" style="display:none">
</pre>
</div>
<p>Tuples items can themselves be other tuples. For example, we could improve
the information about our movie stars to hold the full date of birth rather
than just the year, and we could have a list of some of her movies and dates that they
were made, and so on:</p>
<div id="listcreation4" class="pywindow" >
<div id="listcreation4_code_div" style="display: block">
<textarea rows="9" id="listcreation4_code" class="active_code" prefixcode="undefined">
julia_more_info = ( ("Julia", "Roberts"), (8, "October", 1967),
"Actress", ("Atlanta", "Georgia"),
[ ("Duplicity", 2009),
("Notting Hill", 1999),
("Pretty Woman", 1990),
("Erin Brockovich", 2000),
("Eat Pray Love", 2010),
("Mona Lisa Smile", 2003),
("Oceans Twelve", 2004) ])</textarea>
</div>
<script type="text/javascript">
pythonTool.lineNumberFlags['listcreation4_code'] = false;
pythonTool.readOnlyFlags['listcreation4_code'] = true;
</script>
<div id='listcreation4_error'></div>
<pre id="listcreation4_suffix" style="display:none">
</pre>
</div>
<p>Notice in this case that the tuple has just five elements — but each of those in turn
can be another tuple, a list, a string, or any other kind of Python value.
This property is known as being <strong>heterogeneous</strong>, meaning that it can
be composed of elements of different types.</p>
<span class="target" id="accessing-elements"></span></div>
<div class="section" id="index-5">
<span id="id1"></span><h2>8.5. Accessing elements<a class="headerlink" href="#index-5" title="Permalink to this headline">¶</a></h2>
<p>The syntax for accessing the elements of a list is the same as the syntax for
accessing the characters of a string or a tuple — the index operator: <tt class="docutils literal"><span class="pre">[]</span></tt> (not to
be confused with an empty list). The expression inside the brackets specifies
the index. Remember that the indices start at 0:</p>
<div id="listaccessing1" class="pywindow" >
<div id="listaccessing1_code_div" style="display: block">
<textarea rows="3" id="listaccessing1_code" class="active_code" prefixcode="undefined">
numbers = [17, 5]
a = numbers[0]
print(a)</textarea>
</div>
<script type="text/javascript">
pythonTool.lineNumberFlags['listaccessing1_code'] = true;
pythonTool.readOnlyFlags['listaccessing1_code'] = false;
</script>
<div>
<button style="float:left" type='button' class='btn btn-run' id="listaccessing1_runb">Run</button>
<button style="float:left; margin-left:150px;" type='button' class='btn' id="listaccessing1_popb">Pop Out</button>
<button style="float:right" type="button" class='btn btn-reset' id="listaccessing1_resetb">Reset</button>
<div style='clear:both'></div>
</div>
<div id='listaccessing1_error'></div>
<div style="text-align: center">
<canvas id="listaccessing1_canvas" class="ac-canvas" height="400" width="400" style="border-style: solid; display: none; text-align: center"></canvas>
</div>
<pre id="listaccessing1_suffix" style="display:none">
</pre>
<pre id="listaccessing1_pre" class="active_out">
</pre>
<div id="listaccessing1_files" class="ac-files ac-files-hidden"></div>
</div>
<p>Any expression evaluating to an integer can be used as an index:</p>
<div id="listaccessing2" class="pywindow" >
<div id="listaccessing2_code_div" style="display: block">
<textarea rows="3" id="listaccessing2_code" class="active_code" prefixcode="undefined">
numbers = [17, 5]
b = numbers[9-8]
print(b)</textarea>
</div>
<script type="text/javascript">
pythonTool.lineNumberFlags['listaccessing2_code'] = true;
pythonTool.readOnlyFlags['listaccessing2_code'] = false;
</script>
<div>
<button style="float:left" type='button' class='btn btn-run' id="listaccessing2_runb">Run</button>
<button style="float:left; margin-left:150px;" type='button' class='btn' id="listaccessing2_popb">Pop Out</button>
<button style="float:right" type="button" class='btn btn-reset' id="listaccessing2_resetb">Reset</button>
<div style='clear:both'></div>
</div>
<div id='listaccessing2_error'></div>
<div style="text-align: center">
<canvas id="listaccessing2_canvas" class="ac-canvas" height="400" width="400" style="border-style: solid; display: none; text-align: center"></canvas>
</div>
<pre id="listaccessing2_suffix" style="display:none">
</pre>
<pre id="listaccessing2_pre" class="active_out">
</pre>
<div id="listaccessing2_files" class="ac-files ac-files-hidden"></div>
</div>
<p>If you try to access or assign to an element that does not exist, you get a runtime
error:</p>
<div id="listaccessing4" class="pywindow" >
<div id="listaccessing4_code_div" style="display: block">
<textarea rows="3" id="listaccessing4_code" class="active_code" prefixcode="undefined">
numbers = [17, 5]
d = numbers[2] # will give an error
print(d)</textarea>
</div>
<script type="text/javascript">
pythonTool.lineNumberFlags['listaccessing4_code'] = true;
pythonTool.readOnlyFlags['listaccessing4_code'] = false;
</script>
<div>
<button style="float:left" type='button' class='btn btn-run' id="listaccessing4_runb">Run</button>
<button style="float:left; margin-left:150px;" type='button' class='btn' id="listaccessing4_popb">Pop Out</button>
<button style="float:right" type="button" class='btn btn-reset' id="listaccessing4_resetb">Reset</button>
<div style='clear:both'></div>
</div>
<div id='listaccessing4_error'></div>
<div style="text-align: center">
<canvas id="listaccessing4_canvas" class="ac-canvas" height="400" width="400" style="border-style: solid; display: none; text-align: center"></canvas>
</div>
<pre id="listaccessing4_suffix" style="display:none">
</pre>
<pre id="listaccessing4_pre" class="active_out">
</pre>
<div id="listaccessing4_files" class="ac-files ac-files-hidden"></div>
</div>
<p>It is common to use a loop variable as a list index.</p>
<div id="listtraversaldumb" class="pywindow" >
<div id="listtraversaldumb_code_div" style="display: block">
<textarea rows="4" id="listtraversaldumb_code" class="active_code" prefixcode="undefined">
horsemen = ["war", "famine", "pestilence", "death"]
for i in [0, 1, 2, 3]:
print(horsemen[i])</textarea>
</div>
<script type="text/javascript">
pythonTool.lineNumberFlags['listtraversaldumb_code'] = true;
pythonTool.readOnlyFlags['listtraversaldumb_code'] = false;
</script>
<div>
<button style="float:left" type='button' class='btn btn-run' id="listtraversaldumb_runb">Run</button>
<button style="float:left; margin-left:150px;" type='button' class='btn' id="listtraversaldumb_popb">Pop Out</button>
<button style="float:right" type="button" class='btn btn-reset' id="listtraversaldumb_resetb">Reset</button>
<div style='clear:both'></div>
</div>
<div id='listtraversaldumb_error'></div>
<div style="text-align: center">
<canvas id="listtraversaldumb_canvas" class="ac-canvas" height="400" width="400" style="border-style: solid; display: none; text-align: center"></canvas>
</div>
<pre id="listtraversaldumb_suffix" style="display:none">
</pre>
<pre id="listtraversaldumb_pre" class="active_out">
</pre>
<div id="listtraversaldumb_files" class="ac-files ac-files-hidden"></div>
</div>
<p>Each time through the loop, the variable <tt class="docutils literal"><span class="pre">i</span></tt> is used as an index into the
list, printing the <tt class="docutils literal"><span class="pre">i</span></tt>‘th element. This pattern of computation is called a
<strong>list traversal</strong>.</p>
<p>The above sample doesn’t need or use the index <tt class="docutils literal"><span class="pre">i</span></tt> for anything besides getting
the items from the list, so this more direct version — where the <tt class="docutils literal"><span class="pre">for</span></tt> loop gets
the items — might be preferred:</p>
<div id="listtraversalsmart" class="pywindow" >
<div id="listtraversalsmart_code_div" style="display: block">
<textarea rows="4" id="listtraversalsmart_code" class="active_code" prefixcode="undefined">
horsemen = ["war", "famine", "pestilence", "death"]
for h in horsemen:
print(h)</textarea>
</div>
<script type="text/javascript">
pythonTool.lineNumberFlags['listtraversalsmart_code'] = true;
pythonTool.readOnlyFlags['listtraversalsmart_code'] = false;
</script>
<div>
<button style="float:left" type='button' class='btn btn-run' id="listtraversalsmart_runb">Run</button>
<button style="float:left; margin-left:150px;" type='button' class='btn' id="listtraversalsmart_popb">Pop Out</button>
<button style="float:right" type="button" class='btn btn-reset' id="listtraversalsmart_resetb">Reset</button>
<div style='clear:both'></div>
</div>
<div id='listtraversalsmart_error'></div>
<div style="text-align: center">
<canvas id="listtraversalsmart_canvas" class="ac-canvas" height="400" width="400" style="border-style: solid; display: none; text-align: center"></canvas>
</div>
<pre id="listtraversalsmart_suffix" style="display:none">
</pre>
<pre id="listtraversalsmart_pre" class="active_out">
</pre>
<div id="listtraversalsmart_files" class="ac-files ac-files-hidden"></div>
</div>
<p>The function <tt class="docutils literal"><span class="pre">len</span></tt> returns the length of a list, which is equal to the number
of its elements. If you are going to use an integer index to access the list,
it is a good idea to use this value as the upper bound of a
loop instead of a constant. That way, if the size of the list changes, you
won’t have to go through the program changing all the loops; they will work
correctly for any size list:</p>
<div id="listtraversalokay" class="pywindow" >
<div id="listtraversalokay_code_div" style="display: block">
<textarea rows="4" id="listtraversalokay_code" class="active_code" prefixcode="undefined">
horsemen = ["war", "famine", "pestilence", "death"]
for i in range(len(horsemen)):
print(horsemen[i])</textarea>
</div>
<script type="text/javascript">
pythonTool.lineNumberFlags['listtraversalokay_code'] = true;
pythonTool.readOnlyFlags['listtraversalokay_code'] = false;
</script>
<div>
<button style="float:left" type='button' class='btn btn-run' id="listtraversalokay_runb">Run</button>
<button style="float:left; margin-left:150px;" type='button' class='btn' id="listtraversalokay_popb">Pop Out</button>
<button style="float:right" type="button" class='btn btn-reset' id="listtraversalokay_resetb">Reset</button>
<div style='clear:both'></div>
</div>
<div id='listtraversalokay_error'></div>
<div style="text-align: center">
<canvas id="listtraversalokay_canvas" class="ac-canvas" height="400" width="400" style="border-style: solid; display: none; text-align: center"></canvas>
</div>
<pre id="listtraversalokay_suffix" style="display:none">
</pre>
<pre id="listtraversalokay_pre" class="active_out">
</pre>
<div id="listtraversalokay_files" class="ac-files ac-files-hidden"></div>
</div>
<p>The last time the body of the loop is executed, <tt class="docutils literal"><span class="pre">i</span></tt> is <tt class="docutils literal"><span class="pre">len(horsemen)</span> <span class="pre">-</span> <span class="pre">1</span></tt>,
which is the index of the last element. (But the version without the index
looks even better now!)</p>
<p>Although a list can contain another list, the nested list still counts as a
single element in its parent list. The length of this list is 4:</p>
<div id="listlengthexample" class="pywindow" >
<div id="listlengthexample_code_div" style="display: block">
<textarea rows="1" id="listlengthexample_code" class="active_code" prefixcode="undefined">
print(len(["car makers", 1, ["Ford", "Toyota", "BMW"], [1, 2, 3]]))</textarea>
</div>
<script type="text/javascript">
pythonTool.lineNumberFlags['listlengthexample_code'] = true;
pythonTool.readOnlyFlags['listlengthexample_code'] = false;
</script>
<div>
<button style="float:left" type='button' class='btn btn-run' id="listlengthexample_runb">Run</button>
<button style="float:left; margin-left:150px;" type='button' class='btn' id="listlengthexample_popb">Pop Out</button>
<button style="float:right" type="button" class='btn btn-reset' id="listlengthexample_resetb">Reset</button>
<div style='clear:both'></div>
</div>
<div id='listlengthexample_error'></div>
<div style="text-align: center">
<canvas id="listlengthexample_canvas" class="ac-canvas" height="400" width="400" style="border-style: solid; display: none; text-align: center"></canvas>
</div>
<pre id="listlengthexample_suffix" style="display:none">
</pre>
<pre id="listlengthexample_pre" class="active_out">
</pre>
<div id="listlengthexample_files" class="ac-files ac-files-hidden"></div>
</div>
<p><tt class="docutils literal"><span class="pre">in</span></tt> and <tt class="docutils literal"><span class="pre">not</span> <span class="pre">in</span></tt> are Boolean operators that test membership in a sequence. We
used them previously with strings, but they also work with lists and
other sequences:</p>
<div id="listmembershipexample" class="pywindow" >
<div id="listmembershipexample_code_div" style="display: block">
<textarea rows="4" id="listmembershipexample_code" class="active_code" prefixcode="undefined">
horsemen = ["war", "famine", "pestilence", "death"]
print("pestilence" in horsemen) # True
print("debauchery" in horsemen) # False
print("debauchery" not in horsemen) # False</textarea>
</div>
<script type="text/javascript">
pythonTool.lineNumberFlags['listmembershipexample_code'] = true;
pythonTool.readOnlyFlags['listmembershipexample_code'] = false;
</script>
<div>
<button style="float:left" type='button' class='btn btn-run' id="listmembershipexample_runb">Run</button>
<button style="float:left; margin-left:150px;" type='button' class='btn' id="listmembershipexample_popb">Pop Out</button>
<button style="float:right" type="button" class='btn btn-reset' id="listmembershipexample_resetb">Reset</button>
<div style='clear:both'></div>
</div>
<div id='listmembershipexample_error'></div>
<div style="text-align: center">
<canvas id="listmembershipexample_canvas" class="ac-canvas" height="400" width="400" style="border-style: solid; display: none; text-align: center"></canvas>
</div>
<pre id="listmembershipexample_suffix" style="display:none">
</pre>
<pre id="listmembershipexample_pre" class="active_out">
</pre>
<div id="listmembershipexample_files" class="ac-files ac-files-hidden"></div>
</div>
</div>
<div class="section" id="list-operations">
<span id="index-6"></span><h2>8.6. List operations<a class="headerlink" href="#list-operations" title="Permalink to this headline">¶</a></h2>
<p>The <tt class="docutils literal"><span class="pre">+</span></tt> operator concatenates lists:</p>
<div id="listconcatexample" class="pywindow" >
<div id="listconcatexample_code_div" style="display: block">
<textarea rows="4" id="listconcatexample_code" class="active_code" prefixcode="undefined">
a = [1, 2, 3]
b = [4, 5, 6]
c = a + b
print(c)</textarea>
</div>
<script type="text/javascript">
pythonTool.lineNumberFlags['listconcatexample_code'] = true;
pythonTool.readOnlyFlags['listconcatexample_code'] = false;
</script>
<div>
<button style="float:left" type='button' class='btn btn-run' id="listconcatexample_runb">Run</button>
<button style="float:left; margin-left:150px;" type='button' class='btn' id="listconcatexample_popb">Pop Out</button>
<button style="float:right" type="button" class='btn btn-reset' id="listconcatexample_resetb">Reset</button>
<div style='clear:both'></div>
</div>
<div id='listconcatexample_error'></div>
<div style="text-align: center">
<canvas id="listconcatexample_canvas" class="ac-canvas" height="400" width="400" style="border-style: solid; display: none; text-align: center"></canvas>
</div>
<pre id="listconcatexample_suffix" style="display:none">
</pre>
<pre id="listconcatexample_pre" class="active_out">
</pre>
<div id="listconcatexample_files" class="ac-files ac-files-hidden"></div>
</div>
<p>Similarly, the <tt class="docutils literal"><span class="pre">*</span></tt> operator repeats a list a given number of times:</p>
<div id="listrepeatexample" class="pywindow" >
<div id="listrepeatexample_code_div" style="display: block">
<textarea rows="5" id="listrepeatexample_code" class="active_code" prefixcode="undefined">
a = [0]
b = [0] * 4
print(b)
c = [1, 2, 3] * 3
print(c)</textarea>
</div>
<script type="text/javascript">