blob: 97e0ee84e936249ef10d0424b9543cdfd66d7f44 [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
Ezio Melottieb729912010-03-31 07:26:24 +0000141It is also possible to use a list as a queue, where the first element added is
142the first element retrieved ("first-in, first-out"); however, lists are not
143efficient for this purpose. While appends and pops from the end of list are
144fast, doing inserts or pops from the beginning of a list is slow (because all
145of the other elements have to be shifted by one).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000146
Ezio Melottieb729912010-03-31 07:26:24 +0000147To implement a queue, use :class:`collections.deque` which was designed to
148have fast appends and pops from both ends. For example::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000149
Ezio Melottieb729912010-03-31 07:26:24 +0000150 >>> from collections import deque
151 >>> queue = deque(["Eric", "John", "Michael"])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000152 >>> queue.append("Terry") # Terry arrives
153 >>> queue.append("Graham") # Graham arrives
Ezio Melottieb729912010-03-31 07:26:24 +0000154 >>> queue.popleft() # The first to arrive now leaves
Georg Brandl8ec7f652007-08-15 14:28:01 +0000155 'Eric'
Ezio Melottieb729912010-03-31 07:26:24 +0000156 >>> queue.popleft() # The second to arrive now leaves
Georg Brandl8ec7f652007-08-15 14:28:01 +0000157 'John'
Ezio Melottieb729912010-03-31 07:26:24 +0000158 >>> queue # Remaining queue in order of arrival
159 deque(['Michael', 'Terry', 'Graham'])
Georg Brandla39f2af2010-03-21 09:37:54 +0000160
Georg Brandl8ec7f652007-08-15 14:28:01 +0000161
162.. _tut-functional:
163
164Functional Programming Tools
165----------------------------
166
167There are three built-in functions that are very useful when used with lists:
168:func:`filter`, :func:`map`, and :func:`reduce`.
169
170``filter(function, sequence)`` returns a sequence consisting of those items from
171the sequence for which ``function(item)`` is true. If *sequence* is a
172:class:`string` or :class:`tuple`, the result will be of the same type;
Senthil Kumaran169fa932011-09-29 07:52:46 +0800173otherwise, it is always a :class:`list`. For example, to compute a sequence of
174numbers not divisible by 2 and 3::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000175
176 >>> def f(x): return x % 2 != 0 and x % 3 != 0
177 ...
178 >>> filter(f, range(2, 25))
179 [5, 7, 11, 13, 17, 19, 23]
180
181``map(function, sequence)`` calls ``function(item)`` for each of the sequence's
182items and returns a list of the return values. For example, to compute some
183cubes::
184
185 >>> def cube(x): return x*x*x
186 ...
187 >>> map(cube, range(1, 11))
188 [1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
189
190More than one sequence may be passed; the function must then have as many
191arguments as there are sequences and is called with the corresponding item from
192each sequence (or ``None`` if some sequence is shorter than another). For
193example::
194
195 >>> seq = range(8)
196 >>> def add(x, y): return x+y
197 ...
198 >>> map(add, seq, seq)
199 [0, 2, 4, 6, 8, 10, 12, 14]
200
201``reduce(function, sequence)`` returns a single value constructed by calling the
202binary function *function* on the first two items of the sequence, then on the
203result and the next item, and so on. For example, to compute the sum of the
204numbers 1 through 10::
205
206 >>> def add(x,y): return x+y
207 ...
208 >>> reduce(add, range(1, 11))
209 55
210
211If there's only one item in the sequence, its value is returned; if the sequence
212is empty, an exception is raised.
213
214A third argument can be passed to indicate the starting value. In this case the
215starting value is returned for an empty sequence, and the function is first
216applied to the starting value and the first sequence item, then to the result
217and the next item, and so on. For example, ::
218
219 >>> def sum(seq):
220 ... def add(x,y): return x+y
221 ... return reduce(add, seq, 0)
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000222 ...
Georg Brandl8ec7f652007-08-15 14:28:01 +0000223 >>> sum(range(1, 11))
224 55
225 >>> sum([])
226 0
227
228Don't use this example's definition of :func:`sum`: since summing numbers is
229such a common need, a built-in function ``sum(sequence)`` is already provided,
230and works exactly like this.
231
232.. versionadded:: 2.3
233
234
235List Comprehensions
236-------------------
237
238List comprehensions provide a concise way to create lists without resorting to
239use of :func:`map`, :func:`filter` and/or :keyword:`lambda`. The resulting list
240definition tends often to be clearer than lists built using those constructs.
241Each list comprehension consists of an expression followed by a :keyword:`for`
242clause, then zero or more :keyword:`for` or :keyword:`if` clauses. The result
243will be a list resulting from evaluating the expression in the context of the
244:keyword:`for` and :keyword:`if` clauses which follow it. If the expression
245would evaluate to a tuple, it must be parenthesized. ::
246
247 >>> freshfruit = [' banana', ' loganberry ', 'passion fruit ']
248 >>> [weapon.strip() for weapon in freshfruit]
249 ['banana', 'loganberry', 'passion fruit']
250 >>> vec = [2, 4, 6]
251 >>> [3*x for x in vec]
252 [6, 12, 18]
253 >>> [3*x for x in vec if x > 3]
254 [12, 18]
255 >>> [3*x for x in vec if x < 2]
256 []
257 >>> [[x,x**2] for x in vec]
258 [[2, 4], [4, 16], [6, 36]]
Georg Brandl7044b112009-01-03 21:04:55 +0000259 >>> [x, x**2 for x in vec] # error - parens required for tuples
Georg Brandl8ec7f652007-08-15 14:28:01 +0000260 File "<stdin>", line 1, in ?
261 [x, x**2 for x in vec]
262 ^
263 SyntaxError: invalid syntax
264 >>> [(x, x**2) for x in vec]
265 [(2, 4), (4, 16), (6, 36)]
266 >>> vec1 = [2, 4, 6]
267 >>> vec2 = [4, 3, -9]
268 >>> [x*y for x in vec1 for y in vec2]
269 [8, 6, -18, 16, 12, -36, 24, 18, -54]
270 >>> [x+y for x in vec1 for y in vec2]
271 [6, 5, -7, 8, 7, -5, 10, 9, -3]
272 >>> [vec1[i]*vec2[i] for i in range(len(vec1))]
273 [8, 12, -54]
274
275List comprehensions are much more flexible than :func:`map` and can be applied
276to complex expressions and nested functions::
277
278 >>> [str(round(355/113.0, i)) for i in range(1,6)]
279 ['3.1', '3.14', '3.142', '3.1416', '3.14159']
280
281
Georg Brandladbda842007-12-14 19:03:36 +0000282Nested List Comprehensions
283--------------------------
284
285If you've got the stomach for it, list comprehensions can be nested. They are a
286powerful tool but -- like all powerful tools -- they need to be used carefully,
287if at all.
288
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000289Consider the following example of a 3x3 matrix held as a list containing three
Georg Brandladbda842007-12-14 19:03:36 +0000290lists, one list per row::
291
292 >>> mat = [
293 ... [1, 2, 3],
294 ... [4, 5, 6],
295 ... [7, 8, 9],
296 ... ]
297
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000298Now, if you wanted to swap rows and columns, you could use a list
Georg Brandladbda842007-12-14 19:03:36 +0000299comprehension::
300
301 >>> print [[row[i] for row in mat] for i in [0, 1, 2]]
302 [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
303
304Special care has to be taken for the *nested* list comprehension:
305
306 To avoid apprehension when nesting list comprehensions, read from right to
307 left.
308
309A more verbose version of this snippet shows the flow explicitly::
310
311 for i in [0, 1, 2]:
312 for row in mat:
313 print row[i],
314 print
315
Mark Dickinson3e4caeb2009-02-21 20:27:01 +0000316In real world, you should prefer built-in functions to complex flow statements.
Georg Brandladbda842007-12-14 19:03:36 +0000317The :func:`zip` function would do a great job for this use case::
318
319 >>> zip(*mat)
320 [(1, 4, 7), (2, 5, 8), (3, 6, 9)]
321
322See :ref:`tut-unpacking-arguments` for details on the asterisk in this line.
323
Georg Brandl8ec7f652007-08-15 14:28:01 +0000324.. _tut-del:
325
326The :keyword:`del` statement
327============================
328
329There is a way to remove an item from a list given its index instead of its
330value: the :keyword:`del` statement. This differs from the :meth:`pop` method
331which returns a value. The :keyword:`del` statement can also be used to remove
332slices from a list or clear the entire list (which we did earlier by assignment
333of an empty list to the slice). For example::
334
335 >>> a = [-1, 1, 66.25, 333, 333, 1234.5]
336 >>> del a[0]
337 >>> a
338 [1, 66.25, 333, 333, 1234.5]
339 >>> del a[2:4]
340 >>> a
341 [1, 66.25, 1234.5]
342 >>> del a[:]
343 >>> a
344 []
345
346:keyword:`del` can also be used to delete entire variables::
347
348 >>> del a
349
350Referencing the name ``a`` hereafter is an error (at least until another value
351is assigned to it). We'll find other uses for :keyword:`del` later.
352
353
354.. _tut-tuples:
355
356Tuples and Sequences
357====================
358
359We saw that lists and strings have many common properties, such as indexing and
360slicing operations. They are two examples of *sequence* data types (see
361:ref:`typesseq`). Since Python is an evolving language, other sequence data
362types may be added. There is also another standard sequence data type: the
363*tuple*.
364
365A tuple consists of a number of values separated by commas, for instance::
366
367 >>> t = 12345, 54321, 'hello!'
368 >>> t[0]
369 12345
370 >>> t
371 (12345, 54321, 'hello!')
372 >>> # Tuples may be nested:
373 ... u = t, (1, 2, 3, 4, 5)
374 >>> u
375 ((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))
376
377As you see, on output tuples are always enclosed in parentheses, so that nested
378tuples are interpreted correctly; they may be input with or without surrounding
379parentheses, although often parentheses are necessary anyway (if the tuple is
380part of a larger expression).
381
382Tuples have many uses. For example: (x, y) coordinate pairs, employee records
383from a database, etc. Tuples, like strings, are immutable: it is not possible
384to assign to the individual items of a tuple (you can simulate much of the same
385effect with slicing and concatenation, though). It is also possible to create
386tuples which contain mutable objects, such as lists.
387
388A special problem is the construction of tuples containing 0 or 1 items: the
389syntax has some extra quirks to accommodate these. Empty tuples are constructed
390by an empty pair of parentheses; a tuple with one item is constructed by
391following a value with a comma (it is not sufficient to enclose a single value
392in parentheses). Ugly, but effective. For example::
393
394 >>> empty = ()
395 >>> singleton = 'hello', # <-- note trailing comma
396 >>> len(empty)
397 0
398 >>> len(singleton)
399 1
400 >>> singleton
401 ('hello',)
402
403The statement ``t = 12345, 54321, 'hello!'`` is an example of *tuple packing*:
404the values ``12345``, ``54321`` and ``'hello!'`` are packed together in a tuple.
405The reverse operation is also possible::
406
407 >>> x, y, z = t
408
Georg Brandl354e4cb2009-03-31 22:40:16 +0000409This is called, appropriately enough, *sequence unpacking* and works for any
410sequence on the right-hand side. Sequence unpacking requires the list of
411variables on the left to have the same number of elements as the length of the
412sequence. Note that multiple assignment is really just a combination of tuple
Georg Brandla08867d2009-03-31 23:01:27 +0000413packing and sequence unpacking.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000414
Georg Brandlb19be572007-12-29 10:57:00 +0000415.. XXX Add a bit on the difference between tuples and lists.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000416
417
418.. _tut-sets:
419
420Sets
421====
422
423Python also includes a data type for *sets*. A set is an unordered collection
424with no duplicate elements. Basic uses include membership testing and
425eliminating duplicate entries. Set objects also support mathematical operations
426like union, intersection, difference, and symmetric difference.
427
428Here is a brief demonstration::
429
430 >>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
431 >>> fruit = set(basket) # create a set without duplicates
432 >>> fruit
433 set(['orange', 'pear', 'apple', 'banana'])
434 >>> 'orange' in fruit # fast membership testing
435 True
436 >>> 'crabgrass' in fruit
437 False
438
439 >>> # Demonstrate set operations on unique letters from two words
440 ...
441 >>> a = set('abracadabra')
442 >>> b = set('alacazam')
443 >>> a # unique letters in a
444 set(['a', 'r', 'b', 'c', 'd'])
445 >>> a - b # letters in a but not in b
446 set(['r', 'd', 'b'])
447 >>> a | b # letters in either a or b
448 set(['a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'])
449 >>> a & b # letters in both a and b
450 set(['a', 'c'])
451 >>> a ^ b # letters in a or b but not both
452 set(['r', 'd', 'b', 'm', 'z', 'l'])
453
454
455.. _tut-dictionaries:
456
457Dictionaries
458============
459
460Another useful data type built into Python is the *dictionary* (see
461:ref:`typesmapping`). Dictionaries are sometimes found in other languages as
462"associative memories" or "associative arrays". Unlike sequences, which are
463indexed by a range of numbers, dictionaries are indexed by *keys*, which can be
464any immutable type; strings and numbers can always be keys. Tuples can be used
465as keys if they contain only strings, numbers, or tuples; if a tuple contains
466any mutable object either directly or indirectly, it cannot be used as a key.
467You can't use lists as keys, since lists can be modified in place using index
468assignments, slice assignments, or methods like :meth:`append` and
469:meth:`extend`.
470
471It is best to think of a dictionary as an unordered set of *key: value* pairs,
472with the requirement that the keys are unique (within one dictionary). A pair of
473braces creates an empty dictionary: ``{}``. Placing a comma-separated list of
474key:value pairs within the braces adds initial key:value pairs to the
475dictionary; this is also the way dictionaries are written on output.
476
477The main operations on a dictionary are storing a value with some key and
478extracting the value given the key. It is also possible to delete a key:value
479pair with ``del``. If you store using a key that is already in use, the old
480value associated with that key is forgotten. It is an error to extract a value
481using a non-existent key.
482
483The :meth:`keys` method of a dictionary object returns a list of all the keys
484used in the dictionary, in arbitrary order (if you want it sorted, just apply
Georg Brandl44c3ceb2010-10-15 15:31:09 +0000485the :func:`sorted` function to it). To check whether a single key is in the
486dictionary, use the :keyword:`in` keyword.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000487
488Here is a small example using a dictionary::
489
490 >>> tel = {'jack': 4098, 'sape': 4139}
491 >>> tel['guido'] = 4127
492 >>> tel
493 {'sape': 4139, 'guido': 4127, 'jack': 4098}
494 >>> tel['jack']
495 4098
496 >>> del tel['sape']
497 >>> tel['irv'] = 4127
498 >>> tel
499 {'guido': 4127, 'irv': 4127, 'jack': 4098}
500 >>> tel.keys()
501 ['guido', 'irv', 'jack']
Georg Brandl8ec7f652007-08-15 14:28:01 +0000502 >>> 'guido' in tel
503 True
504
505The :func:`dict` constructor builds dictionaries directly from lists of
506key-value pairs stored as tuples. When the pairs form a pattern, list
507comprehensions can compactly specify the key-value list. ::
508
509 >>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
510 {'sape': 4139, 'jack': 4098, 'guido': 4127}
511 >>> dict([(x, x**2) for x in (2, 4, 6)]) # use a list comprehension
512 {2: 4, 4: 16, 6: 36}
513
514Later in the tutorial, we will learn about Generator Expressions which are even
515better suited for the task of supplying key-values pairs to the :func:`dict`
516constructor.
517
518When the keys are simple strings, it is sometimes easier to specify pairs using
519keyword arguments::
520
521 >>> dict(sape=4139, guido=4127, jack=4098)
522 {'sape': 4139, 'jack': 4098, 'guido': 4127}
523
524
525.. _tut-loopidioms:
526
527Looping Techniques
528==================
529
530When looping through dictionaries, the key and corresponding value can be
531retrieved at the same time using the :meth:`iteritems` method. ::
532
533 >>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
534 >>> for k, v in knights.iteritems():
535 ... print k, v
536 ...
537 gallahad the pure
538 robin the brave
539
540When looping through a sequence, the position index and corresponding value can
541be retrieved at the same time using the :func:`enumerate` function. ::
542
543 >>> for i, v in enumerate(['tic', 'tac', 'toe']):
544 ... print i, v
545 ...
546 0 tic
547 1 tac
548 2 toe
549
550To loop over two or more sequences at the same time, the entries can be paired
551with the :func:`zip` function. ::
552
553 >>> questions = ['name', 'quest', 'favorite color']
554 >>> answers = ['lancelot', 'the holy grail', 'blue']
555 >>> for q, a in zip(questions, answers):
Benjamin Petersonf9ef9882008-05-26 00:54:22 +0000556 ... print 'What is your {0}? It is {1}.'.format(q, a)
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000557 ...
Georg Brandl8ec7f652007-08-15 14:28:01 +0000558 What is your name? It is lancelot.
559 What is your quest? It is the holy grail.
560 What is your favorite color? It is blue.
561
562To loop over a sequence in reverse, first specify the sequence in a forward
563direction and then call the :func:`reversed` function. ::
564
565 >>> for i in reversed(xrange(1,10,2)):
566 ... print i
567 ...
568 9
569 7
570 5
571 3
572 1
573
574To loop over a sequence in sorted order, use the :func:`sorted` function which
575returns a new sorted list while leaving the source unaltered. ::
576
577 >>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
578 >>> for f in sorted(set(basket)):
579 ... print f
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000580 ...
Georg Brandl8ec7f652007-08-15 14:28:01 +0000581 apple
582 banana
583 orange
584 pear
585
586
587.. _tut-conditions:
588
589More on Conditions
590==================
591
592The conditions used in ``while`` and ``if`` statements can contain any
593operators, not just comparisons.
594
595The comparison operators ``in`` and ``not in`` check whether a value occurs
596(does not occur) in a sequence. The operators ``is`` and ``is not`` compare
597whether two objects are really the same object; this only matters for mutable
598objects like lists. All comparison operators have the same priority, which is
599lower than that of all numerical operators.
600
601Comparisons can be chained. For example, ``a < b == c`` tests whether ``a`` is
602less than ``b`` and moreover ``b`` equals ``c``.
603
604Comparisons may be combined using the Boolean operators ``and`` and ``or``, and
605the outcome of a comparison (or of any other Boolean expression) may be negated
606with ``not``. These have lower priorities than comparison operators; between
607them, ``not`` has the highest priority and ``or`` the lowest, so that ``A and
608not B or C`` is equivalent to ``(A and (not B)) or C``. As always, parentheses
609can be used to express the desired composition.
610
611The Boolean operators ``and`` and ``or`` are so-called *short-circuit*
612operators: their arguments are evaluated from left to right, and evaluation
613stops as soon as the outcome is determined. For example, if ``A`` and ``C`` are
614true but ``B`` is false, ``A and B and C`` does not evaluate the expression
615``C``. When used as a general value and not as a Boolean, the return value of a
616short-circuit operator is the last evaluated argument.
617
618It is possible to assign the result of a comparison or other Boolean expression
619to a variable. For example, ::
620
621 >>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance'
622 >>> non_null = string1 or string2 or string3
623 >>> non_null
624 'Trondheim'
625
626Note that in Python, unlike C, assignment cannot occur inside expressions. C
627programmers may grumble about this, but it avoids a common class of problems
628encountered in C programs: typing ``=`` in an expression when ``==`` was
629intended.
630
631
632.. _tut-comparing:
633
634Comparing Sequences and Other Types
635===================================
636
637Sequence objects may be compared to other objects with the same sequence type.
638The comparison uses *lexicographical* ordering: first the first two items are
639compared, and if they differ this determines the outcome of the comparison; if
640they are equal, the next two items are compared, and so on, until either
641sequence is exhausted. If two items to be compared are themselves sequences of
642the same type, the lexicographical comparison is carried out recursively. If
643all items of two sequences compare equal, the sequences are considered equal.
644If one sequence is an initial sub-sequence of the other, the shorter sequence is
645the smaller (lesser) one. Lexicographical ordering for strings uses the ASCII
646ordering for individual characters. Some examples of comparisons between
647sequences of the same type::
648
649 (1, 2, 3) < (1, 2, 4)
650 [1, 2, 3] < [1, 2, 4]
651 'ABC' < 'C' < 'Pascal' < 'Python'
652 (1, 2, 3, 4) < (1, 2, 4)
653 (1, 2) < (1, 2, -1)
654 (1, 2, 3) == (1.0, 2.0, 3.0)
655 (1, 2, ('aa', 'ab')) < (1, 2, ('abc', 'a'), 4)
656
657Note that comparing objects of different types is legal. The outcome is
658deterministic but arbitrary: the types are ordered by their name. Thus, a list
659is always smaller than a string, a string is always smaller than a tuple, etc.
660[#]_ Mixed numeric types are compared according to their numeric value, so 0
661equals 0.0, etc.
662
663
664.. rubric:: Footnotes
665
666.. [#] The rules for comparing objects of different types should not be relied upon;
667 they may change in a future version of the language.
668