blob: 623986ecd67a35610d9563f6fca3472776e4df96 [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
Georg Brandl116aa622007-08-15 14:28:22 +000010.. _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)
Christian Heimes4fbc72b2008-03-22 00:47:35 +000020 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +000021
22 Add an item to the end of the list; equivalent to ``a[len(a):] = [x]``.
23
24
25.. method:: list.extend(L)
Christian Heimes4fbc72b2008-03-22 00:47:35 +000026 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +000027
28 Extend the list by appending all the items in the given list; equivalent to
29 ``a[len(a):] = L``.
30
31
32.. method:: list.insert(i, x)
Christian Heimes4fbc72b2008-03-22 00:47:35 +000033 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +000034
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)
Christian Heimes4fbc72b2008-03-22 00:47:35 +000041 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +000042
43 Remove the first item from the list whose value is *x*. It is an error if there
44 is no such item.
45
46
47.. method:: list.pop([i])
Christian Heimes4fbc72b2008-03-22 00:47:35 +000048 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +000049
50 Remove the item at the given position in the list, and return it. If no index
51 is specified, ``a.pop()`` removes and returns the last item in the list. (The
52 square brackets around the *i* in the method signature denote that the parameter
53 is optional, not that you should type square brackets at that position. You
54 will see this notation frequently in the Python Library Reference.)
55
56
57.. method:: list.index(x)
Christian Heimes4fbc72b2008-03-22 00:47:35 +000058 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +000059
60 Return the index in the list of the first item whose value is *x*. It is an
61 error if there is no such item.
62
63
64.. method:: list.count(x)
Christian Heimes4fbc72b2008-03-22 00:47:35 +000065 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +000066
67 Return the number of times *x* appears in the list.
68
69
70.. method:: list.sort()
Christian Heimes4fbc72b2008-03-22 00:47:35 +000071 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +000072
73 Sort the items of the list, in place.
74
75
76.. method:: list.reverse()
Christian Heimes4fbc72b2008-03-22 00:47:35 +000077 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +000078
79 Reverse the elements of the list, in place.
80
81An example that uses most of the list methods::
82
83 >>> a = [66.25, 333, 333, 1, 1234.5]
Guido van Rossum0616b792007-08-31 03:25:11 +000084 >>> print(a.count(333), a.count(66.25), a.count('x'))
Georg Brandl116aa622007-08-15 14:28:22 +000085 2 1 0
86 >>> a.insert(2, -1)
87 >>> a.append(333)
88 >>> a
89 [66.25, 333, -1, 333, 1, 1234.5, 333]
90 >>> a.index(333)
91 1
92 >>> a.remove(333)
93 >>> a
94 [66.25, -1, 333, 1, 1234.5, 333]
95 >>> a.reverse()
96 >>> a
97 [333, 1234.5, 1, 333, -1, 66.25]
98 >>> a.sort()
99 >>> a
100 [-1, 1, 66.25, 333, 333, 1234.5]
101
102
103.. _tut-lists-as-stacks:
104
105Using Lists as Stacks
106---------------------
107
108.. sectionauthor:: Ka-Ping Yee <ping@lfw.org>
109
110
111The list methods make it very easy to use a list as a stack, where the last
112element added is the first element retrieved ("last-in, first-out"). To add an
113item to the top of the stack, use :meth:`append`. To retrieve an item from the
114top of the stack, use :meth:`pop` without an explicit index. For example::
115
116 >>> stack = [3, 4, 5]
117 >>> stack.append(6)
118 >>> stack.append(7)
119 >>> stack
120 [3, 4, 5, 6, 7]
121 >>> stack.pop()
122 7
123 >>> stack
124 [3, 4, 5, 6]
125 >>> stack.pop()
126 6
127 >>> stack.pop()
128 5
129 >>> stack
130 [3, 4]
131
132
133.. _tut-lists-as-queues:
134
135Using Lists as Queues
136---------------------
137
138.. sectionauthor:: Ka-Ping Yee <ping@lfw.org>
139
140
141You can also use a list conveniently as a queue, where the first element added
142is the first element retrieved ("first-in, first-out"). To add an item to the
143back of the queue, use :meth:`append`. To retrieve an item from the front of
144the queue, use :meth:`pop` with ``0`` as the index. For example::
145
146 >>> queue = ["Eric", "John", "Michael"]
147 >>> queue.append("Terry") # Terry arrives
148 >>> queue.append("Graham") # Graham arrives
149 >>> queue.pop(0)
150 'Eric'
151 >>> queue.pop(0)
152 'John'
153 >>> queue
154 ['Michael', 'Terry', 'Graham']
155
156
Georg Brandl116aa622007-08-15 14:28:22 +0000157List Comprehensions
158-------------------
159
Guido van Rossum0616b792007-08-31 03:25:11 +0000160List comprehensions provide a concise way to create lists from sequences.
161Common applications are to make lists where each element is the result of
162some operations applied to each member of the sequence, or to create a
163subsequence of those elements that satisfy a certain condition.
164
165
Georg Brandl116aa622007-08-15 14:28:22 +0000166Each list comprehension consists of an expression followed by a :keyword:`for`
167clause, then zero or more :keyword:`for` or :keyword:`if` clauses. The result
168will be a list resulting from evaluating the expression in the context of the
169:keyword:`for` and :keyword:`if` clauses which follow it. If the expression
Guido van Rossum0616b792007-08-31 03:25:11 +0000170would evaluate to a tuple, it must be parenthesized.
171
172Here we take a list of numbers and return a list of three times each number::
173
174 >>> vec = [2, 4, 6]
175 >>> [3*x for x in vec]
176 [6, 12, 18]
177
178Now we get a little fancier::
179
Georg Brandle4ac7502007-09-03 07:10:24 +0000180 >>> [[x, x**2] for x in vec]
Guido van Rossum0616b792007-08-31 03:25:11 +0000181 [[2, 4], [4, 16], [6, 36]]
182
183Here we apply a method call to each item in a sequence::
Georg Brandl116aa622007-08-15 14:28:22 +0000184
185 >>> freshfruit = [' banana', ' loganberry ', 'passion fruit ']
186 >>> [weapon.strip() for weapon in freshfruit]
187 ['banana', 'loganberry', 'passion fruit']
Guido van Rossum0616b792007-08-31 03:25:11 +0000188
Georg Brandle4ac7502007-09-03 07:10:24 +0000189Using the :keyword:`if` clause we can filter the stream::
Guido van Rossum0616b792007-08-31 03:25:11 +0000190
Georg Brandl116aa622007-08-15 14:28:22 +0000191 >>> [3*x for x in vec if x > 3]
192 [12, 18]
193 >>> [3*x for x in vec if x < 2]
194 []
Guido van Rossum0616b792007-08-31 03:25:11 +0000195
196Tuples can often be created without their parentheses, but not here::
197
Georg Brandl116aa622007-08-15 14:28:22 +0000198 >>> [x, x**2 for x in vec] # error - parens required for tuples
199 File "<stdin>", line 1, in ?
200 [x, x**2 for x in vec]
201 ^
202 SyntaxError: invalid syntax
203 >>> [(x, x**2) for x in vec]
204 [(2, 4), (4, 16), (6, 36)]
Guido van Rossum0616b792007-08-31 03:25:11 +0000205
Georg Brandle4ac7502007-09-03 07:10:24 +0000206Here are some nested for loops and other fancy behavior::
Guido van Rossum0616b792007-08-31 03:25:11 +0000207
Georg Brandl116aa622007-08-15 14:28:22 +0000208 >>> vec1 = [2, 4, 6]
209 >>> vec2 = [4, 3, -9]
210 >>> [x*y for x in vec1 for y in vec2]
211 [8, 6, -18, 16, 12, -36, 24, 18, -54]
212 >>> [x+y for x in vec1 for y in vec2]
213 [6, 5, -7, 8, 7, -5, 10, 9, -3]
214 >>> [vec1[i]*vec2[i] for i in range(len(vec1))]
215 [8, 12, -54]
216
Guido van Rossum0616b792007-08-31 03:25:11 +0000217List comprehensions can be applied to complex expressions and nested functions::
Georg Brandl116aa622007-08-15 14:28:22 +0000218
Georg Brandlf6945182008-02-01 11:56:49 +0000219 >>> [str(round(355/113, i)) for i in range(1, 6)]
Georg Brandl116aa622007-08-15 14:28:22 +0000220 ['3.1', '3.14', '3.142', '3.1416', '3.14159']
221
222
Christian Heimes0449f632007-12-15 01:27:15 +0000223Nested List Comprehensions
224--------------------------
225
226If you've got the stomach for it, list comprehensions can be nested. They are a
227powerful tool but -- like all powerful tools -- they need to be used carefully,
228if at all.
229
230Consider the following example of a 3x3 matrix held as a list containing three
231lists, one list per row::
232
233 >>> mat = [
234 ... [1, 2, 3],
235 ... [4, 5, 6],
236 ... [7, 8, 9],
237 ... ]
238
239Now, if you wanted to swap rows and columns, you could use a list
240comprehension::
241
Neal Norwitz752abd02008-05-13 04:55:24 +0000242 >>> print([[row[i] for row in mat] for i in [0, 1, 2]])
Christian Heimes0449f632007-12-15 01:27:15 +0000243 [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
244
245Special care has to be taken for the *nested* list comprehension:
246
247 To avoid apprehension when nesting list comprehensions, read from right to
248 left.
249
250A more verbose version of this snippet shows the flow explicitly::
251
252 for i in [0, 1, 2]:
253 for row in mat:
Neal Norwitz752abd02008-05-13 04:55:24 +0000254 print(row[i], end="")
Benjamin Petersonbfc644b2008-07-05 23:39:56 +0000255 print()
Christian Heimes0449f632007-12-15 01:27:15 +0000256
257In real world, you should prefer builtin functions to complex flow statements.
258The :func:`zip` function would do a great job for this use case::
259
260 >>> zip(*mat)
261 [(1, 4, 7), (2, 5, 8), (3, 6, 9)]
262
263See :ref:`tut-unpacking-arguments` for details on the asterisk in this line.
264
Georg Brandl116aa622007-08-15 14:28:22 +0000265.. _tut-del:
266
267The :keyword:`del` statement
268============================
269
270There is a way to remove an item from a list given its index instead of its
271value: the :keyword:`del` statement. This differs from the :meth:`pop` method
272which returns a value. The :keyword:`del` statement can also be used to remove
273slices from a list or clear the entire list (which we did earlier by assignment
274of an empty list to the slice). For example::
275
276 >>> a = [-1, 1, 66.25, 333, 333, 1234.5]
277 >>> del a[0]
278 >>> a
279 [1, 66.25, 333, 333, 1234.5]
280 >>> del a[2:4]
281 >>> a
282 [1, 66.25, 1234.5]
283 >>> del a[:]
284 >>> a
285 []
286
287:keyword:`del` can also be used to delete entire variables::
288
289 >>> del a
290
291Referencing the name ``a`` hereafter is an error (at least until another value
292is assigned to it). We'll find other uses for :keyword:`del` later.
293
294
Georg Brandl116aa622007-08-15 14:28:22 +0000295
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000296Tuples and Sequences
297====================
298
299We saw that lists and strings have many common properties, such as indexing and
300slicing operations. They are two examples of *sequence* data types (see
301:ref:`typesseq`). Since Python is an evolving language, other sequence data
302types may be added. There is also another standard sequence data type: the
303*tuple*.
304
305A tuple consists of a number of values separated by commas, for instance::
306
307 >>> t = 12345, 54321, 'hello!'
308 >>> t[0]
309 12345
310 >>> t
311 (12345, 54321, 'hello!')
312 >>> # Tuples may be nested:
313 ... u = t, (1, 2, 3, 4, 5)
314 >>> u
315 ((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))
316
317As you see, on output tuples are always enclosed in parentheses, so that nested
318tuples are interpreted correctly; they may be input with or without surrounding
319parentheses, although often parentheses are necessary anyway (if the tuple is
320part of a larger expression).
321
322Tuples have many uses. For example: (x, y) coordinate pairs, employee records
323from a database, etc. Tuples, like strings, are immutable: it is not possible
324to assign to the individual items of a tuple (you can simulate much of the same
325effect with slicing and concatenation, though). It is also possible to create
326tuples which contain mutable objects, such as lists.
327
328A special problem is the construction of tuples containing 0 or 1 items: the
329syntax has some extra quirks to accommodate these. Empty tuples are constructed
330by an empty pair of parentheses; a tuple with one item is constructed by
331following a value with a comma (it is not sufficient to enclose a single value
332in parentheses). Ugly, but effective. For example::
333
334 >>> empty = ()
335 >>> singleton = 'hello', # <-- note trailing comma
336 >>> len(empty)
337 0
338 >>> len(singleton)
339 1
340 >>> singleton
341 ('hello',)
342
343The statement ``t = 12345, 54321, 'hello!'`` is an example of *tuple packing*:
344the values ``12345``, ``54321`` and ``'hello!'`` are packed together in a tuple.
345The reverse operation is also possible::
346
347 >>> x, y, z = t
348
349This is called, appropriately enough, *sequence unpacking*. Sequence unpacking
350requires the list of variables on the left to have the same number of elements
351as the length of the sequence. Note that multiple assignment is really just a
352combination of tuple packing and sequence unpacking!
353
354There is a small bit of asymmetry here: packing multiple values always creates
355a tuple, and unpacking works for any sequence.
356
357.. XXX Add a bit on the difference between tuples and lists.
358
359
Georg Brandl116aa622007-08-15 14:28:22 +0000360.. _tut-sets:
361
362Sets
363====
364
365Python also includes a data type for *sets*. A set is an unordered collection
366with no duplicate elements. Basic uses include membership testing and
367eliminating duplicate entries. Set objects also support mathematical operations
368like union, intersection, difference, and symmetric difference.
369
Guido van Rossum0616b792007-08-31 03:25:11 +0000370Curly braces or the :func:`set` function can be use to create sets. Note:
371To create an empty set you have to use set(), not {}; the latter creates
372an empty dictionary, a data structure that we discuss in the next section.
373
Georg Brandl116aa622007-08-15 14:28:22 +0000374Here is a brief demonstration::
375
Guido van Rossum0616b792007-08-31 03:25:11 +0000376 >>> basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
377 >>> print(basket)
378 {'orange', 'bananna', 'pear', 'apple'}
379 >>> fruit = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
Georg Brandl116aa622007-08-15 14:28:22 +0000380 >>> fruit = set(basket) # create a set without duplicates
381 >>> fruit
Guido van Rossum0616b792007-08-31 03:25:11 +0000382 {'orange', 'pear', 'apple', 'banana'}
Georg Brandlf6945182008-02-01 11:56:49 +0000383 >>> fruit = {'orange', 'apple'} # {} syntax is equivalent to [] for lists
384 >>> fruit
385 {'orange', 'apple'}
Georg Brandl116aa622007-08-15 14:28:22 +0000386 >>> 'orange' in fruit # fast membership testing
387 True
388 >>> 'crabgrass' in fruit
389 False
390
391 >>> # Demonstrate set operations on unique letters from two words
392 ...
393 >>> a = set('abracadabra')
394 >>> b = set('alacazam')
395 >>> a # unique letters in a
Guido van Rossum0616b792007-08-31 03:25:11 +0000396 {'a', 'r', 'b', 'c', 'd'}
Georg Brandl116aa622007-08-15 14:28:22 +0000397 >>> a - b # letters in a but not in b
Guido van Rossum0616b792007-08-31 03:25:11 +0000398 {'r', 'd', 'b'}
Georg Brandl116aa622007-08-15 14:28:22 +0000399 >>> a | b # letters in either a or b
Guido van Rossum0616b792007-08-31 03:25:11 +0000400 {'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}
Georg Brandl116aa622007-08-15 14:28:22 +0000401 >>> a & b # letters in both a and b
Guido van Rossum0616b792007-08-31 03:25:11 +0000402 {'a', 'c'}
Georg Brandl116aa622007-08-15 14:28:22 +0000403 >>> a ^ b # letters in a or b but not both
Guido van Rossum0616b792007-08-31 03:25:11 +0000404 {'r', 'd', 'b', 'm', 'z', 'l'}
405
Georg Brandlf6945182008-02-01 11:56:49 +0000406Like for lists, there is a set comprehension syntax::
407
408 >>> a = {x for x in 'abracadabra' if x not in 'abc'}
409 >>> a
410 {'r', 'd'}
Guido van Rossum0616b792007-08-31 03:25:11 +0000411
Georg Brandl116aa622007-08-15 14:28:22 +0000412
413
414.. _tut-dictionaries:
415
416Dictionaries
417============
418
419Another useful data type built into Python is the *dictionary* (see
420:ref:`typesmapping`). Dictionaries are sometimes found in other languages as
421"associative memories" or "associative arrays". Unlike sequences, which are
422indexed by a range of numbers, dictionaries are indexed by *keys*, which can be
423any immutable type; strings and numbers can always be keys. Tuples can be used
424as keys if they contain only strings, numbers, or tuples; if a tuple contains
425any mutable object either directly or indirectly, it cannot be used as a key.
426You can't use lists as keys, since lists can be modified in place using index
427assignments, slice assignments, or methods like :meth:`append` and
428:meth:`extend`.
429
430It is best to think of a dictionary as an unordered set of *key: value* pairs,
431with the requirement that the keys are unique (within one dictionary). A pair of
432braces creates an empty dictionary: ``{}``. Placing a comma-separated list of
433key:value pairs within the braces adds initial key:value pairs to the
434dictionary; this is also the way dictionaries are written on output.
435
436The main operations on a dictionary are storing a value with some key and
437extracting the value given the key. It is also possible to delete a key:value
438pair with ``del``. If you store using a key that is already in use, the old
439value associated with that key is forgotten. It is an error to extract a value
440using a non-existent key.
441
442The :meth:`keys` method of a dictionary object returns a list of all the keys
443used in the dictionary, in arbitrary order (if you want it sorted, just apply
444the :meth:`sort` method to the list of keys). To check whether a single key is
Collin Winter19ab2bd2007-09-10 00:20:46 +0000445in the dictionary, use the :keyword:`in` keyword.
Georg Brandl116aa622007-08-15 14:28:22 +0000446
447Here is a small example using a dictionary::
448
449 >>> tel = {'jack': 4098, 'sape': 4139}
450 >>> tel['guido'] = 4127
451 >>> tel
452 {'sape': 4139, 'guido': 4127, 'jack': 4098}
453 >>> tel['jack']
454 4098
455 >>> del tel['sape']
456 >>> tel['irv'] = 4127
457 >>> tel
458 {'guido': 4127, 'irv': 4127, 'jack': 4098}
Neal Norwitze0906d12007-08-31 03:46:28 +0000459 >>> list(tel.keys())
Georg Brandl116aa622007-08-15 14:28:22 +0000460 ['guido', 'irv', 'jack']
Georg Brandl116aa622007-08-15 14:28:22 +0000461 >>> 'guido' in tel
462 True
Neal Norwitze0906d12007-08-31 03:46:28 +0000463 >>> 'jack' not in tel
464 False
Georg Brandl116aa622007-08-15 14:28:22 +0000465
466The :func:`dict` constructor builds dictionaries directly from lists of
467key-value pairs stored as tuples. When the pairs form a pattern, list
468comprehensions can compactly specify the key-value list. ::
469
470 >>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
471 {'sape': 4139, 'jack': 4098, 'guido': 4127}
Georg Brandl116aa622007-08-15 14:28:22 +0000472
Georg Brandlf6945182008-02-01 11:56:49 +0000473In addition, dict comprehensions can be used to create dictionaries from
474arbitrary key and value expressions::
475
476 >>> {x: x**2 for x in (2, 4, 6)}
477 {2: 4, 4: 16, 6: 36}
Georg Brandl116aa622007-08-15 14:28:22 +0000478
479When the keys are simple strings, it is sometimes easier to specify pairs using
480keyword arguments::
481
482 >>> dict(sape=4139, guido=4127, jack=4098)
483 {'sape': 4139, 'jack': 4098, 'guido': 4127}
484
485
Georg Brandlf6945182008-02-01 11:56:49 +0000486.. XXX Find out the right way to do these DUBOIS
Georg Brandl116aa622007-08-15 14:28:22 +0000487.. _tut-loopidioms:
488
489Looping Techniques
490==================
491
492When looping through dictionaries, the key and corresponding value can be
Neal Norwitze0906d12007-08-31 03:46:28 +0000493retrieved at the same time using the :meth:`items` method. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000494
495 >>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
Neal Norwitze0906d12007-08-31 03:46:28 +0000496 >>> for k, v in knights.items():
Guido van Rossum0616b792007-08-31 03:25:11 +0000497 ... print(k, v)
Georg Brandl116aa622007-08-15 14:28:22 +0000498 ...
499 gallahad the pure
500 robin the brave
501
502When looping through a sequence, the position index and corresponding value can
503be retrieved at the same time using the :func:`enumerate` function. ::
504
505 >>> for i, v in enumerate(['tic', 'tac', 'toe']):
Guido van Rossum0616b792007-08-31 03:25:11 +0000506 ... print(i, v)
Georg Brandl116aa622007-08-15 14:28:22 +0000507 ...
508 0 tic
509 1 tac
510 2 toe
511
512To loop over two or more sequences at the same time, the entries can be paired
513with the :func:`zip` function. ::
514
515 >>> questions = ['name', 'quest', 'favorite color']
516 >>> answers = ['lancelot', 'the holy grail', 'blue']
517 >>> for q, a in zip(questions, answers):
Benjamin Petersone6f00632008-05-26 01:03:56 +0000518 ... print('What is your {0}? It is {1}.'.format(q, a))
Georg Brandl116aa622007-08-15 14:28:22 +0000519 ...
520 What is your name? It is lancelot.
521 What is your quest? It is the holy grail.
522 What is your favorite color? It is blue.
523
524To loop over a sequence in reverse, first specify the sequence in a forward
525direction and then call the :func:`reversed` function. ::
526
Georg Brandle4ac7502007-09-03 07:10:24 +0000527 >>> for i in reversed(range(1, 10, 2)):
Guido van Rossum0616b792007-08-31 03:25:11 +0000528 ... print(i)
Georg Brandl116aa622007-08-15 14:28:22 +0000529 ...
530 9
531 7
532 5
533 3
534 1
535
536To loop over a sequence in sorted order, use the :func:`sorted` function which
537returns a new sorted list while leaving the source unaltered. ::
538
539 >>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
540 >>> for f in sorted(set(basket)):
Guido van Rossum0616b792007-08-31 03:25:11 +0000541 ... print(f)
Georg Brandl116aa622007-08-15 14:28:22 +0000542 ...
543 apple
544 banana
545 orange
546 pear
547
548
549.. _tut-conditions:
550
551More on Conditions
552==================
553
554The conditions used in ``while`` and ``if`` statements can contain any
555operators, not just comparisons.
556
557The comparison operators ``in`` and ``not in`` check whether a value occurs
558(does not occur) in a sequence. The operators ``is`` and ``is not`` compare
559whether two objects are really the same object; this only matters for mutable
560objects like lists. All comparison operators have the same priority, which is
561lower than that of all numerical operators.
562
563Comparisons can be chained. For example, ``a < b == c`` tests whether ``a`` is
564less than ``b`` and moreover ``b`` equals ``c``.
565
566Comparisons may be combined using the Boolean operators ``and`` and ``or``, and
567the outcome of a comparison (or of any other Boolean expression) may be negated
568with ``not``. These have lower priorities than comparison operators; between
569them, ``not`` has the highest priority and ``or`` the lowest, so that ``A and
570not B or C`` is equivalent to ``(A and (not B)) or C``. As always, parentheses
571can be used to express the desired composition.
572
573The Boolean operators ``and`` and ``or`` are so-called *short-circuit*
574operators: their arguments are evaluated from left to right, and evaluation
575stops as soon as the outcome is determined. For example, if ``A`` and ``C`` are
576true but ``B`` is false, ``A and B and C`` does not evaluate the expression
577``C``. When used as a general value and not as a Boolean, the return value of a
578short-circuit operator is the last evaluated argument.
579
580It is possible to assign the result of a comparison or other Boolean expression
581to a variable. For example, ::
582
583 >>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance'
584 >>> non_null = string1 or string2 or string3
585 >>> non_null
586 'Trondheim'
587
588Note that in Python, unlike C, assignment cannot occur inside expressions. C
589programmers may grumble about this, but it avoids a common class of problems
590encountered in C programs: typing ``=`` in an expression when ``==`` was
591intended.
592
593
594.. _tut-comparing:
595
596Comparing Sequences and Other Types
597===================================
598
599Sequence objects may be compared to other objects with the same sequence type.
600The comparison uses *lexicographical* ordering: first the first two items are
601compared, and if they differ this determines the outcome of the comparison; if
602they are equal, the next two items are compared, and so on, until either
603sequence is exhausted. If two items to be compared are themselves sequences of
604the same type, the lexicographical comparison is carried out recursively. If
605all items of two sequences compare equal, the sequences are considered equal.
606If one sequence is an initial sub-sequence of the other, the shorter sequence is
607the smaller (lesser) one. Lexicographical ordering for strings uses the ASCII
608ordering for individual characters. Some examples of comparisons between
609sequences of the same type::
610
611 (1, 2, 3) < (1, 2, 4)
612 [1, 2, 3] < [1, 2, 4]
613 'ABC' < 'C' < 'Pascal' < 'Python'
614 (1, 2, 3, 4) < (1, 2, 4)
615 (1, 2) < (1, 2, -1)
616 (1, 2, 3) == (1.0, 2.0, 3.0)
617 (1, 2, ('aa', 'ab')) < (1, 2, ('abc', 'a'), 4)
618
Georg Brandl9f2c39a2007-10-08 14:08:36 +0000619Note that comparing objects of different types with ``<`` or ``>`` is legal
620provided that the objects have appropriate comparison methods. For example,
621mixed numeric types are compared according to their numeric value, so 0 equals
6220.0, etc. Otherwise, rather than providing an arbitrary ordering, the
623interpreter will raise a :exc:`TypeError` exception.