forked from ninas/umonya_notes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tuples.html
295 lines (238 loc) · 10 KB
/
tuples.html
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
<!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>
<title>Introductory Programming in Python: Tuples</title>
<link rel='stylesheet' type='text/css' href='style.css' />
<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />
<script src="animation.js" type="text/javascript">
</script>
</head>
<body onload="animate_loop()">
<div class="page">
<h1>Introductory Programming in Python: Lesson 9<br />
Tuples</h1>
<div class="centered">
[<a href="lists.html">Prev: Lists</a>] [<a href="index.html">Course Outline</a>] [<a href="for_loops.html">Next: Flow Control: Sequencial Loops</a>]
</div>
<h2>Tuples as Immutable Lists</h2>
<p>In many ways tuples and lists are very similar. In fact <a
class="doclink"
href="http://olympiad.cs.uct.ac.za/docs/python-docs-2.6/library/stdtypes.html#typesseq">tuples</a> are
basically immutable lists, that is, lists which cannot be changed. All
the same operators work on them: concatenation, repetition,
subscription, and slicing. All the comparison operators work in the
same way: equivalence, less than, greater than, 'is'. However,
<strong>assignments to tuples cannot be made</strong> as they are
immutable, or unchangeable. Once a tuple has been formed, it cannot be
changed. New tuples can be formed from others using concatenation,
repetition, etc... but the operand tuples remain unchanged by the
operators.</p>
<h2>Forming a Tuple</h2>
<p>Tuples are technically formed in python using a comma, although most
often they are found recorded in round braces. Tuples can be of any
length, and have their elements indexed from 0 to len(tuple)-1.</p>
<pre class='listing'>
Python 2.6.4 (r264:75706, Dec 7 2009, 18:43:55) [MSC v.1310 32 bit (Intel)] on win32
[GCC 3.4.6 (Gentoo 3.4.6-r1, ssp-3.4.5-1.0, pie-8.7.9)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 1, 2
(1, 2)
>>> 1,
(1,)
>>> (1)
1
>>> (1, 2)
(1, 2)
>>> ("Tuples", "can", "have", "elements", "of", "more", "than", 1, "type")
('Tuples', 'can', 'have', 'elements', 'of', 'more', 'than', 1, 'type')
>>>
</pre>
<h2>Using Tuples</h2>
<p>Breaking it down we get to the old grind of operators, and in the
case of tuples a few new ideas. Let's get the operators out of the
way! If both 'a' and 'b' are tuples, 'v' is any expression, and 'i',
'j', and 'k' are integers then</p>
<ul>
<li><code>a + b</code> yields Concatenation.</li>
<li><code>a * i</code> yields Repetition.</li>
<li><code>a[i]</code> yields Subscription, or the 'i'th element of
'a'.</li>
<li><code>a[i:j:k]</code> yields Slicing, or a copy of the list 'a'
from its 'i'th element to its (j-1)'th element, taking only every
'k'th element. If 'k' is omitted, every element in the range is
taken.</li>
<li><code>a[:i]</code> yields a slice from the beginning of the
list to (i-1)'th element of 'a'.</li>
<li><code>a[i:]</code> yields a slice from the 'i'th element to the
end of the tuple.</li>
<li><code>a[:]</code> yields a slice of the entire tuple.</li>
</ul>
<p>For completeness sake, here are examples ...</p>
<pre class='listing'>
Python 2.6.4 (r264:75706, Dec 7 2009, 18:43:55) [MSC v.1310 32 bit (Intel)] on win32
[GCC 3.4.6 (Gentoo 3.4.6-r1, ssp-3.4.5-1.0, pie-8.7.9)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a = (1,2,3)
>>> a+(4,5)
(1, 2, 3, 4, 5)
>>>
>>> (4,5)+a
(4, 5, 1, 2, 3)
</pre>
<pre class='listing'>
>>> a*2
(1, 2, 3, 1, 2, 3)
>>>
>>> (1,)*2+2*(2,)
(1, 1, 2, 2)
>>>
>>> ((1,)*2,(2,)*2)
((1, 1), (2, 2))
>>>
>>> (1,)*2*3
(1, 1, 1, 1, 1, 1)
>>>
</pre>
<pre class='listing'>
>>> a[0]
1
>>> a[1:3]
(2, 3)
>>> a = (1, 2, 3, 4, 5)
>>> a[0:6:2]
(1, 3, 5)
>>> a[:3]
(1, 2, 3)
>>> a[3:]
(4, 5)
>>> a[:]
(1, 2, 3, 4, 5)
>>>
</pre>
<p>The comparison of tuples to other tuples happens in the same way as
lists to lists.</p>
<ul>
<li><code>a == b</code> yields Equivalence</li>
<li><code>a < b</code> yields Less Than. Note that tuples are
compared in sequence order, meaning that 'a' is less then 'b' if
'a's first element is less than 'b's first element. If 'a's first
element and 'b's first element are equal, the second elements are
checked, etc...</li>
<li><code>v in a</code> is True only if the tuple 'a' contains an
element whose value is that of the expression 'v'.</li>
<li><code>a is b</code> is True only if 'a' and 'b' are the same
tuple.</li>
</ul>
<p>If tuples have a subset of the functionality of lists, why ever use
them? What can they do that lists cannot. Well, actually they provide a
very convenient way to package multiple variables together for passing
to a function as a parameter, or more likely returning from a function.
Technically speaking functions can only return one value, but since a
tuple is a single 'value' no matter how many elements it contains, a
tuple could be used in a function that returns a two-component piece of
data, for example an x:y coordinate. Even better, is that python
<strong>implicitly unpacks tuples</strong>. By unpack we mean the
assignment of multiple variables at once to their respective (based on
position) elements in a tuple, for example</p>
<pre class='listing'>
>>> t = (1, 2, 3)
>>> a, b, c = t
>>> a
1
>>> b
2
>>> c
3
>>>
</pre>
<p>And since tuples are formed by a comma, this provides us with a
nifty little method to swap the values of two variables,</p>
<pre class='listing'>
>>> a = 1
>>> b = 2
>>> b, a = a, b
>>> a
2
>>> b
1
>>>
</pre>
<h2>Exercises</h2>
<ol>
<li>If the use of a comma forms a tuple, then how do we indicate a
tuple as an expression to the print statement, rather than its
elements as separate expressions?</li>
<li>What is the difference between concatenation and addition of
tuples? Why is the python plus operator for tuples a concatenation
operator instead of an addition operator?</li>
<li>The code <code>a, b = b, a</code> swaps the values of <em>a</em>
and <em>b</em>. What would happen if added a third variable to the
mix, <em>c</em>, as in <code>a, b, c = b, c, a</code>? What would
happen if one repeated the statement indefinitely?</li>
<li>Given a variable with the value of the empty tuple (<code>a =
()</code>), how does one 'append' an element to 'a'?</li>
<li>Write a program that accepts a list of numbers terminated by a
blank line. Print out the entered numbers as elements of a tuple, in
the order they were entered.</li>
<li>Given a list of tuples each specifying a subject name and a
grade symbol ('A' - 'F') in the form <code>[('Maths', 'D'),
('Comp Sci', 'B'), ('English', 'C'), ('French', 'A'),
('Science', 'B'), ('History', 'E')]</code>: <ol>
<li>Write a program that prints out the subject with the highest
mark.</li>
<li>Write a program that outputs each subject and the grade
symbol in the format 'subject: symbol', with each subject on a
single line.</li>
<li>Write a program that prints out a tab separated list of
subjects on the first line, and the corresponding grades, also
tab separated on the second line.</li>
</ol></li>
<li>Write a program that accepts a list of numbers terminated by a
blank line, and stores the result in a tuple, <em>a</em>. Repeat the
process to form a second user inputted tuple, <em>b</em>, making
sure there are the same number of elements in <em>b</em> as in
<em>a</em>. Print out the result of the <strong>mathematical
addition</strong> (not concatenation) of the two tuples as a
tuple.</li>
<li>Write a program that reads a name and an age for a person, until
the name is blank. As each name age pair is entered, store names in
a list, and ages in another. Print a list of tuples of paired names
and ages.</li>
<li>Write a program that reads a name and an age for a person, until
the name is blank. Once all names have been present the user with an
option to list the entered people in alphabetical order, or in
descending age order. For either choice, list each person's name
followed by their age on a single line. Make sure you output the
correct age for the correct person.</li>
<!--
<li>
Write a function that returns the sum of two vectors, where the
sum of two vectors is a vector of the same dimension (i.e. has
the same number of elements) as both the original vectors (i.e.
original vectors must be of equal dimension, otherwise return
None), and has each element equal to the sum of its respective
elements from the original two vectors.<br />
<br />
<code>[x, y, z] + [a, b, c] = [x+a, y+b, z+c]</code><br />
<br />
Then ask the user to enter the direction and speed (in the form
of a 2 dimensional vector) of the wind, and again of an object
travelling in a two dimensional space. Your program should
output the vector representing the resultant direction vector of
the object.<br />
<br />
<a href="http://www.physicsclassroom.com/Class/vectors/U3L3a.html">Some High School Physics Background</a><br />
<a href="http://kipper.crk.umn.edu/physics/1012/xtr/vectors.html">More Complex, but More Complete</a>
</li>
-->
</ol>
<div class="centered">
[<a href="lists.html">Prev: Lists</a>] [<a href="index.html">Course Outline</a>] [<a href="for_loops.html">Next: Flow Control: Sequencial Loops</a>]
</div>
</div>
<div class="pagefooter">
Copyright © James Dominy 2007-2008; Released under the <a href="http://www.gnu.org/copyleft/fdl.html">GNU Free Documentation License</a><br />
<a href="intropython.tar.gz">Download the tarball</a>
</div>
</body>
</html>