blob: cf9fea3bd5c77b744b81111ea8ca5970eff04115 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +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
Guido van Rossum0616b792007-08-31 03:25:11 +000010.. _tut-tuples:
11
12Tuples and Sequences
13====================
14
15We saw that lists and strings have many common properties, such as indexing and
16slicing operations. They are two examples of *sequence* data types (see
17:ref:`typesseq`). Since Python is an evolving language, other sequence data
18types may be added. There is also another standard sequence data type: the
19*tuple*.
20
21A tuple consists of a number of values separated by commas, for instance::
22
23 >>> t = 12345, 54321, 'hello!'
24 >>> t[0]
25 12345
26 >>> t
27 (12345, 54321, 'hello!')
28 >>> # Tuples may be nested:
29 ... u = t, (1, 2, 3, 4, 5)
30 >>> u
31 ((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))
32
33As you see, on output tuples are always enclosed in parentheses, so that nested
34tuples are interpreted correctly; they may be input with or without surrounding
35parentheses, although often parentheses are necessary anyway (if the tuple is
36part of a larger expression).
37
38Tuples have many uses. For example: (x, y) coordinate pairs, employee records
39from a database, etc. Tuples, like strings, are immutable: it is not possible
40to assign to the individual items of a tuple (you can simulate much of the same
41effect with slicing and concatenation, though). It is also possible to create
42tuples which contain mutable objects, such as lists.
43
44A special problem is the construction of tuples containing 0 or 1 items: the
45syntax has some extra quirks to accommodate these. Empty tuples are constructed
46by an empty pair of parentheses; a tuple with one item is constructed by
47following a value with a comma (it is not sufficient to enclose a single value
48in parentheses). Ugly, but effective. For example::
49
50 >>> empty = ()
51 >>> singleton = 'hello', # <-- note trailing comma
52 >>> len(empty)
53 0
54 >>> len(singleton)
55 1
56 >>> singleton
57 ('hello',)
58
59The statement ``t = 12345, 54321, 'hello!'`` is an example of *tuple packing*:
60the values ``12345``, ``54321`` and ``'hello!'`` are packed together in a tuple.
61The reverse operation is also possible::
62
63 >>> x, y, z = t
64
65This is called, appropriately enough, *sequence unpacking*. Sequence unpacking
66requires the list of variables on the left to have the same number of elements
67as the length of the sequence. Note that multiple assignment is really just a
68combination of tuple packing and sequence unpacking!
69
70There is a small bit of asymmetry here: packing multiple values always creates
71a tuple, and unpacking works for any sequence.
72
73.. % XXX Add a bit on the difference between tuples and lists.
74
Georg Brandl116aa622007-08-15 14:28:22 +000075
76.. _tut-morelists:
77
78More on Lists
79=============
80
81The list data type has some more methods. Here are all of the methods of list
82objects:
83
84
85.. method:: list.append(x)
86
87 Add an item to the end of the list; equivalent to ``a[len(a):] = [x]``.
88
89
90.. method:: list.extend(L)
91
92 Extend the list by appending all the items in the given list; equivalent to
93 ``a[len(a):] = L``.
94
95
96.. method:: list.insert(i, x)
97
98 Insert an item at a given position. The first argument is the index of the
99 element before which to insert, so ``a.insert(0, x)`` inserts at the front of
100 the list, and ``a.insert(len(a), x)`` is equivalent to ``a.append(x)``.
101
102
103.. method:: list.remove(x)
104
105 Remove the first item from the list whose value is *x*. It is an error if there
106 is no such item.
107
108
109.. method:: list.pop([i])
110
111 Remove the item at the given position in the list, and return it. If no index
112 is specified, ``a.pop()`` removes and returns the last item in the list. (The
113 square brackets around the *i* in the method signature denote that the parameter
114 is optional, not that you should type square brackets at that position. You
115 will see this notation frequently in the Python Library Reference.)
116
117
118.. method:: list.index(x)
119
120 Return the index in the list of the first item whose value is *x*. It is an
121 error if there is no such item.
122
123
124.. method:: list.count(x)
125
126 Return the number of times *x* appears in the list.
127
128
129.. method:: list.sort()
130
131 Sort the items of the list, in place.
132
133
134.. method:: list.reverse()
135
136 Reverse the elements of the list, in place.
137
138An example that uses most of the list methods::
139
140 >>> a = [66.25, 333, 333, 1, 1234.5]
Guido van Rossum0616b792007-08-31 03:25:11 +0000141 >>> print(a.count(333), a.count(66.25), a.count('x'))
Georg Brandl116aa622007-08-15 14:28:22 +0000142 2 1 0
143 >>> a.insert(2, -1)
144 >>> a.append(333)
145 >>> a
146 [66.25, 333, -1, 333, 1, 1234.5, 333]
147 >>> a.index(333)
148 1
149 >>> a.remove(333)
150 >>> a
151 [66.25, -1, 333, 1, 1234.5, 333]
152 >>> a.reverse()
153 >>> a
154 [333, 1234.5, 1, 333, -1, 66.25]
155 >>> a.sort()
156 >>> a
157 [-1, 1, 66.25, 333, 333, 1234.5]
158
159
160.. _tut-lists-as-stacks:
161
162Using Lists as Stacks
163---------------------
164
165.. sectionauthor:: Ka-Ping Yee <ping@lfw.org>
166
167
168The list methods make it very easy to use a list as a stack, where the last
169element added is the first element retrieved ("last-in, first-out"). To add an
170item to the top of the stack, use :meth:`append`. To retrieve an item from the
171top of the stack, use :meth:`pop` without an explicit index. For example::
172
173 >>> stack = [3, 4, 5]
174 >>> stack.append(6)
175 >>> stack.append(7)
176 >>> stack
177 [3, 4, 5, 6, 7]
178 >>> stack.pop()
179 7
180 >>> stack
181 [3, 4, 5, 6]
182 >>> stack.pop()
183 6
184 >>> stack.pop()
185 5
186 >>> stack
187 [3, 4]
188
189
190.. _tut-lists-as-queues:
191
192Using Lists as Queues
193---------------------
194
195.. sectionauthor:: Ka-Ping Yee <ping@lfw.org>
196
197
198You can also use a list conveniently as a queue, where the first element added
199is the first element retrieved ("first-in, first-out"). To add an item to the
200back of the queue, use :meth:`append`. To retrieve an item from the front of
201the queue, use :meth:`pop` with ``0`` as the index. For example::
202
203 >>> queue = ["Eric", "John", "Michael"]
204 >>> queue.append("Terry") # Terry arrives
205 >>> queue.append("Graham") # Graham arrives
206 >>> queue.pop(0)
207 'Eric'
208 >>> queue.pop(0)
209 'John'
210 >>> queue
211 ['Michael', 'Terry', 'Graham']
212
213
Georg Brandl116aa622007-08-15 14:28:22 +0000214List Comprehensions
215-------------------
216
Guido van Rossum0616b792007-08-31 03:25:11 +0000217List comprehensions provide a concise way to create lists from sequences.
218Common applications are to make lists where each element is the result of
219some operations applied to each member of the sequence, or to create a
220subsequence of those elements that satisfy a certain condition.
221
222
Georg Brandl116aa622007-08-15 14:28:22 +0000223Each list comprehension consists of an expression followed by a :keyword:`for`
224clause, then zero or more :keyword:`for` or :keyword:`if` clauses. The result
225will be a list resulting from evaluating the expression in the context of the
226:keyword:`for` and :keyword:`if` clauses which follow it. If the expression
Guido van Rossum0616b792007-08-31 03:25:11 +0000227would evaluate to a tuple, it must be parenthesized.
228
229Here we take a list of numbers and return a list of three times each number::
230
231 >>> vec = [2, 4, 6]
232 >>> [3*x for x in vec]
233 [6, 12, 18]
234
235Now we get a little fancier::
236
Georg Brandle4ac7502007-09-03 07:10:24 +0000237 >>> [[x, x**2] for x in vec]
Guido van Rossum0616b792007-08-31 03:25:11 +0000238 [[2, 4], [4, 16], [6, 36]]
239
240Here we apply a method call to each item in a sequence::
Georg Brandl116aa622007-08-15 14:28:22 +0000241
242 >>> freshfruit = [' banana', ' loganberry ', 'passion fruit ']
243 >>> [weapon.strip() for weapon in freshfruit]
244 ['banana', 'loganberry', 'passion fruit']
Guido van Rossum0616b792007-08-31 03:25:11 +0000245
Georg Brandle4ac7502007-09-03 07:10:24 +0000246Using the :keyword:`if` clause we can filter the stream::
Guido van Rossum0616b792007-08-31 03:25:11 +0000247
Georg Brandl116aa622007-08-15 14:28:22 +0000248 >>> [3*x for x in vec if x > 3]
249 [12, 18]
250 >>> [3*x for x in vec if x < 2]
251 []
Guido van Rossum0616b792007-08-31 03:25:11 +0000252
253Tuples can often be created without their parentheses, but not here::
254
Georg Brandl116aa622007-08-15 14:28:22 +0000255 >>> [x, x**2 for x in vec] # error - parens required for tuples
256 File "<stdin>", line 1, in ?
257 [x, x**2 for x in vec]
258 ^
259 SyntaxError: invalid syntax
260 >>> [(x, x**2) for x in vec]
261 [(2, 4), (4, 16), (6, 36)]
Guido van Rossum0616b792007-08-31 03:25:11 +0000262
Georg Brandle4ac7502007-09-03 07:10:24 +0000263Here are some nested for loops and other fancy behavior::
Guido van Rossum0616b792007-08-31 03:25:11 +0000264
Georg Brandl116aa622007-08-15 14:28:22 +0000265 >>> vec1 = [2, 4, 6]
266 >>> vec2 = [4, 3, -9]
267 >>> [x*y for x in vec1 for y in vec2]
268 [8, 6, -18, 16, 12, -36, 24, 18, -54]
269 >>> [x+y for x in vec1 for y in vec2]
270 [6, 5, -7, 8, 7, -5, 10, 9, -3]
271 >>> [vec1[i]*vec2[i] for i in range(len(vec1))]
272 [8, 12, -54]
273
Guido van Rossum0616b792007-08-31 03:25:11 +0000274List comprehensions can be applied to complex expressions and nested functions::
Georg Brandl116aa622007-08-15 14:28:22 +0000275
Georg Brandle4ac7502007-09-03 07:10:24 +0000276 >>> [str(round(355/113.0, i)) for i in range(1, 6)]
Georg Brandl116aa622007-08-15 14:28:22 +0000277 ['3.1', '3.14', '3.142', '3.1416', '3.14159']
278
279
Christian Heimes0449f632007-12-15 01:27:15 +0000280Nested List Comprehensions
281--------------------------
282
283If you've got the stomach for it, list comprehensions can be nested. They are a
284powerful tool but -- like all powerful tools -- they need to be used carefully,
285if at all.
286
287Consider the following example of a 3x3 matrix held as a list containing three
288lists, one list per row::
289
290 >>> mat = [
291 ... [1, 2, 3],
292 ... [4, 5, 6],
293 ... [7, 8, 9],
294 ... ]
295
296Now, if you wanted to swap rows and columns, you could use a list
297comprehension::
298
299 >>> print [[row[i] for row in mat] for i in [0, 1, 2]]
300 [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
301
302Special care has to be taken for the *nested* list comprehension:
303
304 To avoid apprehension when nesting list comprehensions, read from right to
305 left.
306
307A more verbose version of this snippet shows the flow explicitly::
308
309 for i in [0, 1, 2]:
310 for row in mat:
311 print row[i],
312 print
313
314In real world, you should prefer builtin functions to complex flow statements.
315The :func:`zip` function would do a great job for this use case::
316
317 >>> zip(*mat)
318 [(1, 4, 7), (2, 5, 8), (3, 6, 9)]
319
320See :ref:`tut-unpacking-arguments` for details on the asterisk in this line.
321
Georg Brandl116aa622007-08-15 14:28:22 +0000322.. _tut-del:
323
324The :keyword:`del` statement
325============================
326
327There is a way to remove an item from a list given its index instead of its
328value: the :keyword:`del` statement. This differs from the :meth:`pop` method
329which returns a value. The :keyword:`del` statement can also be used to remove
330slices from a list or clear the entire list (which we did earlier by assignment
331of an empty list to the slice). For example::
332
333 >>> a = [-1, 1, 66.25, 333, 333, 1234.5]
334 >>> del a[0]
335 >>> a
336 [1, 66.25, 333, 333, 1234.5]
337 >>> del a[2:4]
338 >>> a
339 [1, 66.25, 1234.5]
340 >>> del a[:]
341 >>> a
342 []
343
344:keyword:`del` can also be used to delete entire variables::
345
346 >>> del a
347
348Referencing the name ``a`` hereafter is an error (at least until another value
349is assigned to it). We'll find other uses for :keyword:`del` later.
350
351
Georg Brandl116aa622007-08-15 14:28:22 +0000352
353.. _tut-sets:
354
355Sets
356====
357
358Python also includes a data type for *sets*. A set is an unordered collection
359with no duplicate elements. Basic uses include membership testing and
360eliminating duplicate entries. Set objects also support mathematical operations
361like union, intersection, difference, and symmetric difference.
362
Guido van Rossum0616b792007-08-31 03:25:11 +0000363Curly braces or the :func:`set` function can be use to create sets. Note:
364To create an empty set you have to use set(), not {}; the latter creates
365an empty dictionary, a data structure that we discuss in the next section.
366
Georg Brandl116aa622007-08-15 14:28:22 +0000367Here is a brief demonstration::
368
Guido van Rossum0616b792007-08-31 03:25:11 +0000369 >>> basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
370 >>> print(basket)
371 {'orange', 'bananna', 'pear', 'apple'}
372 >>> fruit = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
Georg Brandl116aa622007-08-15 14:28:22 +0000373 >>> fruit = set(basket) # create a set without duplicates
374 >>> fruit
Guido van Rossum0616b792007-08-31 03:25:11 +0000375 {'orange', 'pear', 'apple', 'banana'}
Georg Brandl116aa622007-08-15 14:28:22 +0000376 >>> 'orange' in fruit # fast membership testing
377 True
378 >>> 'crabgrass' in fruit
379 False
380
381 >>> # Demonstrate set operations on unique letters from two words
382 ...
383 >>> a = set('abracadabra')
384 >>> b = set('alacazam')
385 >>> a # unique letters in a
Guido van Rossum0616b792007-08-31 03:25:11 +0000386 {'a', 'r', 'b', 'c', 'd'}
Georg Brandl116aa622007-08-15 14:28:22 +0000387 >>> a - b # letters in a but not in b
Guido van Rossum0616b792007-08-31 03:25:11 +0000388 {'r', 'd', 'b'}
Georg Brandl116aa622007-08-15 14:28:22 +0000389 >>> a | b # letters in either a or b
Guido van Rossum0616b792007-08-31 03:25:11 +0000390 {'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}
Georg Brandl116aa622007-08-15 14:28:22 +0000391 >>> a & b # letters in both a and b
Guido van Rossum0616b792007-08-31 03:25:11 +0000392 {'a', 'c'}
Georg Brandl116aa622007-08-15 14:28:22 +0000393 >>> a ^ b # letters in a or b but not both
Guido van Rossum0616b792007-08-31 03:25:11 +0000394 {'r', 'd', 'b', 'm', 'z', 'l'}
395
396
Georg Brandl116aa622007-08-15 14:28:22 +0000397
398
399.. _tut-dictionaries:
400
401Dictionaries
402============
403
404Another useful data type built into Python is the *dictionary* (see
405:ref:`typesmapping`). Dictionaries are sometimes found in other languages as
406"associative memories" or "associative arrays". Unlike sequences, which are
407indexed by a range of numbers, dictionaries are indexed by *keys*, which can be
408any immutable type; strings and numbers can always be keys. Tuples can be used
409as keys if they contain only strings, numbers, or tuples; if a tuple contains
410any mutable object either directly or indirectly, it cannot be used as a key.
411You can't use lists as keys, since lists can be modified in place using index
412assignments, slice assignments, or methods like :meth:`append` and
413:meth:`extend`.
414
415It is best to think of a dictionary as an unordered set of *key: value* pairs,
416with the requirement that the keys are unique (within one dictionary). A pair of
417braces creates an empty dictionary: ``{}``. Placing a comma-separated list of
418key:value pairs within the braces adds initial key:value pairs to the
419dictionary; this is also the way dictionaries are written on output.
420
421The main operations on a dictionary are storing a value with some key and
422extracting the value given the key. It is also possible to delete a key:value
423pair with ``del``. If you store using a key that is already in use, the old
424value associated with that key is forgotten. It is an error to extract a value
425using a non-existent key.
426
427The :meth:`keys` method of a dictionary object returns a list of all the keys
428used in the dictionary, in arbitrary order (if you want it sorted, just apply
429the :meth:`sort` method to the list of keys). To check whether a single key is
Collin Winter19ab2bd2007-09-10 00:20:46 +0000430in the dictionary, use the :keyword:`in` keyword.
Georg Brandl116aa622007-08-15 14:28:22 +0000431
432Here is a small example using a dictionary::
433
434 >>> tel = {'jack': 4098, 'sape': 4139}
435 >>> tel['guido'] = 4127
436 >>> tel
437 {'sape': 4139, 'guido': 4127, 'jack': 4098}
438 >>> tel['jack']
439 4098
440 >>> del tel['sape']
441 >>> tel['irv'] = 4127
442 >>> tel
443 {'guido': 4127, 'irv': 4127, 'jack': 4098}
Neal Norwitze0906d12007-08-31 03:46:28 +0000444 >>> list(tel.keys())
Georg Brandl116aa622007-08-15 14:28:22 +0000445 ['guido', 'irv', 'jack']
Georg Brandl116aa622007-08-15 14:28:22 +0000446 >>> 'guido' in tel
447 True
Neal Norwitze0906d12007-08-31 03:46:28 +0000448 >>> 'jack' not in tel
449 False
Georg Brandl116aa622007-08-15 14:28:22 +0000450
451The :func:`dict` constructor builds dictionaries directly from lists of
452key-value pairs stored as tuples. When the pairs form a pattern, list
453comprehensions can compactly specify the key-value list. ::
454
455 >>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
456 {'sape': 4139, 'jack': 4098, 'guido': 4127}
457 >>> dict([(x, x**2) for x in (2, 4, 6)]) # use a list comprehension
458 {2: 4, 4: 16, 6: 36}
459
460Later in the tutorial, we will learn about Generator Expressions which are even
461better suited for the task of supplying key-values pairs to the :func:`dict`
462constructor.
463
464When the keys are simple strings, it is sometimes easier to specify pairs using
465keyword arguments::
466
467 >>> dict(sape=4139, guido=4127, jack=4098)
468 {'sape': 4139, 'jack': 4098, 'guido': 4127}
469
470
471.. _tut-loopidioms:
Guido van Rossum0616b792007-08-31 03:25:11 +0000472.. %
473 Find out the right way to do these DUBOIS
Georg Brandl116aa622007-08-15 14:28:22 +0000474
475Looping Techniques
476==================
477
478When looping through dictionaries, the key and corresponding value can be
Neal Norwitze0906d12007-08-31 03:46:28 +0000479retrieved at the same time using the :meth:`items` method. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000480
481 >>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
Neal Norwitze0906d12007-08-31 03:46:28 +0000482 >>> for k, v in knights.items():
Guido van Rossum0616b792007-08-31 03:25:11 +0000483 ... print(k, v)
Georg Brandl116aa622007-08-15 14:28:22 +0000484 ...
485 gallahad the pure
486 robin the brave
487
488When looping through a sequence, the position index and corresponding value can
489be retrieved at the same time using the :func:`enumerate` function. ::
490
491 >>> for i, v in enumerate(['tic', 'tac', 'toe']):
Guido van Rossum0616b792007-08-31 03:25:11 +0000492 ... print(i, v)
Georg Brandl116aa622007-08-15 14:28:22 +0000493 ...
494 0 tic
495 1 tac
496 2 toe
497
498To loop over two or more sequences at the same time, the entries can be paired
499with the :func:`zip` function. ::
500
501 >>> questions = ['name', 'quest', 'favorite color']
502 >>> answers = ['lancelot', 'the holy grail', 'blue']
503 >>> for q, a in zip(questions, answers):
Guido van Rossum0616b792007-08-31 03:25:11 +0000504 ... print('What is your %s? It is %s.' % (q, a))
Georg Brandl116aa622007-08-15 14:28:22 +0000505 ...
506 What is your name? It is lancelot.
507 What is your quest? It is the holy grail.
508 What is your favorite color? It is blue.
509
510To loop over a sequence in reverse, first specify the sequence in a forward
511direction and then call the :func:`reversed` function. ::
512
Georg Brandle4ac7502007-09-03 07:10:24 +0000513 >>> for i in reversed(range(1, 10, 2)):
Guido van Rossum0616b792007-08-31 03:25:11 +0000514 ... print(i)
Georg Brandl116aa622007-08-15 14:28:22 +0000515 ...
516 9
517 7
518 5
519 3
520 1
521
522To loop over a sequence in sorted order, use the :func:`sorted` function which
523returns a new sorted list while leaving the source unaltered. ::
524
525 >>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
526 >>> for f in sorted(set(basket)):
Guido van Rossum0616b792007-08-31 03:25:11 +0000527 ... print(f)
Georg Brandl116aa622007-08-15 14:28:22 +0000528 ...
529 apple
530 banana
531 orange
532 pear
533
534
535.. _tut-conditions:
536
537More on Conditions
538==================
539
540The conditions used in ``while`` and ``if`` statements can contain any
541operators, not just comparisons.
542
543The comparison operators ``in`` and ``not in`` check whether a value occurs
544(does not occur) in a sequence. The operators ``is`` and ``is not`` compare
545whether two objects are really the same object; this only matters for mutable
546objects like lists. All comparison operators have the same priority, which is
547lower than that of all numerical operators.
548
549Comparisons can be chained. For example, ``a < b == c`` tests whether ``a`` is
550less than ``b`` and moreover ``b`` equals ``c``.
551
552Comparisons may be combined using the Boolean operators ``and`` and ``or``, and
553the outcome of a comparison (or of any other Boolean expression) may be negated
554with ``not``. These have lower priorities than comparison operators; between
555them, ``not`` has the highest priority and ``or`` the lowest, so that ``A and
556not B or C`` is equivalent to ``(A and (not B)) or C``. As always, parentheses
557can be used to express the desired composition.
558
559The Boolean operators ``and`` and ``or`` are so-called *short-circuit*
560operators: their arguments are evaluated from left to right, and evaluation
561stops as soon as the outcome is determined. For example, if ``A`` and ``C`` are
562true but ``B`` is false, ``A and B and C`` does not evaluate the expression
563``C``. When used as a general value and not as a Boolean, the return value of a
564short-circuit operator is the last evaluated argument.
565
566It is possible to assign the result of a comparison or other Boolean expression
567to a variable. For example, ::
568
569 >>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance'
570 >>> non_null = string1 or string2 or string3
571 >>> non_null
572 'Trondheim'
573
574Note that in Python, unlike C, assignment cannot occur inside expressions. C
575programmers may grumble about this, but it avoids a common class of problems
576encountered in C programs: typing ``=`` in an expression when ``==`` was
577intended.
578
579
580.. _tut-comparing:
581
582Comparing Sequences and Other Types
583===================================
584
585Sequence objects may be compared to other objects with the same sequence type.
586The comparison uses *lexicographical* ordering: first the first two items are
587compared, and if they differ this determines the outcome of the comparison; if
588they are equal, the next two items are compared, and so on, until either
589sequence is exhausted. If two items to be compared are themselves sequences of
590the same type, the lexicographical comparison is carried out recursively. If
591all items of two sequences compare equal, the sequences are considered equal.
592If one sequence is an initial sub-sequence of the other, the shorter sequence is
593the smaller (lesser) one. Lexicographical ordering for strings uses the ASCII
594ordering for individual characters. Some examples of comparisons between
595sequences of the same type::
596
597 (1, 2, 3) < (1, 2, 4)
598 [1, 2, 3] < [1, 2, 4]
599 'ABC' < 'C' < 'Pascal' < 'Python'
600 (1, 2, 3, 4) < (1, 2, 4)
601 (1, 2) < (1, 2, -1)
602 (1, 2, 3) == (1.0, 2.0, 3.0)
603 (1, 2, ('aa', 'ab')) < (1, 2, ('abc', 'a'), 4)
604
Georg Brandl9f2c39a2007-10-08 14:08:36 +0000605Note that comparing objects of different types with ``<`` or ``>`` is legal
606provided that the objects have appropriate comparison methods. For example,
607mixed numeric types are compared according to their numeric value, so 0 equals
6080.0, etc. Otherwise, rather than providing an arbitrary ordering, the
609interpreter will raise a :exc:`TypeError` exception.