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