rest25/tutorial/datastructures.rst => rest262/tutorial/datastructures.rst
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)
n21+   :noindex:
21
22   Add an item to the end of the list; equivalent to ``a[len(a):] = [x]``.
23
24
25.. method:: list.extend(L)
n27+   :noindex:
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)
n34+   :noindex:
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)
n42+   :noindex:
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])
n49+   :noindex:
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
n50-   will see this notation frequently in the Python Library Reference (XXX
n55+   will see this notation frequently in the Python Library Reference.)
51-   reference: ../lib/lib.html).)
52
53
54.. method:: list.index(x)
n59+   :noindex:
55
56   Return the index in the list of the first item whose value is *x*. It is an
57   error if there is no such item.
58
59
60.. method:: list.count(x)
n66+   :noindex:
61
62   Return the number of times *x* appears in the list.
63
64
65.. method:: list.sort()
n72+   :noindex:
66
67   Sort the items of the list, in place.
68
69
70.. method:: list.reverse()
n78+   :noindex:
71
72   Reverse the elements of the list, in place.
73
74An example that uses most of the list methods::
75
76   >>> a = [66.25, 333, 333, 1, 1234.5]
77   >>> print a.count(333), a.count(66.25), a.count('x')
78   2 1 0
201A third argument can be passed to indicate the starting value.  In this case the
202starting value is returned for an empty sequence, and the function is first
203applied to the starting value and the first sequence item, then to the result
204and the next item, and so on.  For example, ::
205
206   >>> def sum(seq):
207   ...     def add(x,y): return x+y
208   ...     return reduce(add, seq, 0)
n209-   ... 
n217+   ...
210   >>> sum(range(1, 11))
211   55
212   >>> sum([])
213   0
214
215Don't use this example's definition of :func:`sum`: since summing numbers is
216such a common need, a built-in function ``sum(sequence)`` is already provided,
217and works exactly like this.
238   >>> [3*x for x in vec]
239   [6, 12, 18]
240   >>> [3*x for x in vec if x > 3]
241   [12, 18]
242   >>> [3*x for x in vec if x < 2]
243   []
244   >>> [[x,x**2] for x in vec]
245   [[2, 4], [4, 16], [6, 36]]
n246-   >>> [x, x**2 for x in vec]   # error - parens required for tuples
n254+   >>> [x, x**2 for x in vec]  # error - parens required for tuples
247     File "<stdin>", line 1, in ?
248       [x, x**2 for x in vec]
249                  ^
250   SyntaxError: invalid syntax
251   >>> [(x, x**2) for x in vec]
252   [(2, 4), (4, 16), (6, 36)]
253   >>> vec1 = [2, 4, 6]
254   >>> vec2 = [4, 3, -9]
261
262List comprehensions are much more flexible than :func:`map` and can be applied
263to complex expressions and nested functions::
264
265   >>> [str(round(355/113.0, i)) for i in range(1,6)]
266   ['3.1', '3.14', '3.142', '3.1416', '3.14159']
267
268
n277+Nested List Comprehensions
278+--------------------------
279+ 
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.
283+ 
284+Consider the following example of a 3x3 matrix held as a list containing three
285+lists, one list per row::
286+ 
287+    >>> mat = [
288+    ...        [1, 2, 3],
289+    ...        [4, 5, 6],
290+    ...        [7, 8, 9],
291+    ...       ]
292+ 
293+Now, if you wanted to swap rows and columns, you could use a list
294+comprehension::
295+ 
296+    >>> print [[row[i] for row in mat] for i in [0, 1, 2]]
297+    [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
298+ 
299+Special care has to be taken for the *nested* list comprehension:
300+ 
301+    To avoid apprehension when nesting list comprehensions, read from right to
302+    left.
303+ 
304+A more verbose version of this snippet shows the flow explicitly::
305+ 
306+    for i in [0, 1, 2]:
307+        for row in mat:
308+            print row[i],
309+        print
310+ 
311+In real world, you should prefer builtin functions to complex flow statements.
312+The :func:`zip` function would do a great job for this use case::
313+ 
314+    >>> zip(*mat)
315+    [(1, 4, 7), (2, 5, 8), (3, 6, 9)]
316+ 
317+See :ref:`tut-unpacking-arguments` for details on the asterisk in this line.
318+ 
269.. _tut-del:
270
271The :keyword:`del` statement
272============================
273
274There is a way to remove an item from a list given its index instead of its
n275-value: the :keyword:`del` statement.  This differs from the :meth:`pop`) method
n325+value: the :keyword:`del` statement.  This differs from the :meth:`pop` method
276which returns a value.  The :keyword:`del` statement can also be used to remove
277slices from a list or clear the entire list (which we did earlier by assignment
278of an empty list to the slice).  For example::
279
280   >>> a = [-1, 1, 66.25, 333, 333, 1234.5]
281   >>> del a[0]
282   >>> a
283   [1, 66.25, 333, 333, 1234.5]
297
298
299.. _tut-tuples:
300
301Tuples and Sequences
302====================
303
304We saw that lists and strings have many common properties, such as indexing and
n305-slicing operations.  They are two examples of *sequence* data types (XXX
n355+slicing operations.  They are two examples of *sequence* data types (see
306-reference: ../lib/typesseq.html).  Since Python is an evolving language, other
356+:ref:`typesseq`).  Since Python is an evolving language, other sequence data
307-sequence data types may be added.  There is also another standard sequence data
357+types may be added.  There is also another standard sequence data type: the
308-type: the *tuple*.
358+*tuple*.
309
310A tuple consists of a number of values separated by commas, for instance::
311
312   >>> t = 12345, 54321, 'hello!'
313   >>> t[0]
314   12345
315   >>> t
316   (12345, 54321, 'hello!')
346   ('hello',)
347
348The statement ``t = 12345, 54321, 'hello!'`` is an example of *tuple packing*:
349the values ``12345``, ``54321`` and ``'hello!'`` are packed together in a tuple.
350The reverse operation is also possible::
351
352   >>> x, y, z = t
353
n354-This is called, appropriately enough, *sequence unpacking*. Sequence unpacking
n404+This is called, appropriately enough, *sequence unpacking* and works for any
355-requires the list of variables on the left to have the same number of elements
405+sequence on the right-hand side.  Sequence unpacking requires the list of
356-as the length of the sequence.  Note that multiple assignment is really just a
406+variables on the left to have the same number of elements as the length of the
357-combination of tuple packing and sequence unpacking!
407+sequence.  Note that multiple assignment is really just a combination of tuple
408+packing and sequence unpacking.
358
n359-There is a small bit of asymmetry here:  packing multiple values always creates
360-a tuple, and unpacking works for any sequence.
361- 
362-.. % XXX Add a bit on the difference between tuples and lists.
410+.. XXX Add a bit on the difference between tuples and lists.
363
364
365.. _tut-sets:
366
367Sets
368====
369
370Python also includes a data type for *sets*.  A set is an unordered collection
399   set(['r', 'd', 'b', 'm', 'z', 'l'])
400
401
402.. _tut-dictionaries:
403
404Dictionaries
405============
406
n407-Another useful data type built into Python is the *dictionary* (XXX reference:
n455+Another useful data type built into Python is the *dictionary* (see
408-../lib/typesmapping.html). Dictionaries are sometimes found in other languages
456+:ref:`typesmapping`). Dictionaries are sometimes found in other languages as
409-as "associative memories" or "associative arrays".  Unlike sequences, which are
457+"associative memories" or "associative arrays".  Unlike sequences, which are
410indexed by a range of numbers, dictionaries are indexed by *keys*, which can be
411any immutable type; strings and numbers can always be keys.  Tuples can be used
412as keys if they contain only strings, numbers, or tuples; if a tuple contains
413any mutable object either directly or indirectly, it cannot be used as a key.
414You can't use lists as keys, since lists can be modified in place using index
415assignments, slice assignments, or methods like :meth:`append` and
416:meth:`extend`.
417
425extracting the value given the key.  It is also possible to delete a key:value
426pair with ``del``. If you store using a key that is already in use, the old
427value associated with that key is forgotten.  It is an error to extract a value
428using a non-existent key.
429
430The :meth:`keys` method of a dictionary object returns a list of all the keys
431used in the dictionary, in arbitrary order (if you want it sorted, just apply
432the :meth:`sort` method to the list of keys).  To check whether a single key is
n433-in the dictionary, either use the dictionary's :meth:`has_key` method or the
n481+in the dictionary, use the :keyword:`in` keyword.
434-:keyword:`in` keyword.
435
436Here is a small example using a dictionary::
437
438   >>> tel = {'jack': 4098, 'sape': 4139}
439   >>> tel['guido'] = 4127
440   >>> tel
441   {'sape': 4139, 'guido': 4127, 'jack': 4098}
442   >>> tel['jack']
443   4098
444   >>> del tel['sape']
445   >>> tel['irv'] = 4127
446   >>> tel
447   {'guido': 4127, 'irv': 4127, 'jack': 4098}
448   >>> tel.keys()
449   ['guido', 'irv', 'jack']
n450-   >>> tel.has_key('guido')
451-   True
452   >>> 'guido' in tel
453   True
454
n455-The :func:`dict` constructor builds dictionaries directly from lists of key-
n500+The :func:`dict` constructor builds dictionaries directly from lists of
456-value pairs stored as tuples.  When the pairs form a pattern, list
501+key-value pairs stored as tuples.  When the pairs form a pattern, list
457comprehensions can compactly specify the key-value list. ::
458
459   >>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
460   {'sape': 4139, 'jack': 4098, 'guido': 4127}
461   >>> dict([(x, x**2) for x in (2, 4, 6)])     # use a list comprehension
462   {2: 4, 4: 16, 6: 36}
463
464Later in the tutorial, we will learn about Generator Expressions which are even
498   2 toe
499
500To loop over two or more sequences at the same time, the entries can be paired
501with the :func:`zip` function. ::
502
503   >>> questions = ['name', 'quest', 'favorite color']
504   >>> answers = ['lancelot', 'the holy grail', 'blue']
505   >>> for q, a in zip(questions, answers):
n506-   ...     print 'What is your %s?  It is %s.' % (q, a)
n551+   ...     print 'What is your {0}?  It is {1}.'.format(q, a)
507-   ...  
552+   ...
508   What is your name?  It is lancelot.
509   What is your quest?  It is the holy grail.
510   What is your favorite color?  It is blue.
511
512To loop over a sequence in reverse, first specify the sequence in a forward
513direction and then call the :func:`reversed` function. ::
514
515   >>> for i in reversed(xrange(1,10,2)):
522   1
523
524To loop over a sequence in sorted order, use the :func:`sorted` function which
525returns a new sorted list while leaving the source unaltered. ::
526
527   >>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
528   >>> for f in sorted(set(basket)):
529   ...     print f
t530-   ...  
t575+   ...
531   apple
532   banana
533   orange
534   pear
535
536
537.. _tut-conditions:
538
Legends
Colors
 Added 
Changed
Deleted
Links
(f)irst change
(n)ext change
(t)op