blob: a56fd2b042af9c7ca8c79ef5539ca8451807abdd [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)
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000217 ...
Georg Brandl8ec7f652007-08-15 14:28:01 +0000218 >>> 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]]
Georg Brandl7044b112009-01-03 21:04:55 +0000254 >>> [x, x**2 for x in vec] # error - parens required for tuples
Georg Brandl8ec7f652007-08-15 14:28:01 +0000255 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
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000284Consider the following example of a 3x3 matrix held as a list containing three
Georg Brandladbda842007-12-14 19:03:36 +0000285lists, one list per row::
286
287 >>> mat = [
288 ... [1, 2, 3],
289 ... [4, 5, 6],
290 ... [7, 8, 9],
291 ... ]
292
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000293Now, if you wanted to swap rows and columns, you could use a list
Georg Brandladbda842007-12-14 19:03:36 +0000294comprehension::
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
Mark Dickinson3e4caeb2009-02-21 20:27:01 +0000311In real world, you should prefer built-in functions to complex flow statements.
Georg Brandladbda842007-12-14 19:03:36 +0000312The :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
348
349.. _tut-tuples:
350
351Tuples and Sequences
352====================
353
354We saw that lists and strings have many common properties, such as indexing and
355slicing operations. They are two examples of *sequence* data types (see
356:ref:`typesseq`). Since Python is an evolving language, other sequence data
357types may be added. There is also another standard sequence data type: the
358*tuple*.
359
360A tuple consists of a number of values separated by commas, for instance::
361
362 >>> t = 12345, 54321, 'hello!'
363 >>> t[0]
364 12345
365 >>> t
366 (12345, 54321, 'hello!')
367 >>> # Tuples may be nested:
368 ... u = t, (1, 2, 3, 4, 5)
369 >>> u
370 ((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))
371
372As you see, on output tuples are always enclosed in parentheses, so that nested
373tuples are interpreted correctly; they may be input with or without surrounding
374parentheses, although often parentheses are necessary anyway (if the tuple is
375part of a larger expression).
376
377Tuples have many uses. For example: (x, y) coordinate pairs, employee records
378from a database, etc. Tuples, like strings, are immutable: it is not possible
379to assign to the individual items of a tuple (you can simulate much of the same
380effect with slicing and concatenation, though). It is also possible to create
381tuples which contain mutable objects, such as lists.
382
383A special problem is the construction of tuples containing 0 or 1 items: the
384syntax has some extra quirks to accommodate these. Empty tuples are constructed
385by an empty pair of parentheses; a tuple with one item is constructed by
386following a value with a comma (it is not sufficient to enclose a single value
387in parentheses). Ugly, but effective. For example::
388
389 >>> empty = ()
390 >>> singleton = 'hello', # <-- note trailing comma
391 >>> len(empty)
392 0
393 >>> len(singleton)
394 1
395 >>> singleton
396 ('hello',)
397
398The statement ``t = 12345, 54321, 'hello!'`` is an example of *tuple packing*:
399the values ``12345``, ``54321`` and ``'hello!'`` are packed together in a tuple.
400The reverse operation is also possible::
401
402 >>> x, y, z = t
403
Georg Brandl354e4cb2009-03-31 22:40:16 +0000404This is called, appropriately enough, *sequence unpacking* and works for any
405sequence on the right-hand side. Sequence unpacking requires the list of
406variables on the left to have the same number of elements as the length of the
407sequence. Note that multiple assignment is really just a combination of tuple
Georg Brandla08867d2009-03-31 23:01:27 +0000408packing and sequence unpacking.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000409
Georg Brandlb19be572007-12-29 10:57:00 +0000410.. XXX Add a bit on the difference between tuples and lists.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000411
412
413.. _tut-sets:
414
415Sets
416====
417
418Python also includes a data type for *sets*. A set is an unordered collection
419with no duplicate elements. Basic uses include membership testing and
420eliminating duplicate entries. Set objects also support mathematical operations
421like union, intersection, difference, and symmetric difference.
422
423Here is a brief demonstration::
424
425 >>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
426 >>> fruit = set(basket) # create a set without duplicates
427 >>> fruit
428 set(['orange', 'pear', 'apple', 'banana'])
429 >>> 'orange' in fruit # fast membership testing
430 True
431 >>> 'crabgrass' in fruit
432 False
433
434 >>> # Demonstrate set operations on unique letters from two words
435 ...
436 >>> a = set('abracadabra')
437 >>> b = set('alacazam')
438 >>> a # unique letters in a
439 set(['a', 'r', 'b', 'c', 'd'])
440 >>> a - b # letters in a but not in b
441 set(['r', 'd', 'b'])
442 >>> a | b # letters in either a or b
443 set(['a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'])
444 >>> a & b # letters in both a and b
445 set(['a', 'c'])
446 >>> a ^ b # letters in a or b but not both
447 set(['r', 'd', 'b', 'm', 'z', 'l'])
448
449
450.. _tut-dictionaries:
451
452Dictionaries
453============
454
455Another useful data type built into Python is the *dictionary* (see
456:ref:`typesmapping`). Dictionaries are sometimes found in other languages as
457"associative memories" or "associative arrays". Unlike sequences, which are
458indexed by a range of numbers, dictionaries are indexed by *keys*, which can be
459any immutable type; strings and numbers can always be keys. Tuples can be used
460as keys if they contain only strings, numbers, or tuples; if a tuple contains
461any mutable object either directly or indirectly, it cannot be used as a key.
462You can't use lists as keys, since lists can be modified in place using index
463assignments, slice assignments, or methods like :meth:`append` and
464:meth:`extend`.
465
466It is best to think of a dictionary as an unordered set of *key: value* pairs,
467with the requirement that the keys are unique (within one dictionary). A pair of
468braces creates an empty dictionary: ``{}``. Placing a comma-separated list of
469key:value pairs within the braces adds initial key:value pairs to the
470dictionary; this is also the way dictionaries are written on output.
471
472The main operations on a dictionary are storing a value with some key and
473extracting the value given the key. It is also possible to delete a key:value
474pair with ``del``. If you store using a key that is already in use, the old
475value associated with that key is forgotten. It is an error to extract a value
476using a non-existent key.
477
478The :meth:`keys` method of a dictionary object returns a list of all the keys
479used in the dictionary, in arbitrary order (if you want it sorted, just apply
480the :meth:`sort` method to the list of keys). To check whether a single key is
Georg Brandl8ca6c842008-03-28 12:22:12 +0000481in the dictionary, use the :keyword:`in` keyword.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000482
483Here is a small example using a dictionary::
484
485 >>> tel = {'jack': 4098, 'sape': 4139}
486 >>> tel['guido'] = 4127
487 >>> tel
488 {'sape': 4139, 'guido': 4127, 'jack': 4098}
489 >>> tel['jack']
490 4098
491 >>> del tel['sape']
492 >>> tel['irv'] = 4127
493 >>> tel
494 {'guido': 4127, 'irv': 4127, 'jack': 4098}
495 >>> tel.keys()
496 ['guido', 'irv', 'jack']
Georg Brandl8ec7f652007-08-15 14:28:01 +0000497 >>> 'guido' in tel
498 True
499
500The :func:`dict` constructor builds dictionaries directly from lists of
501key-value pairs stored as tuples. When the pairs form a pattern, list
502comprehensions can compactly specify the key-value list. ::
503
504 >>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
505 {'sape': 4139, 'jack': 4098, 'guido': 4127}
506 >>> dict([(x, x**2) for x in (2, 4, 6)]) # use a list comprehension
507 {2: 4, 4: 16, 6: 36}
508
509Later in the tutorial, we will learn about Generator Expressions which are even
510better suited for the task of supplying key-values pairs to the :func:`dict`
511constructor.
512
513When the keys are simple strings, it is sometimes easier to specify pairs using
514keyword arguments::
515
516 >>> dict(sape=4139, guido=4127, jack=4098)
517 {'sape': 4139, 'jack': 4098, 'guido': 4127}
518
519
520.. _tut-loopidioms:
521
522Looping Techniques
523==================
524
525When looping through dictionaries, the key and corresponding value can be
526retrieved at the same time using the :meth:`iteritems` method. ::
527
528 >>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
529 >>> for k, v in knights.iteritems():
530 ... print k, v
531 ...
532 gallahad the pure
533 robin the brave
534
535When looping through a sequence, the position index and corresponding value can
536be retrieved at the same time using the :func:`enumerate` function. ::
537
538 >>> for i, v in enumerate(['tic', 'tac', 'toe']):
539 ... print i, v
540 ...
541 0 tic
542 1 tac
543 2 toe
544
545To loop over two or more sequences at the same time, the entries can be paired
546with the :func:`zip` function. ::
547
548 >>> questions = ['name', 'quest', 'favorite color']
549 >>> answers = ['lancelot', 'the holy grail', 'blue']
550 >>> for q, a in zip(questions, answers):
Benjamin Petersonf9ef9882008-05-26 00:54:22 +0000551 ... print 'What is your {0}? It is {1}.'.format(q, a)
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000552 ...
Georg Brandl8ec7f652007-08-15 14:28:01 +0000553 What is your name? It is lancelot.
554 What is your quest? It is the holy grail.
555 What is your favorite color? It is blue.
556
557To loop over a sequence in reverse, first specify the sequence in a forward
558direction and then call the :func:`reversed` function. ::
559
560 >>> for i in reversed(xrange(1,10,2)):
561 ... print i
562 ...
563 9
564 7
565 5
566 3
567 1
568
569To loop over a sequence in sorted order, use the :func:`sorted` function which
570returns a new sorted list while leaving the source unaltered. ::
571
572 >>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
573 >>> for f in sorted(set(basket)):
574 ... print f
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000575 ...
Georg Brandl8ec7f652007-08-15 14:28:01 +0000576 apple
577 banana
578 orange
579 pear
580
581
582.. _tut-conditions:
583
584More on Conditions
585==================
586
587The conditions used in ``while`` and ``if`` statements can contain any
588operators, not just comparisons.
589
590The comparison operators ``in`` and ``not in`` check whether a value occurs
591(does not occur) in a sequence. The operators ``is`` and ``is not`` compare
592whether two objects are really the same object; this only matters for mutable
593objects like lists. All comparison operators have the same priority, which is
594lower than that of all numerical operators.
595
596Comparisons can be chained. For example, ``a < b == c`` tests whether ``a`` is
597less than ``b`` and moreover ``b`` equals ``c``.
598
599Comparisons may be combined using the Boolean operators ``and`` and ``or``, and
600the outcome of a comparison (or of any other Boolean expression) may be negated
601with ``not``. These have lower priorities than comparison operators; between
602them, ``not`` has the highest priority and ``or`` the lowest, so that ``A and
603not B or C`` is equivalent to ``(A and (not B)) or C``. As always, parentheses
604can be used to express the desired composition.
605
606The Boolean operators ``and`` and ``or`` are so-called *short-circuit*
607operators: their arguments are evaluated from left to right, and evaluation
608stops as soon as the outcome is determined. For example, if ``A`` and ``C`` are
609true but ``B`` is false, ``A and B and C`` does not evaluate the expression
610``C``. When used as a general value and not as a Boolean, the return value of a
611short-circuit operator is the last evaluated argument.
612
613It is possible to assign the result of a comparison or other Boolean expression
614to a variable. For example, ::
615
616 >>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance'
617 >>> non_null = string1 or string2 or string3
618 >>> non_null
619 'Trondheim'
620
621Note that in Python, unlike C, assignment cannot occur inside expressions. C
622programmers may grumble about this, but it avoids a common class of problems
623encountered in C programs: typing ``=`` in an expression when ``==`` was
624intended.
625
626
627.. _tut-comparing:
628
629Comparing Sequences and Other Types
630===================================
631
632Sequence objects may be compared to other objects with the same sequence type.
633The comparison uses *lexicographical* ordering: first the first two items are
634compared, and if they differ this determines the outcome of the comparison; if
635they are equal, the next two items are compared, and so on, until either
636sequence is exhausted. If two items to be compared are themselves sequences of
637the same type, the lexicographical comparison is carried out recursively. If
638all items of two sequences compare equal, the sequences are considered equal.
639If one sequence is an initial sub-sequence of the other, the shorter sequence is
640the smaller (lesser) one. Lexicographical ordering for strings uses the ASCII
641ordering for individual characters. Some examples of comparisons between
642sequences of the same type::
643
644 (1, 2, 3) < (1, 2, 4)
645 [1, 2, 3] < [1, 2, 4]
646 'ABC' < 'C' < 'Pascal' < 'Python'
647 (1, 2, 3, 4) < (1, 2, 4)
648 (1, 2) < (1, 2, -1)
649 (1, 2, 3) == (1.0, 2.0, 3.0)
650 (1, 2, ('aa', 'ab')) < (1, 2, ('abc', 'a'), 4)
651
652Note that comparing objects of different types is legal. The outcome is
653deterministic but arbitrary: the types are ordered by their name. Thus, a list
654is always smaller than a string, a string is always smaller than a tuple, etc.
655[#]_ Mixed numeric types are compared according to their numeric value, so 0
656equals 0.0, etc.
657
658
659.. rubric:: Footnotes
660
661.. [#] The rules for comparing objects of different types should not be relied upon;
662 they may change in a future version of the language.
663