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