blob: d65e55b1f57b6f69fb1c8bd4730936cad1185698 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001.. _tut-structures:
2
3***************
4Data Structures
5***************
6
7This chapter describes some things you've learned about already in more detail,
8and adds some new things as well.
9
10
11.. _tut-morelists:
12
13More on Lists
14=============
15
16The list data type has some more methods. Here are all of the methods of list
17objects:
18
19
20.. method:: list.append(x)
21
22 Add an item to the end of the list; equivalent to ``a[len(a):] = [x]``.
23
24
25.. method:: list.extend(L)
26
27 Extend the list by appending all the items in the given list; equivalent to
28 ``a[len(a):] = L``.
29
30
31.. method:: list.insert(i, x)
32
33 Insert an item at a given position. The first argument is the index of the
34 element before which to insert, so ``a.insert(0, x)`` inserts at the front of
35 the list, and ``a.insert(len(a), x)`` is equivalent to ``a.append(x)``.
36
37
38.. method:: list.remove(x)
39
40 Remove the first item from the list whose value is *x*. It is an error if there
41 is no such item.
42
43
44.. method:: list.pop([i])
45
46 Remove the item at the given position in the list, and return it. If no index
47 is specified, ``a.pop()`` removes and returns the last item in the list. (The
48 square brackets around the *i* in the method signature denote that the parameter
49 is optional, not that you should type square brackets at that position. You
50 will see this notation frequently in the Python Library Reference.)
51
52
53.. method:: list.index(x)
54
55 Return the index in the list of the first item whose value is *x*. It is an
56 error if there is no such item.
57
58
59.. method:: list.count(x)
60
61 Return the number of times *x* appears in the list.
62
63
64.. method:: list.sort()
65
66 Sort the items of the list, in place.
67
68
69.. method:: list.reverse()
70
71 Reverse the elements of the list, in place.
72
73An example that uses most of the list methods::
74
75 >>> a = [66.25, 333, 333, 1, 1234.5]
76 >>> print a.count(333), a.count(66.25), a.count('x')
77 2 1 0
78 >>> a.insert(2, -1)
79 >>> a.append(333)
80 >>> a
81 [66.25, 333, -1, 333, 1, 1234.5, 333]
82 >>> a.index(333)
83 1
84 >>> a.remove(333)
85 >>> a
86 [66.25, -1, 333, 1, 1234.5, 333]
87 >>> a.reverse()
88 >>> a
89 [333, 1234.5, 1, 333, -1, 66.25]
90 >>> a.sort()
91 >>> a
92 [-1, 1, 66.25, 333, 333, 1234.5]
93
94
95.. _tut-lists-as-stacks:
96
97Using Lists as Stacks
98---------------------
99
100.. sectionauthor:: Ka-Ping Yee <ping@lfw.org>
101
102
103The list methods make it very easy to use a list as a stack, where the last
104element added is the first element retrieved ("last-in, first-out"). To add an
105item to the top of the stack, use :meth:`append`. To retrieve an item from the
106top of the stack, use :meth:`pop` without an explicit index. For example::
107
108 >>> stack = [3, 4, 5]
109 >>> stack.append(6)
110 >>> stack.append(7)
111 >>> stack
112 [3, 4, 5, 6, 7]
113 >>> stack.pop()
114 7
115 >>> stack
116 [3, 4, 5, 6]
117 >>> stack.pop()
118 6
119 >>> stack.pop()
120 5
121 >>> stack
122 [3, 4]
123
124
125.. _tut-lists-as-queues:
126
127Using Lists as Queues
128---------------------
129
130.. sectionauthor:: Ka-Ping Yee <ping@lfw.org>
131
132
133You can also use a list conveniently as a queue, where the first element added
134is the first element retrieved ("first-in, first-out"). To add an item to the
135back of the queue, use :meth:`append`. To retrieve an item from the front of
136the queue, use :meth:`pop` with ``0`` as the index. For example::
137
138 >>> queue = ["Eric", "John", "Michael"]
139 >>> queue.append("Terry") # Terry arrives
140 >>> queue.append("Graham") # Graham arrives
141 >>> queue.pop(0)
142 'Eric'
143 >>> queue.pop(0)
144 'John'
145 >>> queue
146 ['Michael', 'Terry', 'Graham']
147
148
149.. _tut-functional:
150
151Functional Programming Tools
152----------------------------
153
154There are two built-in functions that are very useful when used with lists:
155:func:`filter` and :func:`map`.
156
157``filter(function, sequence)`` returns a sequence consisting of those items from
158the sequence for which ``function(item)`` is true. If *sequence* is a
159:class:`string` or :class:`tuple`, the result will be of the same type;
160otherwise, it is always a :class:`list`. For example, to compute some primes::
161
162 >>> def f(x): return x % 2 != 0 and x % 3 != 0
163 ...
164 >>> filter(f, range(2, 25))
165 [5, 7, 11, 13, 17, 19, 23]
166
167``map(function, sequence)`` calls ``function(item)`` for each of the sequence's
168items and returns a list of the return values. For example, to compute some
169cubes::
170
171 >>> def cube(x): return x*x*x
172 ...
173 >>> map(cube, range(1, 11))
174 [1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
175
176More than one sequence may be passed; the function must then have as many
177arguments as there are sequences and is called with the corresponding item from
178each sequence (or ``None`` if some sequence is shorter than another). For
179example::
180
181 >>> seq = range(8)
182 >>> def add(x, y): return x+y
183 ...
184 >>> map(add, seq, seq)
185 [0, 2, 4, 6, 8, 10, 12, 14]
186
187.. versionadded:: 2.3
188
189
190List Comprehensions
191-------------------
192
193List comprehensions provide a concise way to create lists without resorting to
194use of :func:`map`, :func:`filter` and/or :keyword:`lambda`. The resulting list
195definition tends often to be clearer than lists built using those constructs.
196Each list comprehension consists of an expression followed by a :keyword:`for`
197clause, then zero or more :keyword:`for` or :keyword:`if` clauses. The result
198will be a list resulting from evaluating the expression in the context of the
199:keyword:`for` and :keyword:`if` clauses which follow it. If the expression
200would evaluate to a tuple, it must be parenthesized. ::
201
202 >>> freshfruit = [' banana', ' loganberry ', 'passion fruit ']
203 >>> [weapon.strip() for weapon in freshfruit]
204 ['banana', 'loganberry', 'passion fruit']
205 >>> vec = [2, 4, 6]
206 >>> [3*x for x in vec]
207 [6, 12, 18]
208 >>> [3*x for x in vec if x > 3]
209 [12, 18]
210 >>> [3*x for x in vec if x < 2]
211 []
212 >>> [[x,x**2] for x in vec]
213 [[2, 4], [4, 16], [6, 36]]
214 >>> [x, x**2 for x in vec] # error - parens required for tuples
215 File "<stdin>", line 1, in ?
216 [x, x**2 for x in vec]
217 ^
218 SyntaxError: invalid syntax
219 >>> [(x, x**2) for x in vec]
220 [(2, 4), (4, 16), (6, 36)]
221 >>> vec1 = [2, 4, 6]
222 >>> vec2 = [4, 3, -9]
223 >>> [x*y for x in vec1 for y in vec2]
224 [8, 6, -18, 16, 12, -36, 24, 18, -54]
225 >>> [x+y for x in vec1 for y in vec2]
226 [6, 5, -7, 8, 7, -5, 10, 9, -3]
227 >>> [vec1[i]*vec2[i] for i in range(len(vec1))]
228 [8, 12, -54]
229
230List comprehensions are much more flexible than :func:`map` and can be applied
231to complex expressions and nested functions::
232
233 >>> [str(round(355/113.0, i)) for i in range(1,6)]
234 ['3.1', '3.14', '3.142', '3.1416', '3.14159']
235
236
237.. _tut-del:
238
239The :keyword:`del` statement
240============================
241
242There is a way to remove an item from a list given its index instead of its
243value: the :keyword:`del` statement. This differs from the :meth:`pop` method
244which returns a value. The :keyword:`del` statement can also be used to remove
245slices from a list or clear the entire list (which we did earlier by assignment
246of an empty list to the slice). For example::
247
248 >>> a = [-1, 1, 66.25, 333, 333, 1234.5]
249 >>> del a[0]
250 >>> a
251 [1, 66.25, 333, 333, 1234.5]
252 >>> del a[2:4]
253 >>> a
254 [1, 66.25, 1234.5]
255 >>> del a[:]
256 >>> a
257 []
258
259:keyword:`del` can also be used to delete entire variables::
260
261 >>> del a
262
263Referencing the name ``a`` hereafter is an error (at least until another value
264is assigned to it). We'll find other uses for :keyword:`del` later.
265
266
267.. _tut-tuples:
268
269Tuples and Sequences
270====================
271
272We saw that lists and strings have many common properties, such as indexing and
273slicing operations. They are two examples of *sequence* data types (see
274:ref:`typesseq`). Since Python is an evolving language, other sequence data
275types may be added. There is also another standard sequence data type: the
276*tuple*.
277
278A tuple consists of a number of values separated by commas, for instance::
279
280 >>> t = 12345, 54321, 'hello!'
281 >>> t[0]
282 12345
283 >>> t
284 (12345, 54321, 'hello!')
285 >>> # Tuples may be nested:
286 ... u = t, (1, 2, 3, 4, 5)
287 >>> u
288 ((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))
289
290As you see, on output tuples are always enclosed in parentheses, so that nested
291tuples are interpreted correctly; they may be input with or without surrounding
292parentheses, although often parentheses are necessary anyway (if the tuple is
293part of a larger expression).
294
295Tuples have many uses. For example: (x, y) coordinate pairs, employee records
296from a database, etc. Tuples, like strings, are immutable: it is not possible
297to assign to the individual items of a tuple (you can simulate much of the same
298effect with slicing and concatenation, though). It is also possible to create
299tuples which contain mutable objects, such as lists.
300
301A special problem is the construction of tuples containing 0 or 1 items: the
302syntax has some extra quirks to accommodate these. Empty tuples are constructed
303by an empty pair of parentheses; a tuple with one item is constructed by
304following a value with a comma (it is not sufficient to enclose a single value
305in parentheses). Ugly, but effective. For example::
306
307 >>> empty = ()
308 >>> singleton = 'hello', # <-- note trailing comma
309 >>> len(empty)
310 0
311 >>> len(singleton)
312 1
313 >>> singleton
314 ('hello',)
315
316The statement ``t = 12345, 54321, 'hello!'`` is an example of *tuple packing*:
317the values ``12345``, ``54321`` and ``'hello!'`` are packed together in a tuple.
318The reverse operation is also possible::
319
320 >>> x, y, z = t
321
322This is called, appropriately enough, *sequence unpacking*. Sequence unpacking
323requires the list of variables on the left to have the same number of elements
324as the length of the sequence. Note that multiple assignment is really just a
325combination of tuple packing and sequence unpacking!
326
327There is a small bit of asymmetry here: packing multiple values always creates
328a tuple, and unpacking works for any sequence.
329
330.. % XXX Add a bit on the difference between tuples and lists.
331
332
333.. _tut-sets:
334
335Sets
336====
337
338Python also includes a data type for *sets*. A set is an unordered collection
339with no duplicate elements. Basic uses include membership testing and
340eliminating duplicate entries. Set objects also support mathematical operations
341like union, intersection, difference, and symmetric difference.
342
343Here is a brief demonstration::
344
345 >>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
346 >>> fruit = set(basket) # create a set without duplicates
347 >>> fruit
348 set(['orange', 'pear', 'apple', 'banana'])
349 >>> 'orange' in fruit # fast membership testing
350 True
351 >>> 'crabgrass' in fruit
352 False
353
354 >>> # Demonstrate set operations on unique letters from two words
355 ...
356 >>> a = set('abracadabra')
357 >>> b = set('alacazam')
358 >>> a # unique letters in a
359 set(['a', 'r', 'b', 'c', 'd'])
360 >>> a - b # letters in a but not in b
361 set(['r', 'd', 'b'])
362 >>> a | b # letters in either a or b
363 set(['a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'])
364 >>> a & b # letters in both a and b
365 set(['a', 'c'])
366 >>> a ^ b # letters in a or b but not both
367 set(['r', 'd', 'b', 'm', 'z', 'l'])
368
369
370.. _tut-dictionaries:
371
372Dictionaries
373============
374
375Another useful data type built into Python is the *dictionary* (see
376:ref:`typesmapping`). Dictionaries are sometimes found in other languages as
377"associative memories" or "associative arrays". Unlike sequences, which are
378indexed by a range of numbers, dictionaries are indexed by *keys*, which can be
379any immutable type; strings and numbers can always be keys. Tuples can be used
380as keys if they contain only strings, numbers, or tuples; if a tuple contains
381any mutable object either directly or indirectly, it cannot be used as a key.
382You can't use lists as keys, since lists can be modified in place using index
383assignments, slice assignments, or methods like :meth:`append` and
384:meth:`extend`.
385
386It is best to think of a dictionary as an unordered set of *key: value* pairs,
387with the requirement that the keys are unique (within one dictionary). A pair of
388braces creates an empty dictionary: ``{}``. Placing a comma-separated list of
389key:value pairs within the braces adds initial key:value pairs to the
390dictionary; this is also the way dictionaries are written on output.
391
392The main operations on a dictionary are storing a value with some key and
393extracting the value given the key. It is also possible to delete a key:value
394pair with ``del``. If you store using a key that is already in use, the old
395value associated with that key is forgotten. It is an error to extract a value
396using a non-existent key.
397
398The :meth:`keys` method of a dictionary object returns a list of all the keys
399used in the dictionary, in arbitrary order (if you want it sorted, just apply
400the :meth:`sort` method to the list of keys). To check whether a single key is
401in the dictionary, either use the dictionary's :meth:`has_key` method or the
402:keyword:`in` keyword.
403
404Here is a small example using a dictionary::
405
406 >>> tel = {'jack': 4098, 'sape': 4139}
407 >>> tel['guido'] = 4127
408 >>> tel
409 {'sape': 4139, 'guido': 4127, 'jack': 4098}
410 >>> tel['jack']
411 4098
412 >>> del tel['sape']
413 >>> tel['irv'] = 4127
414 >>> tel
415 {'guido': 4127, 'irv': 4127, 'jack': 4098}
416 >>> tel.keys()
417 ['guido', 'irv', 'jack']
418 >>> tel.has_key('guido')
419 True
420 >>> 'guido' in tel
421 True
422
423The :func:`dict` constructor builds dictionaries directly from lists of
424key-value pairs stored as tuples. When the pairs form a pattern, list
425comprehensions can compactly specify the key-value list. ::
426
427 >>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
428 {'sape': 4139, 'jack': 4098, 'guido': 4127}
429 >>> dict([(x, x**2) for x in (2, 4, 6)]) # use a list comprehension
430 {2: 4, 4: 16, 6: 36}
431
432Later in the tutorial, we will learn about Generator Expressions which are even
433better suited for the task of supplying key-values pairs to the :func:`dict`
434constructor.
435
436When the keys are simple strings, it is sometimes easier to specify pairs using
437keyword arguments::
438
439 >>> dict(sape=4139, guido=4127, jack=4098)
440 {'sape': 4139, 'jack': 4098, 'guido': 4127}
441
442
443.. _tut-loopidioms:
444
445Looping Techniques
446==================
447
448When looping through dictionaries, the key and corresponding value can be
449retrieved at the same time using the :meth:`iteritems` method. ::
450
451 >>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
452 >>> for k, v in knights.iteritems():
453 ... print k, v
454 ...
455 gallahad the pure
456 robin the brave
457
458When looping through a sequence, the position index and corresponding value can
459be retrieved at the same time using the :func:`enumerate` function. ::
460
461 >>> for i, v in enumerate(['tic', 'tac', 'toe']):
462 ... print i, v
463 ...
464 0 tic
465 1 tac
466 2 toe
467
468To loop over two or more sequences at the same time, the entries can be paired
469with the :func:`zip` function. ::
470
471 >>> questions = ['name', 'quest', 'favorite color']
472 >>> answers = ['lancelot', 'the holy grail', 'blue']
473 >>> for q, a in zip(questions, answers):
474 ... print 'What is your %s? It is %s.' % (q, a)
475 ...
476 What is your name? It is lancelot.
477 What is your quest? It is the holy grail.
478 What is your favorite color? It is blue.
479
480To loop over a sequence in reverse, first specify the sequence in a forward
481direction and then call the :func:`reversed` function. ::
482
483 >>> for i in reversed(range(1,10,2)):
484 ... print i
485 ...
486 9
487 7
488 5
489 3
490 1
491
492To loop over a sequence in sorted order, use the :func:`sorted` function which
493returns a new sorted list while leaving the source unaltered. ::
494
495 >>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
496 >>> for f in sorted(set(basket)):
497 ... print f
498 ...
499 apple
500 banana
501 orange
502 pear
503
504
505.. _tut-conditions:
506
507More on Conditions
508==================
509
510The conditions used in ``while`` and ``if`` statements can contain any
511operators, not just comparisons.
512
513The comparison operators ``in`` and ``not in`` check whether a value occurs
514(does not occur) in a sequence. The operators ``is`` and ``is not`` compare
515whether two objects are really the same object; this only matters for mutable
516objects like lists. All comparison operators have the same priority, which is
517lower than that of all numerical operators.
518
519Comparisons can be chained. For example, ``a < b == c`` tests whether ``a`` is
520less than ``b`` and moreover ``b`` equals ``c``.
521
522Comparisons may be combined using the Boolean operators ``and`` and ``or``, and
523the outcome of a comparison (or of any other Boolean expression) may be negated
524with ``not``. These have lower priorities than comparison operators; between
525them, ``not`` has the highest priority and ``or`` the lowest, so that ``A and
526not B or C`` is equivalent to ``(A and (not B)) or C``. As always, parentheses
527can be used to express the desired composition.
528
529The Boolean operators ``and`` and ``or`` are so-called *short-circuit*
530operators: their arguments are evaluated from left to right, and evaluation
531stops as soon as the outcome is determined. For example, if ``A`` and ``C`` are
532true but ``B`` is false, ``A and B and C`` does not evaluate the expression
533``C``. When used as a general value and not as a Boolean, the return value of a
534short-circuit operator is the last evaluated argument.
535
536It is possible to assign the result of a comparison or other Boolean expression
537to a variable. For example, ::
538
539 >>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance'
540 >>> non_null = string1 or string2 or string3
541 >>> non_null
542 'Trondheim'
543
544Note that in Python, unlike C, assignment cannot occur inside expressions. C
545programmers may grumble about this, but it avoids a common class of problems
546encountered in C programs: typing ``=`` in an expression when ``==`` was
547intended.
548
549
550.. _tut-comparing:
551
552Comparing Sequences and Other Types
553===================================
554
555Sequence objects may be compared to other objects with the same sequence type.
556The comparison uses *lexicographical* ordering: first the first two items are
557compared, and if they differ this determines the outcome of the comparison; if
558they are equal, the next two items are compared, and so on, until either
559sequence is exhausted. If two items to be compared are themselves sequences of
560the same type, the lexicographical comparison is carried out recursively. If
561all items of two sequences compare equal, the sequences are considered equal.
562If one sequence is an initial sub-sequence of the other, the shorter sequence is
563the smaller (lesser) one. Lexicographical ordering for strings uses the ASCII
564ordering for individual characters. Some examples of comparisons between
565sequences of the same type::
566
567 (1, 2, 3) < (1, 2, 4)
568 [1, 2, 3] < [1, 2, 4]
569 'ABC' < 'C' < 'Pascal' < 'Python'
570 (1, 2, 3, 4) < (1, 2, 4)
571 (1, 2) < (1, 2, -1)
572 (1, 2, 3) == (1.0, 2.0, 3.0)
573 (1, 2, ('aa', 'ab')) < (1, 2, ('abc', 'a'), 4)
574
575Note that comparing objects of different types is legal. The outcome is
576deterministic but arbitrary: the types are ordered by their name. Thus, a list
577is always smaller than a string, a string is always smaller than a tuple, etc.
578[#]_ Mixed numeric types are compared according to their numeric value, so 0
579equals 0.0, etc.
580
581
582.. rubric:: Footnotes
583
584.. [#] The rules for comparing objects of different types should not be relied upon;
585 they may change in a future version of the language.
586