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