blob: 206f056724de8c3cce24939cff892a4940b1fe4f [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
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000353Tuples and Sequences
354====================
355
356We saw that lists and strings have many common properties, such as indexing and
357slicing operations. They are two examples of *sequence* data types (see
358:ref:`typesseq`). Since Python is an evolving language, other sequence data
359types may be added. There is also another standard sequence data type: the
360*tuple*.
361
362A tuple consists of a number of values separated by commas, for instance::
363
364 >>> t = 12345, 54321, 'hello!'
365 >>> t[0]
366 12345
367 >>> t
368 (12345, 54321, 'hello!')
369 >>> # Tuples may be nested:
370 ... u = t, (1, 2, 3, 4, 5)
371 >>> u
372 ((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))
373
374As you see, on output tuples are always enclosed in parentheses, so that nested
375tuples are interpreted correctly; they may be input with or without surrounding
376parentheses, although often parentheses are necessary anyway (if the tuple is
377part of a larger expression).
378
379Tuples have many uses. For example: (x, y) coordinate pairs, employee records
380from a database, etc. Tuples, like strings, are immutable: it is not possible
381to assign to the individual items of a tuple (you can simulate much of the same
382effect with slicing and concatenation, though). It is also possible to create
383tuples which contain mutable objects, such as lists.
384
385A special problem is the construction of tuples containing 0 or 1 items: the
386syntax has some extra quirks to accommodate these. Empty tuples are constructed
387by an empty pair of parentheses; a tuple with one item is constructed by
388following a value with a comma (it is not sufficient to enclose a single value
389in parentheses). Ugly, but effective. For example::
390
391 >>> empty = ()
392 >>> singleton = 'hello', # <-- note trailing comma
393 >>> len(empty)
394 0
395 >>> len(singleton)
396 1
397 >>> singleton
398 ('hello',)
399
400The statement ``t = 12345, 54321, 'hello!'`` is an example of *tuple packing*:
401the values ``12345``, ``54321`` and ``'hello!'`` are packed together in a tuple.
402The reverse operation is also possible::
403
404 >>> x, y, z = t
405
406This is called, appropriately enough, *sequence unpacking*. Sequence unpacking
407requires the list of variables on the left to have the same number of elements
408as the length of the sequence. Note that multiple assignment is really just a
409combination of tuple packing and sequence unpacking!
410
411There is a small bit of asymmetry here: packing multiple values always creates
412a tuple, and unpacking works for any sequence.
413
414.. XXX Add a bit on the difference between tuples and lists.
415
416
Georg Brandl116aa622007-08-15 14:28:22 +0000417.. _tut-sets:
418
419Sets
420====
421
422Python also includes a data type for *sets*. A set is an unordered collection
423with no duplicate elements. Basic uses include membership testing and
424eliminating duplicate entries. Set objects also support mathematical operations
425like union, intersection, difference, and symmetric difference.
426
Guido van Rossum0616b792007-08-31 03:25:11 +0000427Curly braces or the :func:`set` function can be use to create sets. Note:
428To create an empty set you have to use set(), not {}; the latter creates
429an empty dictionary, a data structure that we discuss in the next section.
430
Georg Brandl116aa622007-08-15 14:28:22 +0000431Here is a brief demonstration::
432
Guido van Rossum0616b792007-08-31 03:25:11 +0000433 >>> basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
434 >>> print(basket)
435 {'orange', 'bananna', 'pear', 'apple'}
436 >>> fruit = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
Georg Brandl116aa622007-08-15 14:28:22 +0000437 >>> fruit = set(basket) # create a set without duplicates
438 >>> fruit
Guido van Rossum0616b792007-08-31 03:25:11 +0000439 {'orange', 'pear', 'apple', 'banana'}
Georg Brandl116aa622007-08-15 14:28:22 +0000440 >>> 'orange' in fruit # fast membership testing
441 True
442 >>> 'crabgrass' in fruit
443 False
444
445 >>> # Demonstrate set operations on unique letters from two words
446 ...
447 >>> a = set('abracadabra')
448 >>> b = set('alacazam')
449 >>> a # unique letters in a
Guido van Rossum0616b792007-08-31 03:25:11 +0000450 {'a', 'r', 'b', 'c', 'd'}
Georg Brandl116aa622007-08-15 14:28:22 +0000451 >>> a - b # letters in a but not in b
Guido van Rossum0616b792007-08-31 03:25:11 +0000452 {'r', 'd', 'b'}
Georg Brandl116aa622007-08-15 14:28:22 +0000453 >>> a | b # letters in either a or b
Guido van Rossum0616b792007-08-31 03:25:11 +0000454 {'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}
Georg Brandl116aa622007-08-15 14:28:22 +0000455 >>> a & b # letters in both a and b
Guido van Rossum0616b792007-08-31 03:25:11 +0000456 {'a', 'c'}
Georg Brandl116aa622007-08-15 14:28:22 +0000457 >>> a ^ b # letters in a or b but not both
Guido van Rossum0616b792007-08-31 03:25:11 +0000458 {'r', 'd', 'b', 'm', 'z', 'l'}
459
460
Georg Brandl116aa622007-08-15 14:28:22 +0000461
462
463.. _tut-dictionaries:
464
465Dictionaries
466============
467
468Another useful data type built into Python is the *dictionary* (see
469:ref:`typesmapping`). Dictionaries are sometimes found in other languages as
470"associative memories" or "associative arrays". Unlike sequences, which are
471indexed by a range of numbers, dictionaries are indexed by *keys*, which can be
472any immutable type; strings and numbers can always be keys. Tuples can be used
473as keys if they contain only strings, numbers, or tuples; if a tuple contains
474any mutable object either directly or indirectly, it cannot be used as a key.
475You can't use lists as keys, since lists can be modified in place using index
476assignments, slice assignments, or methods like :meth:`append` and
477:meth:`extend`.
478
479It is best to think of a dictionary as an unordered set of *key: value* pairs,
480with the requirement that the keys are unique (within one dictionary). A pair of
481braces creates an empty dictionary: ``{}``. Placing a comma-separated list of
482key:value pairs within the braces adds initial key:value pairs to the
483dictionary; this is also the way dictionaries are written on output.
484
485The main operations on a dictionary are storing a value with some key and
486extracting the value given the key. It is also possible to delete a key:value
487pair with ``del``. If you store using a key that is already in use, the old
488value associated with that key is forgotten. It is an error to extract a value
489using a non-existent key.
490
491The :meth:`keys` method of a dictionary object returns a list of all the keys
492used in the dictionary, in arbitrary order (if you want it sorted, just apply
493the :meth:`sort` method to the list of keys). To check whether a single key is
Collin Winter19ab2bd2007-09-10 00:20:46 +0000494in the dictionary, use the :keyword:`in` keyword.
Georg Brandl116aa622007-08-15 14:28:22 +0000495
496Here is a small example using a dictionary::
497
498 >>> tel = {'jack': 4098, 'sape': 4139}
499 >>> tel['guido'] = 4127
500 >>> tel
501 {'sape': 4139, 'guido': 4127, 'jack': 4098}
502 >>> tel['jack']
503 4098
504 >>> del tel['sape']
505 >>> tel['irv'] = 4127
506 >>> tel
507 {'guido': 4127, 'irv': 4127, 'jack': 4098}
Neal Norwitze0906d12007-08-31 03:46:28 +0000508 >>> list(tel.keys())
Georg Brandl116aa622007-08-15 14:28:22 +0000509 ['guido', 'irv', 'jack']
Georg Brandl116aa622007-08-15 14:28:22 +0000510 >>> 'guido' in tel
511 True
Neal Norwitze0906d12007-08-31 03:46:28 +0000512 >>> 'jack' not in tel
513 False
Georg Brandl116aa622007-08-15 14:28:22 +0000514
515The :func:`dict` constructor builds dictionaries directly from lists of
516key-value pairs stored as tuples. When the pairs form a pattern, list
517comprehensions can compactly specify the key-value list. ::
518
519 >>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
520 {'sape': 4139, 'jack': 4098, 'guido': 4127}
521 >>> dict([(x, x**2) for x in (2, 4, 6)]) # use a list comprehension
522 {2: 4, 4: 16, 6: 36}
523
524Later in the tutorial, we will learn about Generator Expressions which are even
525better suited for the task of supplying key-values pairs to the :func:`dict`
526constructor.
527
528When the keys are simple strings, it is sometimes easier to specify pairs using
529keyword arguments::
530
531 >>> dict(sape=4139, guido=4127, jack=4098)
532 {'sape': 4139, 'jack': 4098, 'guido': 4127}
533
534
535.. _tut-loopidioms:
Guido van Rossum0616b792007-08-31 03:25:11 +0000536.. %
537 Find out the right way to do these DUBOIS
Georg Brandl116aa622007-08-15 14:28:22 +0000538
539Looping Techniques
540==================
541
542When looping through dictionaries, the key and corresponding value can be
Neal Norwitze0906d12007-08-31 03:46:28 +0000543retrieved at the same time using the :meth:`items` method. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000544
545 >>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
Neal Norwitze0906d12007-08-31 03:46:28 +0000546 >>> for k, v in knights.items():
Guido van Rossum0616b792007-08-31 03:25:11 +0000547 ... print(k, v)
Georg Brandl116aa622007-08-15 14:28:22 +0000548 ...
549 gallahad the pure
550 robin the brave
551
552When looping through a sequence, the position index and corresponding value can
553be retrieved at the same time using the :func:`enumerate` function. ::
554
555 >>> for i, v in enumerate(['tic', 'tac', 'toe']):
Guido van Rossum0616b792007-08-31 03:25:11 +0000556 ... print(i, v)
Georg Brandl116aa622007-08-15 14:28:22 +0000557 ...
558 0 tic
559 1 tac
560 2 toe
561
562To loop over two or more sequences at the same time, the entries can be paired
563with the :func:`zip` function. ::
564
565 >>> questions = ['name', 'quest', 'favorite color']
566 >>> answers = ['lancelot', 'the holy grail', 'blue']
567 >>> for q, a in zip(questions, answers):
Guido van Rossum0616b792007-08-31 03:25:11 +0000568 ... print('What is your %s? It is %s.' % (q, a))
Georg Brandl116aa622007-08-15 14:28:22 +0000569 ...
570 What is your name? It is lancelot.
571 What is your quest? It is the holy grail.
572 What is your favorite color? It is blue.
573
574To loop over a sequence in reverse, first specify the sequence in a forward
575direction and then call the :func:`reversed` function. ::
576
Georg Brandle4ac7502007-09-03 07:10:24 +0000577 >>> for i in reversed(range(1, 10, 2)):
Guido van Rossum0616b792007-08-31 03:25:11 +0000578 ... print(i)
Georg Brandl116aa622007-08-15 14:28:22 +0000579 ...
580 9
581 7
582 5
583 3
584 1
585
586To loop over a sequence in sorted order, use the :func:`sorted` function which
587returns a new sorted list while leaving the source unaltered. ::
588
589 >>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
590 >>> for f in sorted(set(basket)):
Guido van Rossum0616b792007-08-31 03:25:11 +0000591 ... print(f)
Georg Brandl116aa622007-08-15 14:28:22 +0000592 ...
593 apple
594 banana
595 orange
596 pear
597
598
599.. _tut-conditions:
600
601More on Conditions
602==================
603
604The conditions used in ``while`` and ``if`` statements can contain any
605operators, not just comparisons.
606
607The comparison operators ``in`` and ``not in`` check whether a value occurs
608(does not occur) in a sequence. The operators ``is`` and ``is not`` compare
609whether two objects are really the same object; this only matters for mutable
610objects like lists. All comparison operators have the same priority, which is
611lower than that of all numerical operators.
612
613Comparisons can be chained. For example, ``a < b == c`` tests whether ``a`` is
614less than ``b`` and moreover ``b`` equals ``c``.
615
616Comparisons may be combined using the Boolean operators ``and`` and ``or``, and
617the outcome of a comparison (or of any other Boolean expression) may be negated
618with ``not``. These have lower priorities than comparison operators; between
619them, ``not`` has the highest priority and ``or`` the lowest, so that ``A and
620not B or C`` is equivalent to ``(A and (not B)) or C``. As always, parentheses
621can be used to express the desired composition.
622
623The Boolean operators ``and`` and ``or`` are so-called *short-circuit*
624operators: their arguments are evaluated from left to right, and evaluation
625stops as soon as the outcome is determined. For example, if ``A`` and ``C`` are
626true but ``B`` is false, ``A and B and C`` does not evaluate the expression
627``C``. When used as a general value and not as a Boolean, the return value of a
628short-circuit operator is the last evaluated argument.
629
630It is possible to assign the result of a comparison or other Boolean expression
631to a variable. For example, ::
632
633 >>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance'
634 >>> non_null = string1 or string2 or string3
635 >>> non_null
636 'Trondheim'
637
638Note that in Python, unlike C, assignment cannot occur inside expressions. C
639programmers may grumble about this, but it avoids a common class of problems
640encountered in C programs: typing ``=`` in an expression when ``==`` was
641intended.
642
643
644.. _tut-comparing:
645
646Comparing Sequences and Other Types
647===================================
648
649Sequence objects may be compared to other objects with the same sequence type.
650The comparison uses *lexicographical* ordering: first the first two items are
651compared, and if they differ this determines the outcome of the comparison; if
652they are equal, the next two items are compared, and so on, until either
653sequence is exhausted. If two items to be compared are themselves sequences of
654the same type, the lexicographical comparison is carried out recursively. If
655all items of two sequences compare equal, the sequences are considered equal.
656If one sequence is an initial sub-sequence of the other, the shorter sequence is
657the smaller (lesser) one. Lexicographical ordering for strings uses the ASCII
658ordering for individual characters. Some examples of comparisons between
659sequences of the same type::
660
661 (1, 2, 3) < (1, 2, 4)
662 [1, 2, 3] < [1, 2, 4]
663 'ABC' < 'C' < 'Pascal' < 'Python'
664 (1, 2, 3, 4) < (1, 2, 4)
665 (1, 2) < (1, 2, -1)
666 (1, 2, 3) == (1.0, 2.0, 3.0)
667 (1, 2, ('aa', 'ab')) < (1, 2, ('abc', 'a'), 4)
668
Georg Brandl9f2c39a2007-10-08 14:08:36 +0000669Note that comparing objects of different types with ``<`` or ``>`` is legal
670provided that the objects have appropriate comparison methods. For example,
671mixed numeric types are compared according to their numeric value, so 0 equals
6720.0, etc. Otherwise, rather than providing an arbitrary ordering, the
673interpreter will raise a :exc:`TypeError` exception.