|
1 Lists and Tuples |
|
2 ================ |
|
3 |
|
4 Lists |
|
5 ----- |
|
6 |
|
7 Python provides an intuitive way to represent a group items, called *Lists*. The |
|
8 items of a *List* are called its elements. Unlike C/C++, elements can be of any |
|
9 type. A *List* is represented as a list of comma-sepated elements with square |
|
10 brackets around them:: |
|
11 |
|
12 >>> a = [10, 'Python programming', 20.3523, 23, 3534534L] |
|
13 >>> a |
|
14 [10, 'Python programming', 20.3523, 23, 3534534L] |
|
15 |
|
16 |
|
17 Common List Operations |
|
18 ~~~~~~~~~~~~~~~~~~~~~~ |
|
19 |
|
20 The following are some of the most commonly used operations on *Lists*. |
|
21 |
|
22 |
|
23 ~~~~~~~~ |
|
24 Indexing |
|
25 ~~~~~~~~ |
|
26 |
|
27 Individual elements of a *List* can be accessed using an index to the element. |
|
28 The indices start at 0. One can also access the elements of the *List* in reverse |
|
29 using negative indices.:: |
|
30 |
|
31 >>> a[1] |
|
32 'Python programming' |
|
33 >>> a[-1] |
|
34 3534534L |
|
35 |
|
36 It is important to note here that the last element of the *List* has an index of |
|
37 -1. |
|
38 |
|
39 ~~~~~~~~~~~~~ |
|
40 Concatenating |
|
41 ~~~~~~~~~~~~~ |
|
42 |
|
43 Two or more *Lists* can be concatenated using the + operator:: |
|
44 |
|
45 >>> a + ['foo', 12, 23.3432, 54] |
|
46 [10, 'Python programming', 20.3523, 'foo', 12, 23.3432, 54] |
|
47 >>> [54, 75, 23] + ['write', 67, 'read'] |
|
48 [54, 75, 23, 'write', 67, 'read'] |
|
49 |
|
50 |
|
51 ~~~~~~~ |
|
52 Slicing |
|
53 ~~~~~~~ |
|
54 |
|
55 A *List* can be sliced off to contain a subset of elements of the *List*. Slicing |
|
56 can be done by using two indices separated by a colon, where the first index is |
|
57 inclusive and the second index is exclusive. The resulting slice is also a *List*.:: |
|
58 |
|
59 >>> num = [1, 2, 3, 4, 5, 6, 7, 8, 9] |
|
60 >>> num[3:6] |
|
61 [4, 5, 6] |
|
62 >>> num[0:1] |
|
63 [1] |
|
64 >>> num[7:10] |
|
65 [7, 8, 9] |
|
66 |
|
67 The last example showed how to access last 3 elements of the *List*. There is a |
|
68 small catch here. The second index 10 actually refers to the 11th element of the |
|
69 *List* which is still valid, even though it doesn't exist because the second |
|
70 index is exclusive and tells the Python interpreter to get the last element of |
|
71 the *List*. But this can also be done in a much easier way using negative indices:: |
|
72 |
|
73 >>> num[-3:-1] |
|
74 [7, 8, 9] |
|
75 |
|
76 Excluding the first index implies that the slice must start at the beginning of |
|
77 the *List*, while excluding the second index includes all the elements till the |
|
78 end of the *List*. A third parameter to a slice, which is implicitly taken as 1 |
|
79 is the step of the slice. It is specified as a value which follows a colon after |
|
80 the second index:: |
|
81 |
|
82 >>> num[:4] |
|
83 [1, 2, 3, 4] |
|
84 >>> num[7:] |
|
85 [8, 9] |
|
86 >>> num[-3:] |
|
87 [7, 8, 9] |
|
88 >>> num[:] |
|
89 [1, 2, 3, 4, 5, 6, 7, 8, 9] |
|
90 >>> num[4:9:3] |
|
91 [5, 8] |
|
92 >>> num[3::2] |
|
93 [4, 6, 8] |
|
94 >>> num[::4] |
|
95 [1, 5, 9] |
|
96 |
|
97 |
|
98 ~~~~~~~~~~~~~~ |
|
99 Multiplication |
|
100 ~~~~~~~~~~~~~~ |
|
101 |
|
102 |
|
103 A *List* can be multiplied with an integer to repeat itself:: |
|
104 |
|
105 >>> [20] * 5 |
|
106 [20, 20, 20, 20, 20] |
|
107 >>> [42, 'Python', 54] * 3 |
|
108 [42, 'Python', 54, 42, 'Python', 54, 42, 'Python', 54] |
|
109 |
|
110 |
|
111 ~~~~~~~~~~ |
|
112 Membership |
|
113 ~~~~~~~~~~ |
|
114 |
|
115 **in** operator is used to find whether an element is part of the *List*. It |
|
116 returns **True** if the element is present in the *List* or **False** if it is not |
|
117 present. Since this operator returns a Boolean value it is called a Boolean |
|
118 operator:: |
|
119 |
|
120 >>> names = ['Guido', 'Alex', 'Tim'] |
|
121 >>> 'Tim' in names |
|
122 True |
|
123 >>> 'Adam' in names |
|
124 False |
|
125 |
|
126 |
|
127 ~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
|
128 Length, Maximum and Minimum |
|
129 ~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
|
130 |
|
131 Length of a *List* can be found out using the len function. The max function |
|
132 returns the element with the largest value and the min function returns the |
|
133 element with the smallest value:: |
|
134 |
|
135 >>> num = [4, 1, 32, 12, 67, 34, 65] |
|
136 >>> len(num) |
|
137 7 |
|
138 >>> max(num) |
|
139 67 |
|
140 >>> min(num) |
|
141 1 |
|
142 |
|
143 |
|
144 ~~~~~~~~~~~~~~~~~ |
|
145 Changing Elements |
|
146 ~~~~~~~~~~~~~~~~~ |
|
147 |
|
148 Unlike Strings *Lists* are mutable, i.e. elements of a *List* can be manipulated:: |
|
149 |
|
150 >>> a = [1, 3, 5, 7] |
|
151 >>> a[2] = 9 |
|
152 >>> a |
|
153 [1, 3, 9, 7] |
|
154 |
|
155 |
|
156 ~~~~~~~~~~~~~~~~~ |
|
157 Deleting Elements |
|
158 ~~~~~~~~~~~~~~~~~ |
|
159 |
|
160 An element or a slice of a *List* can be deleted by using the **del** statement:: |
|
161 |
|
162 >>> a = [1, 3, 5, 7, 9, 11] |
|
163 >>> del a[-2:] |
|
164 >>> a |
|
165 [1, 3, 5, 7] |
|
166 >>> del a[1] |
|
167 >>> a |
|
168 [1, 5, 7] |
|
169 |
|
170 |
|
171 ~~~~~~~~~~~~~~~~ |
|
172 Assign to Slices |
|
173 ~~~~~~~~~~~~~~~~ |
|
174 |
|
175 In the same way, values can be assigned to individual elements of the *List*, |
|
176 a *List* of elements can be assigned to a slice:: |
|
177 |
|
178 >>> a = [2, 3, 4, 5] |
|
179 >>> a[:2] = [0, 1] |
|
180 [0, 1, 4, 5] |
|
181 >>> a[2:2] = [2, 3] |
|
182 >>> a |
|
183 [0, 1, 2, 3, 4, 5] |
|
184 >>> a[2:4] = [] |
|
185 >>> a |
|
186 [0, 1, 4, 5] |
|
187 |
|
188 The last two examples should be particularly noted carefully. The last but one |
|
189 example insert elements or a list of elements into a *List* and the last example |
|
190 deletes a list of elements from the *List*. |
|
191 |
|
192 |
|
193 None, Empty Lists, and Initialization |
|
194 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
|
195 |
|
196 An *Empty List* is a *List* with no elements and is simply represented as |
|
197 []. A *None List* is one with all elements in it being **None**. It serves |
|
198 the purpose having a container list of some fixed number of elements with |
|
199 no value:: |
|
200 |
|
201 >>> a = [] |
|
202 >>> a |
|
203 [] |
|
204 >>> n = [None] * 10 |
|
205 >>> n |
|
206 [None, None, None, None, None, None, None, None, None, None] |
|
207 |
|
208 |
|
209 Nested Lists |
|
210 ~~~~~~~~~~~~ |
|
211 |
|
212 As mentioned earlier, a List can contain elements of any data type. This also |
|
213 implies a *List* can have a *Lists* themselves as its elements. These are |
|
214 called as *Nested Lists*. There is no limit on the depth of the *Nested Lists*:: |
|
215 |
|
216 >>> a = [1, [1, 2, 3], 3, [1, [1, 2, 3]], 7] |
|
217 |
|
218 |
|
219 List Methods |
|
220 ~~~~~~~~~~~~ |
|
221 |
|
222 A method is a function that is coupled to an object. More about objects |
|
223 and its methods are discussed in Advanced Python module. In general, a |
|
224 method is called like:: |
|
225 |
|
226 object.method(arguments) |
|
227 |
|
228 For now, it is enough to know that a list of elements is an object and |
|
229 so *List* methods can be called upon them. Also some of the methods change |
|
230 the *List* in-place, meaning it modifies the existing list instead of creating |
|
231 a new one, while other methods don't. It must be noted as we run through |
|
232 the *List* methods. |
|
233 |
|
234 Some of the most commonly used *List* methods are as follows: |
|
235 |
|
236 |
|
237 ~~~~~~ |
|
238 append |
|
239 ~~~~~~ |
|
240 |
|
241 The *append* method is used to append an object at the end of the list:: |
|
242 |
|
243 >>> prime = [2, 3, 5] |
|
244 >>> prime.append(7) |
|
245 >>> prime |
|
246 [2, 3, 5, 7] |
|
247 |
|
248 It is important to note that append changes the *List* in-place. |
|
249 |
|
250 |
|
251 ~~~~~ |
|
252 count |
|
253 ~~~~~ |
|
254 |
|
255 The *count* method returns the number of occurences of a particular element |
|
256 in a list:: |
|
257 |
|
258 >>> [1, 4, 4, 9, 9, 9].count(9) |
|
259 3 |
|
260 >>> tlst = ['Python', 'is', 'a', 'beautiful', 'language'] |
|
261 >>> tlst.count('Python') |
|
262 1 |
|
263 |
|
264 |
|
265 ~~~~~~ |
|
266 extend |
|
267 ~~~~~~ |
|
268 |
|
269 The *extend* method extends the list on which it is called by the list supplied |
|
270 as argument to it:: |
|
271 |
|
272 >>> a = [1, 2, 3] |
|
273 >>> b = [4, 5, 6] |
|
274 >>> a.extend(b) |
|
275 [1, 2, 3, 4, 5, 6] |
|
276 |
|
277 This is an in-place method. This method is equivalent to using the + operator, but |
|
278 using the + operator returns a new list. |
|
279 |
|
280 |
|
281 ~~~~~ |
|
282 index |
|
283 ~~~~~ |
|
284 |
|
285 The *index* method returns the index position of the element in the list |
|
286 specified as argument:: |
|
287 |
|
288 >>> a = [1, 2, 3, ,4, 5] |
|
289 >>> a.index(4) |
|
290 3 |
|
291 |
|
292 |
|
293 ~~~~~~ |
|
294 insert |
|
295 ~~~~~~ |
|
296 |
|
297 The *insert* method is used to insert an element specified as the second |
|
298 argument to the list at the position specified by the first argument:: |
|
299 |
|
300 >>> a = ['Python', 'is', 'cool'] |
|
301 >>> a.insert(2, 'so') |
|
302 >>> a |
|
303 ['Python', 'is', 'so', 'cool'] |
|
304 |
|
305 The *insert* method changes the *List* in-place. |
|
306 |
|
307 |
|
308 ~~~ |
|
309 pop |
|
310 ~~~ |
|
311 |
|
312 The *pop* method removes an element from the list. The index position |
|
313 of the element to be removed can be specified as an argument to the |
|
314 *pop* method, if not it removes the last element by default:: |
|
315 |
|
316 >>> a = [1, 2, 3, 4, 5] |
|
317 >>> a.pop() |
|
318 >>> a |
|
319 5 |
|
320 >>> a.pop(2) |
|
321 >>> a |
|
322 3 |
|
323 |
|
324 The *pop* method changes the *List* in-place. |
|
325 |
|
326 |
|
327 ~~~~~~ |
|
328 remove |
|
329 ~~~~~~ |
|
330 |
|
331 The *remove* method removes the first occurence of an element supplied as a |
|
332 parameter:: |
|
333 |
|
334 >>> a = [1, 2, 3, 4, 2, 5, 2] |
|
335 >>> a.remove(2) |
|
336 >>> a |
|
337 [1, 3, 4, 2, 5, 2] |
|
338 |
|
339 |
|
340 ~~~~~~~ |
|
341 reverse |
|
342 ~~~~~~~ |
|
343 |
|
344 The *reverse* method reverses elements in the list. It is important to note |
|
345 here that *reverse* method changes the list in-place and doesn't return any |
|
346 thing:: |
|
347 |
|
348 >>> a = ['guido', 'alex', 'tim'] |
|
349 >>> a.reverse() |
|
350 >>> a |
|
351 ['tim', 'alex', 'guido'] |
|
352 |
|
353 |
|
354 ~~~~ |
|
355 sort |
|
356 ~~~~ |
|
357 |
|
358 The *sort* method is used to sort the elements of the list. The *sort* method |
|
359 also sorts in-place and does not return anything:: |
|
360 |
|
361 >>> a = [5, 1, 3, 7, 4] |
|
362 >>> a.sort() |
|
363 >>> a |
|
364 [1, 3, 4, 5, 7] |
|
365 |
|
366 In addition to the sort method on a *List* object we can also use the built-in |
|
367 **sorted** function. This function takes the *List* as a parameter and returns |
|
368 a sorted copy of the list. However the original list is left intact:: |
|
369 |
|
370 >>> a = [5, 1, 3, 7, 4] |
|
371 >>> b = sorted(a) |
|
372 >>> b |
|
373 [1, 3, 4, 5, 7] |
|
374 >>> a |
|
375 [5, 1, 3, 7, 4] |
|
376 |
|
377 |
|
378 Tuples |
|
379 ------ |
|
380 |
|
381 *Tuples* are sequences just like *Lists*, but they are immutable. In other |
|
382 words *Tuples* provides a way to represent a group of items, where the group |
|
383 of items cannot be changed in any way. The syntax of a *Tuple* is also very |
|
384 similar to *List*. A *Tuple* is represented with the list of items, called |
|
385 elements of the *Tuple* separated by comma, with the entire list being enclosed |
|
386 in parenthesis. It is not compulsory to use parenthesis around a *Tuple* but |
|
387 it may be necessary in some of the cases:: |
|
388 |
|
389 >>> a = 1, 2, 3 |
|
390 >>> a |
|
391 (1, 2, 3) |
|
392 >>> b = 1, |
|
393 >>> b |
|
394 (1,) |
|
395 |
|
396 It is interesting to note the second example. Just a value followed by a comma |
|
397 automatically makes that an element of a *Tuple* with only one element. It is |
|
398 also important to note that, irrespective of input having a parenthesis, the |
|
399 output always has a parenthesis. |
|
400 |
|
401 The first example is also known as *Tuple packing*, because values are being |
|
402 packed into a tuple. It is also possible to do *Tuple unpacking* which is more |
|
403 interesting. It is better to understand that by example. Say we have a |
|
404 co-ordinate pair from which we need to separate x and y co-ordinates:: |
|
405 |
|
406 >>> a = (1, 2) |
|
407 >>> x, y = a |
|
408 >>> x |
|
409 1 |
|
410 >>> y |
|
411 2 |
|
412 |
|
413 *Tuple unpacking* also has several other use-cases of which the most interesting |
|
414 one is to swap the values of two variables. Using programming languages like C |
|
415 would require anywhere around 10 lines of code and an extra temporary variable |
|
416 to do this (including all the #include stuff). Python does it in the most |
|
417 intuitive way in just one line. Say we want to swap the co-ordinates in the |
|
418 above example:: |
|
419 |
|
420 >>> x, y = y, x |
|
421 >>> x |
|
422 2 |
|
423 >>> y |
|
424 1 |
|
425 |
|
426 Common Tuple Operations |
|
427 ~~~~~~~~~~~~~~~~~~~~~~~ |
|
428 |
|
429 There is no need to introduce all the *Tuple* operations again, since *Tuples* |
|
430 support the following operations that *List* supports in exactly the same way: |
|
431 |
|
432 * Indexing |
|
433 * Concatenating |
|
434 * Slicing |
|
435 * Membership |
|
436 * Multiplication |
|
437 * Length, Maximum, Minimum |
|
438 |
|
439 The following examples illustrate the above operations:: |
|
440 |
|
441 >>> a = (1, 2, 3, 4, 5, 6) |
|
442 >>> a[5] |
|
443 6 |
|
444 >>> b = (7, 8, 9) |
|
445 >>> a + b |
|
446 (1, 2, 3, 4, 5, 6, 7, 8, 9) |
|
447 >>> a[3:5] |
|
448 (4, 5) |
|
449 >>> 5 in a |
|
450 True |
|
451 >>> c = (1,) |
|
452 >>> c * 5 |
|
453 (1, 1, 1, 1, 1) |
|
454 >>> len(a) |
|
455 6 |
|
456 >>> max(a) |
|
457 6 |
|
458 >>> min(a) |
|
459 1 |
|
460 |
|
461 However the following *List* operations are not supported by *Tuples* because |
|
462 *Tuples* cannot be changed once they are created: |
|
463 |
|
464 * Changing elements |
|
465 * Deleting elements |
|
466 * Assigning to slices |
|
467 |
|
468 Similarity to *Lists* leads to the questions like, why not *Lists* only? Why do |
|
469 we even want *Tuples*? Can we do the same with *Lists*? And the answer is **Yes** |
|
470 we can do it, but *Tuples* are helpful at times, like we can return Tuples from |
|
471 functions. They are also returned by some built-in functions and methods. And |
|
472 also there are some use cases like co-ordinate among other things. So *Tuples* |
|
473 are helpful. |
|
474 |
|
475 Additional Syntax |
|
476 ----------------- |
|
477 |
|
478 The following additional syntax are introduced to make it easier to operate on |
|
479 *Lists*. |
|
480 |
|
481 range() |
|
482 ~~~~~~~ |
|
483 |
|
484 The *range* function takes at least one argument and 2 additional optional |
|
485 arguments. If two or more arguments are specified, the range function returns |
|
486 a list of natural numbers starting from the first argument passed to it to the |
|
487 second argument. The third argument, if specified is used as a step. Suppose |
|
488 only one argument is specified, then *range* function returns a list of natural |
|
489 numbers starting from 0 upto the argument specified:: |
|
490 |
|
491 >>> range(5, 10, 2) |
|
492 [5, 7, 9] |
|
493 >>> range(2, 15) |
|
494 [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] |
|
495 >>> range(12) |
|
496 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] |
|
497 |
|
498 for |
|
499 ~~~ |
|
500 |
|
501 The **for** keyword is used as a part of the looping construct. Unlike for loops |
|
502 in other languages, Python's for is used to iterate through the elements of |
|
503 sequences like *Lists*, *Tuples*, *Dictionaries*, etc. The syntax of the for loop |
|
504 consists of **for**, followed by a variable to hold the individual or the current |
|
505 element of the list during iteration and **in**, followed by the sequence and a |
|
506 semicolon(':') The next line which is part of the **for** loop, i.e the statements |
|
507 that are part of the loop should start with a new intend:: |
|
508 |
|
509 >>> names = ['Guido', 'Alex', 'Tim'] |
|
510 >>> for name in names: |
|
511 ... print "Name =", name |
|
512 ... |
|
513 Name = Guido |
|
514 Name = Alex |
|
515 Name = Tim |
|
516 |
|
517 |
|
518 Conclusion |
|
519 ---------- |
|
520 |
|
521 This section on *Lists* and *Tuples* introduces almost all the necessary |
|
522 machinary required to work on *Lists* and *Tuples*. Topics like how to |
|
523 use these data structures in bigger more useful programs will be introduced |
|
524 in the subsequent chapters. |
|
525 |
|
526 |