Home | History | Annotate | Download | only in tutorial
      1 .. _tut-structures:
      2 
      3 ***************
      4 Data Structures
      5 ***************
      6 
      7 This chapter describes some things you've learned about already in more detail,
      8 and adds some new things as well.
      9 
     10 .. _tut-morelists:
     11 
     12 More on Lists
     13 =============
     14 
     15 The list data type has some more methods.  Here are all of the methods of list
     16 objects:
     17 
     18 
     19 .. method:: list.append(x)
     20    :noindex:
     21 
     22    Add an item to the end of the list.  Equivalent to ``a[len(a):] = [x]``.
     23 
     24 
     25 .. method:: list.extend(iterable)
     26    :noindex:
     27 
     28    Extend the list by appending all the items from the iterable.  Equivalent to
     29    ``a[len(a):] = iterable``.
     30 
     31 
     32 .. method:: list.insert(i, x)
     33    :noindex:
     34 
     35    Insert an item at a given position.  The first argument is the index of the
     36    element before which to insert, so ``a.insert(0, x)`` inserts at the front of
     37    the list, and ``a.insert(len(a), x)`` is equivalent to ``a.append(x)``.
     38 
     39 
     40 .. method:: list.remove(x)
     41    :noindex:
     42 
     43    Remove the first item from the list whose value is *x*.  It is an error if
     44    there is no such item.
     45 
     46 
     47 .. method:: list.pop([i])
     48    :noindex:
     49 
     50    Remove the item at the given position in the list, and return it.  If no index
     51    is specified, ``a.pop()`` removes and returns the last item in the list.  (The
     52    square brackets around the *i* in the method signature denote that the parameter
     53    is optional, not that you should type square brackets at that position.  You
     54    will see this notation frequently in the Python Library Reference.)
     55 
     56 
     57 .. method:: list.clear()
     58    :noindex:
     59 
     60    Remove all items from the list.  Equivalent to ``del a[:]``.
     61 
     62 
     63 .. method:: list.index(x[, start[, end]])
     64    :noindex:
     65 
     66    Return zero-based index in the list of the first item whose value is *x*.
     67    Raises a :exc:`ValueError` if there is no such item.
     68 
     69    The optional arguments *start* and *end* are interpreted as in the slice
     70    notation and are used to limit the search to a particular subsequence of
     71    the list.  The returned index is computed relative to the beginning of the full
     72    sequence rather than the *start* argument.
     73 
     74 
     75 .. method:: list.count(x)
     76    :noindex:
     77 
     78    Return the number of times *x* appears in the list.
     79 
     80 
     81 .. method:: list.sort(key=None, reverse=False)
     82    :noindex:
     83 
     84    Sort the items of the list in place (the arguments can be used for sort
     85    customization, see :func:`sorted` for their explanation).
     86 
     87 
     88 .. method:: list.reverse()
     89    :noindex:
     90 
     91    Reverse the elements of the list in place.
     92 
     93 
     94 .. method:: list.copy()
     95    :noindex:
     96 
     97    Return a shallow copy of the list.  Equivalent to ``a[:]``.
     98 
     99 
    100 An example that uses most of the list methods::
    101 
    102     >>> fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']
    103     >>> fruits.count('apple')
    104     2
    105     >>> fruits.count('tangerine')
    106     0
    107     >>> fruits.index('banana')
    108     3
    109     >>> fruits.index('banana', 4)  # Find next banana starting a position 4
    110     6
    111     >>> fruits.reverse()
    112     >>> fruits
    113     ['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange']
    114     >>> fruits.append('grape')
    115     >>> fruits
    116     ['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange', 'grape']
    117     >>> fruits.sort()
    118     >>> fruits
    119     ['apple', 'apple', 'banana', 'banana', 'grape', 'kiwi', 'orange', 'pear']
    120     >>> fruits.pop()
    121     'pear'
    122 
    123 You might have noticed that methods like ``insert``, ``remove`` or ``sort`` that
    124 only modify the list have no return value printed -- they return the default
    125 ``None``. [1]_  This is a design principle for all mutable data structures in
    126 Python.
    127 
    128 
    129 .. _tut-lists-as-stacks:
    130 
    131 Using Lists as Stacks
    132 ---------------------
    133 
    134 .. sectionauthor:: Ka-Ping Yee <ping (a] lfw.org>
    135 
    136 
    137 The list methods make it very easy to use a list as a stack, where the last
    138 element added is the first element retrieved ("last-in, first-out").  To add an
    139 item to the top of the stack, use :meth:`append`.  To retrieve an item from the
    140 top of the stack, use :meth:`pop` without an explicit index.  For example::
    141 
    142    >>> stack = [3, 4, 5]
    143    >>> stack.append(6)
    144    >>> stack.append(7)
    145    >>> stack
    146    [3, 4, 5, 6, 7]
    147    >>> stack.pop()
    148    7
    149    >>> stack
    150    [3, 4, 5, 6]
    151    >>> stack.pop()
    152    6
    153    >>> stack.pop()
    154    5
    155    >>> stack
    156    [3, 4]
    157 
    158 
    159 .. _tut-lists-as-queues:
    160 
    161 Using Lists as Queues
    162 ---------------------
    163 
    164 .. sectionauthor:: Ka-Ping Yee <ping (a] lfw.org>
    165 
    166 It is also possible to use a list as a queue, where the first element added is
    167 the first element retrieved ("first-in, first-out"); however, lists are not
    168 efficient for this purpose.  While appends and pops from the end of list are
    169 fast, doing inserts or pops from the beginning of a list is slow (because all
    170 of the other elements have to be shifted by one).
    171 
    172 To implement a queue, use :class:`collections.deque` which was designed to
    173 have fast appends and pops from both ends.  For example::
    174 
    175    >>> from collections import deque
    176    >>> queue = deque(["Eric", "John", "Michael"])
    177    >>> queue.append("Terry")           # Terry arrives
    178    >>> queue.append("Graham")          # Graham arrives
    179    >>> queue.popleft()                 # The first to arrive now leaves
    180    'Eric'
    181    >>> queue.popleft()                 # The second to arrive now leaves
    182    'John'
    183    >>> queue                           # Remaining queue in order of arrival
    184    deque(['Michael', 'Terry', 'Graham'])
    185 
    186 
    187 .. _tut-listcomps:
    188 
    189 List Comprehensions
    190 -------------------
    191 
    192 List comprehensions provide a concise way to create lists.
    193 Common applications are to make new lists where each element is the result of
    194 some operations applied to each member of another sequence or iterable, or to
    195 create a subsequence of those elements that satisfy a certain condition.
    196 
    197 For example, assume we want to create a list of squares, like::
    198 
    199    >>> squares = []
    200    >>> for x in range(10):
    201    ...     squares.append(x**2)
    202    ...
    203    >>> squares
    204    [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
    205 
    206 Note that this creates (or overwrites) a variable named ``x`` that still exists
    207 after the loop completes.  We can calculate the list of squares without any
    208 side effects using::
    209 
    210    squares = list(map(lambda x: x**2, range(10)))
    211 
    212 or, equivalently::
    213 
    214    squares = [x**2 for x in range(10)]
    215 
    216 which is more concise and readable.
    217 
    218 A list comprehension consists of brackets containing an expression followed
    219 by a :keyword:`for` clause, then zero or more :keyword:`for` or :keyword:`if`
    220 clauses.  The result will be a new list resulting from evaluating the expression
    221 in the context of the :keyword:`for` and :keyword:`if` clauses which follow it.
    222 For example, this listcomp combines the elements of two lists if they are not
    223 equal::
    224 
    225    >>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
    226    [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
    227 
    228 and it's equivalent to::
    229 
    230    >>> combs = []
    231    >>> for x in [1,2,3]:
    232    ...     for y in [3,1,4]:
    233    ...         if x != y:
    234    ...             combs.append((x, y))
    235    ...
    236    >>> combs
    237    [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
    238 
    239 Note how the order of the :keyword:`for` and :keyword:`if` statements is the
    240 same in both these snippets.
    241 
    242 If the expression is a tuple (e.g. the ``(x, y)`` in the previous example),
    243 it must be parenthesized. ::
    244 
    245    >>> vec = [-4, -2, 0, 2, 4]
    246    >>> # create a new list with the values doubled
    247    >>> [x*2 for x in vec]
    248    [-8, -4, 0, 4, 8]
    249    >>> # filter the list to exclude negative numbers
    250    >>> [x for x in vec if x >= 0]
    251    [0, 2, 4]
    252    >>> # apply a function to all the elements
    253    >>> [abs(x) for x in vec]
    254    [4, 2, 0, 2, 4]
    255    >>> # call a method on each element
    256    >>> freshfruit = ['  banana', '  loganberry ', 'passion fruit  ']
    257    >>> [weapon.strip() for weapon in freshfruit]
    258    ['banana', 'loganberry', 'passion fruit']
    259    >>> # create a list of 2-tuples like (number, square)
    260    >>> [(x, x**2) for x in range(6)]
    261    [(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]
    262    >>> # the tuple must be parenthesized, otherwise an error is raised
    263    >>> [x, x**2 for x in range(6)]
    264      File "<stdin>", line 1, in ?
    265        [x, x**2 for x in range(6)]
    266                   ^
    267    SyntaxError: invalid syntax
    268    >>> # flatten a list using a listcomp with two 'for'
    269    >>> vec = [[1,2,3], [4,5,6], [7,8,9]]
    270    >>> [num for elem in vec for num in elem]
    271    [1, 2, 3, 4, 5, 6, 7, 8, 9]
    272 
    273 List comprehensions can contain complex expressions and nested functions::
    274 
    275    >>> from math import pi
    276    >>> [str(round(pi, i)) for i in range(1, 6)]
    277    ['3.1', '3.14', '3.142', '3.1416', '3.14159']
    278 
    279 Nested List Comprehensions
    280 --------------------------
    281 
    282 The initial expression in a list comprehension can be any arbitrary expression,
    283 including another list comprehension.
    284 
    285 Consider the following example of a 3x4 matrix implemented as a list of
    286 3 lists of length 4::
    287 
    288    >>> matrix = [
    289    ...     [1, 2, 3, 4],
    290    ...     [5, 6, 7, 8],
    291    ...     [9, 10, 11, 12],
    292    ... ]
    293 
    294 The following list comprehension will transpose rows and columns::
    295 
    296    >>> [[row[i] for row in matrix] for i in range(4)]
    297    [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
    298 
    299 As we saw in the previous section, the nested listcomp is evaluated in
    300 the context of the :keyword:`for` that follows it, so this example is
    301 equivalent to::
    302 
    303    >>> transposed = []
    304    >>> for i in range(4):
    305    ...     transposed.append([row[i] for row in matrix])
    306    ...
    307    >>> transposed
    308    [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
    309 
    310 which, in turn, is the same as::
    311 
    312    >>> transposed = []
    313    >>> for i in range(4):
    314    ...     # the following 3 lines implement the nested listcomp
    315    ...     transposed_row = []
    316    ...     for row in matrix:
    317    ...         transposed_row.append(row[i])
    318    ...     transposed.append(transposed_row)
    319    ...
    320    >>> transposed
    321    [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
    322 
    323 In the real world, you should prefer built-in functions to complex flow statements.
    324 The :func:`zip` function would do a great job for this use case::
    325 
    326    >>> list(zip(*matrix))
    327    [(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]
    328 
    329 See :ref:`tut-unpacking-arguments` for details on the asterisk in this line.
    330 
    331 .. _tut-del:
    332 
    333 The :keyword:`del` statement
    334 ============================
    335 
    336 There is a way to remove an item from a list given its index instead of its
    337 value: the :keyword:`del` statement.  This differs from the :meth:`pop` method
    338 which returns a value.  The :keyword:`del` statement can also be used to remove
    339 slices from a list or clear the entire list (which we did earlier by assignment
    340 of an empty list to the slice).  For example::
    341 
    342    >>> a = [-1, 1, 66.25, 333, 333, 1234.5]
    343    >>> del a[0]
    344    >>> a
    345    [1, 66.25, 333, 333, 1234.5]
    346    >>> del a[2:4]
    347    >>> a
    348    [1, 66.25, 1234.5]
    349    >>> del a[:]
    350    >>> a
    351    []
    352 
    353 :keyword:`del` can also be used to delete entire variables::
    354 
    355    >>> del a
    356 
    357 Referencing the name ``a`` hereafter is an error (at least until another value
    358 is assigned to it).  We'll find other uses for :keyword:`del` later.
    359 
    360 
    361 .. _tut-tuples:
    362 
    363 Tuples and Sequences
    364 ====================
    365 
    366 We saw that lists and strings have many common properties, such as indexing and
    367 slicing operations.  They are two examples of *sequence* data types (see
    368 :ref:`typesseq`).  Since Python is an evolving language, other sequence data
    369 types may be added.  There is also another standard sequence data type: the
    370 *tuple*.
    371 
    372 A tuple consists of a number of values separated by commas, for instance::
    373 
    374    >>> t = 12345, 54321, 'hello!'
    375    >>> t[0]
    376    12345
    377    >>> t
    378    (12345, 54321, 'hello!')
    379    >>> # Tuples may be nested:
    380    ... u = t, (1, 2, 3, 4, 5)
    381    >>> u
    382    ((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))
    383    >>> # Tuples are immutable:
    384    ... t[0] = 88888
    385    Traceback (most recent call last):
    386      File "<stdin>", line 1, in <module>
    387    TypeError: 'tuple' object does not support item assignment
    388    >>> # but they can contain mutable objects:
    389    ... v = ([1, 2, 3], [3, 2, 1])
    390    >>> v
    391    ([1, 2, 3], [3, 2, 1])
    392 
    393 
    394 As you see, on output tuples are always enclosed in parentheses, so that nested
    395 tuples are interpreted correctly; they may be input with or without surrounding
    396 parentheses, although often parentheses are necessary anyway (if the tuple is
    397 part of a larger expression).  It is not possible to assign to the individual
    398 items of a tuple, however it is possible to create tuples which contain mutable
    399 objects, such as lists.
    400 
    401 Though tuples may seem similar to lists, they are often used in different
    402 situations and for different purposes.
    403 Tuples are :term:`immutable`, and usually contain a heterogeneous sequence of
    404 elements that are accessed via unpacking (see later in this section) or indexing
    405 (or even by attribute in the case of :func:`namedtuples <collections.namedtuple>`).
    406 Lists are :term:`mutable`, and their elements are usually homogeneous and are
    407 accessed by iterating over the list.
    408 
    409 A special problem is the construction of tuples containing 0 or 1 items: the
    410 syntax has some extra quirks to accommodate these.  Empty tuples are constructed
    411 by an empty pair of parentheses; a tuple with one item is constructed by
    412 following a value with a comma (it is not sufficient to enclose a single value
    413 in parentheses). Ugly, but effective.  For example::
    414 
    415    >>> empty = ()
    416    >>> singleton = 'hello',    # <-- note trailing comma
    417    >>> len(empty)
    418    0
    419    >>> len(singleton)
    420    1
    421    >>> singleton
    422    ('hello',)
    423 
    424 The statement ``t = 12345, 54321, 'hello!'`` is an example of *tuple packing*:
    425 the values ``12345``, ``54321`` and ``'hello!'`` are packed together in a tuple.
    426 The reverse operation is also possible::
    427 
    428    >>> x, y, z = t
    429 
    430 This is called, appropriately enough, *sequence unpacking* and works for any
    431 sequence on the right-hand side.  Sequence unpacking requires that there are as
    432 many variables on the left side of the equals sign as there are elements in the
    433 sequence.  Note that multiple assignment is really just a combination of tuple
    434 packing and sequence unpacking.
    435 
    436 
    437 .. _tut-sets:
    438 
    439 Sets
    440 ====
    441 
    442 Python also includes a data type for *sets*.  A set is an unordered collection
    443 with no duplicate elements.  Basic uses include membership testing and
    444 eliminating duplicate entries.  Set objects also support mathematical operations
    445 like union, intersection, difference, and symmetric difference.
    446 
    447 Curly braces or the :func:`set` function can be used to create sets.  Note: to
    448 create an empty set you have to use ``set()``, not ``{}``; the latter creates an
    449 empty dictionary, a data structure that we discuss in the next section.
    450 
    451 Here is a brief demonstration::
    452 
    453    >>> basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
    454    >>> print(basket)                      # show that duplicates have been removed
    455    {'orange', 'banana', 'pear', 'apple'}
    456    >>> 'orange' in basket                 # fast membership testing
    457    True
    458    >>> 'crabgrass' in basket
    459    False
    460 
    461    >>> # Demonstrate set operations on unique letters from two words
    462    ...
    463    >>> a = set('abracadabra')
    464    >>> b = set('alacazam')
    465    >>> a                                  # unique letters in a
    466    {'a', 'r', 'b', 'c', 'd'}
    467    >>> a - b                              # letters in a but not in b
    468    {'r', 'd', 'b'}
    469    >>> a | b                              # letters in either a or b
    470    {'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}
    471    >>> a & b                              # letters in both a and b
    472    {'a', 'c'}
    473    >>> a ^ b                              # letters in a or b but not both
    474    {'r', 'd', 'b', 'm', 'z', 'l'}
    475 
    476 Similarly to :ref:`list comprehensions <tut-listcomps>`, set comprehensions
    477 are also supported::
    478 
    479    >>> a = {x for x in 'abracadabra' if x not in 'abc'}
    480    >>> a
    481    {'r', 'd'}
    482 
    483 
    484 .. _tut-dictionaries:
    485 
    486 Dictionaries
    487 ============
    488 
    489 Another useful data type built into Python is the *dictionary* (see
    490 :ref:`typesmapping`). Dictionaries are sometimes found in other languages as
    491 "associative memories" or "associative arrays".  Unlike sequences, which are
    492 indexed by a range of numbers, dictionaries are indexed by *keys*, which can be
    493 any immutable type; strings and numbers can always be keys.  Tuples can be used
    494 as keys if they contain only strings, numbers, or tuples; if a tuple contains
    495 any mutable object either directly or indirectly, it cannot be used as a key.
    496 You can't use lists as keys, since lists can be modified in place using index
    497 assignments, slice assignments, or methods like :meth:`append` and
    498 :meth:`extend`.
    499 
    500 It is best to think of a dictionary as an unordered set of *key: value* pairs,
    501 with the requirement that the keys are unique (within one dictionary). A pair of
    502 braces creates an empty dictionary: ``{}``. Placing a comma-separated list of
    503 key:value pairs within the braces adds initial key:value pairs to the
    504 dictionary; this is also the way dictionaries are written on output.
    505 
    506 The main operations on a dictionary are storing a value with some key and
    507 extracting the value given the key.  It is also possible to delete a key:value
    508 pair with ``del``. If you store using a key that is already in use, the old
    509 value associated with that key is forgotten.  It is an error to extract a value
    510 using a non-existent key.
    511 
    512 Performing ``list(d.keys())`` on a dictionary returns a list of all the keys
    513 used in the dictionary, in arbitrary order (if you want it sorted, just use
    514 ``sorted(d.keys())`` instead). [2]_  To check whether a single key is in the
    515 dictionary, use the :keyword:`in` keyword.
    516 
    517 Here is a small example using a dictionary::
    518 
    519    >>> tel = {'jack': 4098, 'sape': 4139}
    520    >>> tel['guido'] = 4127
    521    >>> tel
    522    {'sape': 4139, 'guido': 4127, 'jack': 4098}
    523    >>> tel['jack']
    524    4098
    525    >>> del tel['sape']
    526    >>> tel['irv'] = 4127
    527    >>> tel
    528    {'guido': 4127, 'irv': 4127, 'jack': 4098}
    529    >>> list(tel.keys())
    530    ['irv', 'guido', 'jack']
    531    >>> sorted(tel.keys())
    532    ['guido', 'irv', 'jack']
    533    >>> 'guido' in tel
    534    True
    535    >>> 'jack' not in tel
    536    False
    537 
    538 The :func:`dict` constructor builds dictionaries directly from sequences of
    539 key-value pairs::
    540 
    541    >>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
    542    {'sape': 4139, 'jack': 4098, 'guido': 4127}
    543 
    544 In addition, dict comprehensions can be used to create dictionaries from
    545 arbitrary key and value expressions::
    546 
    547    >>> {x: x**2 for x in (2, 4, 6)}
    548    {2: 4, 4: 16, 6: 36}
    549 
    550 When the keys are simple strings, it is sometimes easier to specify pairs using
    551 keyword arguments::
    552 
    553    >>> dict(sape=4139, guido=4127, jack=4098)
    554    {'sape': 4139, 'jack': 4098, 'guido': 4127}
    555 
    556 
    557 .. _tut-loopidioms:
    558 
    559 Looping Techniques
    560 ==================
    561 
    562 When looping through dictionaries, the key and corresponding value can be
    563 retrieved at the same time using the :meth:`items` method. ::
    564 
    565    >>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
    566    >>> for k, v in knights.items():
    567    ...     print(k, v)
    568    ...
    569    gallahad the pure
    570    robin the brave
    571 
    572 When looping through a sequence, the position index and corresponding value can
    573 be retrieved at the same time using the :func:`enumerate` function. ::
    574 
    575    >>> for i, v in enumerate(['tic', 'tac', 'toe']):
    576    ...     print(i, v)
    577    ...
    578    0 tic
    579    1 tac
    580    2 toe
    581 
    582 To loop over two or more sequences at the same time, the entries can be paired
    583 with the :func:`zip` function. ::
    584 
    585    >>> questions = ['name', 'quest', 'favorite color']
    586    >>> answers = ['lancelot', 'the holy grail', 'blue']
    587    >>> for q, a in zip(questions, answers):
    588    ...     print('What is your {0}?  It is {1}.'.format(q, a))
    589    ...
    590    What is your name?  It is lancelot.
    591    What is your quest?  It is the holy grail.
    592    What is your favorite color?  It is blue.
    593 
    594 To loop over a sequence in reverse, first specify the sequence in a forward
    595 direction and then call the :func:`reversed` function. ::
    596 
    597    >>> for i in reversed(range(1, 10, 2)):
    598    ...     print(i)
    599    ...
    600    9
    601    7
    602    5
    603    3
    604    1
    605 
    606 To loop over a sequence in sorted order, use the :func:`sorted` function which
    607 returns a new sorted list while leaving the source unaltered. ::
    608 
    609    >>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
    610    >>> for f in sorted(set(basket)):
    611    ...     print(f)
    612    ...
    613    apple
    614    banana
    615    orange
    616    pear
    617 
    618 It is sometimes tempting to change a list while you are looping over it;
    619 however, it is often simpler and safer to create a new list instead. ::
    620 
    621    >>> import math
    622    >>> raw_data = [56.2, float('NaN'), 51.7, 55.3, 52.5, float('NaN'), 47.8]
    623    >>> filtered_data = []
    624    >>> for value in raw_data:
    625    ...     if not math.isnan(value):
    626    ...         filtered_data.append(value)
    627    ...
    628    >>> filtered_data
    629    [56.2, 51.7, 55.3, 52.5, 47.8]
    630 
    631 
    632 .. _tut-conditions:
    633 
    634 More on Conditions
    635 ==================
    636 
    637 The conditions used in ``while`` and ``if`` statements can contain any
    638 operators, not just comparisons.
    639 
    640 The comparison operators ``in`` and ``not in`` check whether a value occurs
    641 (does not occur) in a sequence.  The operators ``is`` and ``is not`` compare
    642 whether two objects are really the same object; this only matters for mutable
    643 objects like lists.  All comparison operators have the same priority, which is
    644 lower than that of all numerical operators.
    645 
    646 Comparisons can be chained.  For example, ``a < b == c`` tests whether ``a`` is
    647 less than ``b`` and moreover ``b`` equals ``c``.
    648 
    649 Comparisons may be combined using the Boolean operators ``and`` and ``or``, and
    650 the outcome of a comparison (or of any other Boolean expression) may be negated
    651 with ``not``.  These have lower priorities than comparison operators; between
    652 them, ``not`` has the highest priority and ``or`` the lowest, so that ``A and
    653 not B or C`` is equivalent to ``(A and (not B)) or C``. As always, parentheses
    654 can be used to express the desired composition.
    655 
    656 The Boolean operators ``and`` and ``or`` are so-called *short-circuit*
    657 operators: their arguments are evaluated from left to right, and evaluation
    658 stops as soon as the outcome is determined.  For example, if ``A`` and ``C`` are
    659 true but ``B`` is false, ``A and B and C`` does not evaluate the expression
    660 ``C``.  When used as a general value and not as a Boolean, the return value of a
    661 short-circuit operator is the last evaluated argument.
    662 
    663 It is possible to assign the result of a comparison or other Boolean expression
    664 to a variable.  For example, ::
    665 
    666    >>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance'
    667    >>> non_null = string1 or string2 or string3
    668    >>> non_null
    669    'Trondheim'
    670 
    671 Note that in Python, unlike C, assignment cannot occur inside expressions. C
    672 programmers may grumble about this, but it avoids a common class of problems
    673 encountered in C programs: typing ``=`` in an expression when ``==`` was
    674 intended.
    675 
    676 
    677 .. _tut-comparing:
    678 
    679 Comparing Sequences and Other Types
    680 ===================================
    681 
    682 Sequence objects may be compared to other objects with the same sequence type.
    683 The comparison uses *lexicographical* ordering: first the first two items are
    684 compared, and if they differ this determines the outcome of the comparison; if
    685 they are equal, the next two items are compared, and so on, until either
    686 sequence is exhausted. If two items to be compared are themselves sequences of
    687 the same type, the lexicographical comparison is carried out recursively.  If
    688 all items of two sequences compare equal, the sequences are considered equal.
    689 If one sequence is an initial sub-sequence of the other, the shorter sequence is
    690 the smaller (lesser) one.  Lexicographical ordering for strings uses the Unicode
    691 code point number to order individual characters.  Some examples of comparisons
    692 between sequences of the same type::
    693 
    694    (1, 2, 3)              < (1, 2, 4)
    695    [1, 2, 3]              < [1, 2, 4]
    696    'ABC' < 'C' < 'Pascal' < 'Python'
    697    (1, 2, 3, 4)           < (1, 2, 4)
    698    (1, 2)                 < (1, 2, -1)
    699    (1, 2, 3)             == (1.0, 2.0, 3.0)
    700    (1, 2, ('aa', 'ab'))   < (1, 2, ('abc', 'a'), 4)
    701 
    702 Note that comparing objects of different types with ``<`` or ``>`` is legal
    703 provided that the objects have appropriate comparison methods.  For example,
    704 mixed numeric types are compared according to their numeric value, so 0 equals
    705 0.0, etc.  Otherwise, rather than providing an arbitrary ordering, the
    706 interpreter will raise a :exc:`TypeError` exception.
    707 
    708 
    709 .. rubric:: Footnotes
    710 
    711 .. [1] Other languages may return the mutated object, which allows method
    712        chaining, such as ``d->insert("a")->remove("b")->sort();``.
    713 
    714 .. [2] Calling ``d.keys()`` will return a :dfn:`dictionary view` object.  It
    715        supports operations like membership test and iteration, but its contents
    716        are not independent of the original dictionary -- it is only a *view*.
    717