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