Debian Codegraph @

Doc/tutorial/datastructures.rst

raw
1 .. _tut-structures:
2
3 ***************
4 Data Structures
5 ***************
6
7 This chapter describes some things you've learned about already in more detail,
8 and adds some new things as well.
9
10 .. _tut-morelists:
11
12 More on Lists
13 =============
14
15 The :ref:`list <typesseq-list>` data type has some more methods. Here are all
16 of the methods of list objects:
17
18 .. method:: list.append(x)
19 :noindex:
20
21 Add an item to the end of the list. Similar to ``a[len(a):] = [x]``.
22
23
24 .. method:: list.extend(iterable)
25 :noindex:
26
27 Extend the list by appending all the items from the iterable. Similar to
28 ``a[len(a):] = iterable``.
29
30
31 .. method:: list.insert(i, x)
32 :noindex:
33
34 Insert an item at a given position. The first argument is the index of the
35 element before which to insert, so ``a.insert(0, x)`` inserts at the front of
36 the list, and ``a.insert(len(a), x)`` is equivalent to ``a.append(x)``.
37
38
39 .. method:: list.remove(x)
40 :noindex:
41
42 Remove the first item from the list whose value is equal to *x*. It raises a
43 :exc:`ValueError` if there is no such item.
44
45
46 .. method:: list.pop([i])
47 :noindex:
48
49 Remove the item at the given position in the list, and return it. If no index
50 is specified, ``a.pop()`` removes and returns the last item in the list.
51 It raises an :exc:`IndexError` if the list is empty or the index is
52 outside the list range.
53
54
55 .. method:: list.clear()
56 :noindex:
57
58 Remove all items from the list. Similar to ``del a[:]``.
59
60
61 .. method:: list.index(x[, start[, end]])
62 :noindex:
63
64 Return zero-based index of the first occurrence of *x* in the list.
65 Raises a :exc:`ValueError` if there is no such item.
66
67 The optional arguments *start* and *end* are interpreted as in the slice
68 notation and are used to limit the search to a particular subsequence of
69 the list. The returned index is computed relative to the beginning of the full
70 sequence rather than the *start* argument.
71
72
73 .. method:: list.count(x)
74 :noindex:
75
76 Return the number of times *x* appears in the list.
77
78
79 .. method:: list.sort(*, key=None, reverse=False)
80 :noindex:
81
82 Sort the items of the list in place (the arguments can be used for sort
83 customization, see :func:`sorted` for their explanation).
84
85
86 .. method:: list.reverse()
87 :noindex:
88
89 Reverse the elements of the list in place.
90
91
92 .. method:: list.copy()
93 :noindex:
94
95 Return a shallow copy of the list. Similar to ``a[:]``.
96
97
98 An example that uses most of the list methods::
99
100 >>> fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']
101 >>> fruits.count('apple')
102 2
103 >>> fruits.count('tangerine')
104 0
105 >>> fruits.index('banana')
106 3
107 >>> fruits.index('banana', 4) # Find next banana starting at position 4
108 6
109 >>> fruits.reverse()
110 >>> fruits
111 ['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange']
112 >>> fruits.append('grape')
113 >>> fruits
114 ['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange', 'grape']
115 >>> fruits.sort()
116 >>> fruits
117 ['apple', 'apple', 'banana', 'banana', 'grape', 'kiwi', 'orange', 'pear']
118 >>> fruits.pop()
119 'pear'
120
121 You might have noticed that methods like ``insert``, ``remove`` or ``sort`` that
122 only modify the list have no return value printed -- they return the default
123 ``None``. [#]_ This is a design principle for all mutable data structures in
124 Python.
125
126 Another thing you might notice is that not all data can be sorted or
127 compared. For instance, ``[None, 'hello', 10]`` doesn't sort because
128 integers can't be compared to strings and ``None`` can't be compared to
129 other types. Also, there are some types that don't have a defined
130 ordering relation. For example, ``3+4j < 5+7j`` isn't a valid
131 comparison.
132
133
134 .. _tut-lists-as-stacks:
135
136 Using Lists as Stacks
137 ---------------------
138
139 .. sectionauthor:: Ka-Ping Yee <[email protected]>
140
141
142 The list methods make it very easy to use a list as a stack, where the last
143 element added is the first element retrieved ("last-in, first-out"). To add an
144 item to the top of the stack, use :meth:`~list.append`. To retrieve an item from the
145 top of the stack, use :meth:`~list.pop` without an explicit index. For example::
146
147 >>> stack = [3, 4, 5]
148 >>> stack.append(6)
149 >>> stack.append(7)
150 >>> stack
151 [3, 4, 5, 6, 7]
152 >>> stack.pop()
153 7
154 >>> stack
155 [3, 4, 5, 6]
156 >>> stack.pop()
157 6
158 >>> stack.pop()
159 5
160 >>> stack
161 [3, 4]
162
163
164 .. _tut-lists-as-queues:
165
166 Using Lists as Queues
167 ---------------------
168
169 .. sectionauthor:: Ka-Ping Yee <[email protected]>
170
171 It is also possible to use a list as a queue, where the first element added is
172 the first element retrieved ("first-in, first-out"); however, lists are not
173 efficient for this purpose. While appends and pops from the end of list are
174 fast, doing inserts or pops from the beginning of a list is slow (because all
175 of the other elements have to be shifted by one).
176
177 To implement a queue, use :class:`collections.deque` which was designed to
178 have fast appends and pops from both ends. For example::
179
180 >>> from collections import deque
181 >>> queue = deque(["Eric", "John", "Michael"])
182 >>> queue.append("Terry") # Terry arrives
183 >>> queue.append("Graham") # Graham arrives
184 >>> queue.popleft() # The first to arrive now leaves
185 'Eric'
186 >>> queue.popleft() # The second to arrive now leaves
187 'John'
188 >>> queue # Remaining queue in order of arrival
189 deque(['Michael', 'Terry', 'Graham'])
190
191
192 .. _tut-listcomps:
193
194 List Comprehensions
195 -------------------
196
197 List comprehensions provide a concise way to create lists.
198 Common applications are to make new lists where each element is the result of
199 some operations applied to each member of another sequence or iterable, or to
200 create a subsequence of those elements that satisfy a certain condition.
201
202 For example, assume we want to create a list of squares, like::
203
204 >>> squares = []
205 >>> for x in range(10):
206 ... squares.append(x**2)
207 ...
208 >>> squares
209 [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
210
211 Note that this creates (or overwrites) a variable named ``x`` that still exists
212 after the loop completes. We can calculate the list of squares without any
213 side effects using::
214
215 squares = list(map(lambda x: x**2, range(10)))
216
217 or, equivalently::
218
219 squares = [x**2 for x in range(10)]
220
221 which is more concise and readable.
222
223 A list comprehension consists of brackets containing an expression followed
224 by a :keyword:`!for` clause, then zero or more :keyword:`!for` or :keyword:`!if`
225 clauses. The result will be a new list resulting from evaluating the expression
226 in the context of the :keyword:`!for` and :keyword:`!if` clauses which follow it.
227 For example, this listcomp combines the elements of two lists if they are not
228 equal::
229
230 >>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
231 [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
232
233 and it's equivalent to::
234
235 >>> combs = []
236 >>> for x in [1,2,3]:
237 ... for y in [3,1,4]:
238 ... if x != y:
239 ... combs.append((x, y))
240 ...
241 >>> combs
242 [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
243
244 Note how the order of the :keyword:`for` and :keyword:`if` statements is the
245 same in both these snippets.
246
247 If the expression is a tuple (e.g. the ``(x, y)`` in the previous example),
248 it must be parenthesized. ::
249
250 >>> vec = [-4, -2, 0, 2, 4]
251 >>> # create a new list with the values doubled
252 >>> [x*2 for x in vec]
253 [-8, -4, 0, 4, 8]
254 >>> # filter the list to exclude negative numbers
255 >>> [x for x in vec if x >= 0]
256 [0, 2, 4]
257 >>> # apply a function to all the elements
258 >>> [abs(x) for x in vec]
259 [4, 2, 0, 2, 4]
260 >>> # call a method on each element
261 >>> freshfruit = [' banana', ' loganberry ', 'passion fruit ']
262 >>> [weapon.strip() for weapon in freshfruit]
263 ['banana', 'loganberry', 'passion fruit']
264 >>> # create a list of 2-tuples like (number, square)
265 >>> [(x, x**2) for x in range(6)]
266 [(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]
267 >>> # the tuple must be parenthesized, otherwise an error is raised
268 >>> [x, x**2 for x in range(6)]
269 File "<stdin>", line 1
270 [x, x**2 for x in range(6)]
271 ^^^^^^^
272 SyntaxError: did you forget parentheses around the comprehension target?
273 >>> # flatten a list using a listcomp with two 'for'
274 >>> vec = [[1,2,3], [4,5,6], [7,8,9]]
275 >>> [num for elem in vec for num in elem]
276 [1, 2, 3, 4, 5, 6, 7, 8, 9]
277
278 List comprehensions can contain complex expressions and nested functions::
279
280 >>> from math import pi
281 >>> [str(round(pi, i)) for i in range(1, 6)]
282 ['3.1', '3.14', '3.142', '3.1416', '3.14159']
283
284 Nested List Comprehensions
285 --------------------------
286
287 The initial expression in a list comprehension can be any arbitrary expression,
288 including another list comprehension.
289
290 Consider the following example of a 3x4 matrix implemented as a list of
291 3 lists of length 4::
292
293 >>> matrix = [
294 ... [1, 2, 3, 4],
295 ... [5, 6, 7, 8],
296 ... [9, 10, 11, 12],
297 ... ]
298
299 The following list comprehension will transpose rows and columns::
300
301 >>> [[row[i] for row in matrix] for i in range(4)]
302 [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
303
304 As we saw in the previous section, the inner list comprehension is evaluated in
305 the context of the :keyword:`for` that follows it, so this example is
306 equivalent to::
307
308 >>> transposed = []
309 >>> for i in range(4):
310 ... transposed.append([row[i] for row in matrix])
311 ...
312 >>> transposed
313 [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
314
315 which, in turn, is the same as::
316
317 >>> transposed = []
318 >>> for i in range(4):
319 ... # the following 3 lines implement the nested listcomp
320 ... transposed_row = []
321 ... for row in matrix:
322 ... transposed_row.append(row[i])
323 ... transposed.append(transposed_row)
324 ...
325 >>> transposed
326 [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
327
328 In the real world, you should prefer built-in functions to complex flow statements.
329 The :func:`zip` function would do a great job for this use case::
330
331 >>> list(zip(*matrix))
332 [(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]
333
334 See :ref:`tut-unpacking-arguments` for details on the asterisk in this line.
335
336 .. _tut-del:
337
338 The :keyword:`!del` statement
339 =============================
340
341 There is a way to remove an item from a list given its index instead of its
342 value: the :keyword:`del` statement. This differs from the :meth:`~list.pop` method
343 which returns a value. The :keyword:`!del` statement can also be used to remove
344 slices from a list or clear the entire list (which we did earlier by assignment
345 of an empty list to the slice). For example::
346
347 >>> a = [-1, 1, 66.25, 333, 333, 1234.5]
348 >>> del a[0]
349 >>> a
350 [1, 66.25, 333, 333, 1234.5]
351 >>> del a[2:4]
352 >>> a
353 [1, 66.25, 1234.5]
354 >>> del a[:]
355 >>> a
356 []
357
358 :keyword:`del` can also be used to delete entire variables::
359
360 >>> del a
361
362 Referencing the name ``a`` hereafter is an error (at least until another value
363 is assigned to it). We'll find other uses for :keyword:`del` later.
364
365
366 .. _tut-tuples:
367
368 Tuples and Sequences
369 ====================
370
371 We saw that lists and strings have many common properties, such as indexing and
372 slicing operations. They are two examples of *sequence* data types (see
373 :ref:`typesseq`). Since Python is an evolving language, other sequence data
374 types may be added. There is also another standard sequence data type: the
375 *tuple*.
376
377 A tuple consists of a number of values separated by commas, for instance::
378
379 >>> t = 12345, 54321, 'hello!'
380 >>> t[0]
381 12345
382 >>> t
383 (12345, 54321, 'hello!')
384 >>> # Tuples may be nested:
385 >>> u = t, (1, 2, 3, 4, 5)
386 >>> u
387 ((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))
388 >>> # Tuples are immutable:
389 >>> t[0] = 88888
390 Traceback (most recent call last):
391 File "<stdin>", line 1, in <module>
392 TypeError: 'tuple' object does not support item assignment
393 >>> # but they can contain mutable objects:
394 >>> v = ([1, 2, 3], [3, 2, 1])
395 >>> v
396 ([1, 2, 3], [3, 2, 1])
397
398
399 As you see, on output tuples are always enclosed in parentheses, so that nested
400 tuples are interpreted correctly; they may be input with or without surrounding
401 parentheses, although often parentheses are necessary anyway (if the tuple is
402 part of a larger expression). It is not possible to assign to the individual
403 items of a tuple, however it is possible to create tuples which contain mutable
404 objects, such as lists.
405
406 Though tuples may seem similar to lists, they are often used in different
407 situations and for different purposes.
408 Tuples are :term:`immutable`, and usually contain a heterogeneous sequence of
409 elements that are accessed via unpacking (see later in this section) or indexing
410 (or even by attribute in the case of :func:`namedtuples <collections.namedtuple>`).
411 Lists are :term:`mutable`, and their elements are usually homogeneous and are
412 accessed by iterating over the list.
413
414 A special problem is the construction of tuples containing 0 or 1 items: the
415 syntax has some extra quirks to accommodate these. Empty tuples are constructed
416 by an empty pair of parentheses; a tuple with one item is constructed by
417 following a value with a comma (it is not sufficient to enclose a single value
418 in parentheses). Ugly, but effective. For example::
419
420 >>> empty = ()
421 >>> singleton = 'hello', # <-- note trailing comma
422 >>> len(empty)
423 0
424 >>> len(singleton)
425 1
426 >>> singleton
427 ('hello',)
428
429 The statement ``t = 12345, 54321, 'hello!'`` is an example of *tuple packing*:
430 the values ``12345``, ``54321`` and ``'hello!'`` are packed together in a tuple.
431 The reverse operation is also possible::
432
433 >>> x, y, z = t
434
435 This is called, appropriately enough, *sequence unpacking* and works for any
436 sequence on the right-hand side. Sequence unpacking requires that there are as
437 many variables on the left side of the equals sign as there are elements in the
438 sequence. Note that multiple assignment is really just a combination of tuple
439 packing and sequence unpacking.
440
441
442 .. _tut-sets:
443
444 Sets
445 ====
446
447 Python also includes a data type for :ref:`sets <types-set>`. A set is
448 an unordered collection with no duplicate elements. Basic uses include
449 membership testing and eliminating duplicate entries. Set objects also
450 support mathematical operations like union, intersection, difference, and
451 symmetric difference.
452
453 Curly braces or the :func:`set` function can be used to create sets. Note: to
454 create an empty set you have to use ``set()``, not ``{}``; the latter creates an
455 empty dictionary, a data structure that we discuss in the next section.
456
457 Here is a brief demonstration::
458
459 >>> basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
460 >>> print(basket) # show that duplicates have been removed
461 {'orange', 'banana', 'pear', 'apple'}
462 >>> 'orange' in basket # fast membership testing
463 True
464 >>> 'crabgrass' in basket
465 False
466
467 >>> # Demonstrate set operations on unique letters from two words
468 >>>
469 >>> a = set('abracadabra')
470 >>> b = set('alacazam')
471 >>> a # unique letters in a
472 {'a', 'r', 'b', 'c', 'd'}
473 >>> a - b # letters in a but not in b
474 {'r', 'd', 'b'}
475 >>> a | b # letters in a or b or both
476 {'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}
477 >>> a & b # letters in both a and b
478 {'a', 'c'}
479 >>> a ^ b # letters in a or b but not both
480 {'r', 'd', 'b', 'm', 'z', 'l'}
481
482 Similarly to :ref:`list comprehensions <tut-listcomps>`, set comprehensions
483 are also supported::
484
485 >>> a = {x for x in 'abracadabra' if x not in 'abc'}
486 >>> a
487 {'r', 'd'}
488
489
490 .. _tut-dictionaries:
491
492 Dictionaries
493 ============
494
495 Another useful data type built into Python is the *dictionary* (see
496 :ref:`typesmapping`). Dictionaries are sometimes found in other languages as
497 "associative memories" or "associative arrays". Unlike sequences, which are
498 indexed by a range of numbers, dictionaries are indexed by *keys*, which can be
499 any immutable type; strings and numbers can always be keys. Tuples can be used
500 as keys if they contain only strings, numbers, or tuples; if a tuple contains
501 any mutable object either directly or indirectly, it cannot be used as a key.
502 You can't use lists as keys, since lists can be modified in place using index
503 assignments, slice assignments, or methods like :meth:`~list.append` and
504 :meth:`~list.extend`.
505
506 It is best to think of a dictionary as a set of *key: value* pairs,
507 with the requirement that the keys are unique (within one dictionary). A pair of
508 braces creates an empty dictionary: ``{}``. Placing a comma-separated list of
509 key:value pairs within the braces adds initial key:value pairs to the
510 dictionary; this is also the way dictionaries are written on output.
511
512 The main operations on a dictionary are storing a value with some key and
513 extracting the value given the key. It is also possible to delete a key:value
514 pair with ``del``. If you store using a key that is already in use, the old
515 value associated with that key is forgotten.
516
517 Extracting a value for a non-existent key by subscripting (``d[key]``) raises a
518 :exc:`KeyError`. To avoid getting this error when trying to access a possibly
519 non-existent key, use the :meth:`~dict.get` method instead, which returns
520 ``None`` (or a specified default value) if the key is not in the dictionary.
521
522 Performing ``list(d)`` on a dictionary returns a list of all the keys
523 used in the dictionary, in insertion order (if you want it sorted, just use
524 ``sorted(d)`` instead). To check whether a single key is in the
525 dictionary, use the :keyword:`in` keyword.
526
527 Here is a small example using a dictionary::
528
529 >>> tel = {'jack': 4098, 'sape': 4139}
530 >>> tel['guido'] = 4127
531 >>> tel
532 {'jack': 4098, 'sape': 4139, 'guido': 4127}
533 >>> tel['jack']
534 4098
535 >>> tel['irv']
536 Traceback (most recent call last):
537 File "<stdin>", line 1, in <module>
538 KeyError: 'irv'
539 >>> print(tel.get('irv'))
540 None
541 >>> del tel['sape']
542 >>> tel['irv'] = 4127
543 >>> tel
544 {'jack': 4098, 'guido': 4127, 'irv': 4127}
545 >>> list(tel)
546 ['jack', 'guido', 'irv']
547 >>> sorted(tel)
548 ['guido', 'irv', 'jack']
549 >>> 'guido' in tel
550 True
551 >>> 'jack' not in tel
552 False
553
554 The :func:`dict` constructor builds dictionaries directly from sequences of
555 key-value pairs::
556
557 >>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
558 {'sape': 4139, 'guido': 4127, 'jack': 4098}
559
560 In addition, dict comprehensions can be used to create dictionaries from
561 arbitrary key and value expressions::
562
563 >>> {x: x**2 for x in (2, 4, 6)}
564 {2: 4, 4: 16, 6: 36}
565
566 When the keys are simple strings, it is sometimes easier to specify pairs using
567 keyword arguments::
568
569 >>> dict(sape=4139, guido=4127, jack=4098)
570 {'sape': 4139, 'guido': 4127, 'jack': 4098}
571
572
573 .. _tut-loopidioms:
574
575 Looping Techniques
576 ==================
577
578 When looping through dictionaries, the key and corresponding value can be
579 retrieved at the same time using the :meth:`~dict.items` method. ::
580
581 >>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
582 >>> for k, v in knights.items():
583 ... print(k, v)
584 ...
585 gallahad the pure
586 robin the brave
587
588 When looping through a sequence, the position index and corresponding value can
589 be retrieved at the same time using the :func:`enumerate` function. ::
590
591 >>> for i, v in enumerate(['tic', 'tac', 'toe']):
592 ... print(i, v)
593 ...
594 0 tic
595 1 tac
596 2 toe
597
598 To loop over two or more sequences at the same time, the entries can be paired
599 with the :func:`zip` function. ::
600
601 >>> questions = ['name', 'quest', 'favorite color']
602 >>> answers = ['lancelot', 'the holy grail', 'blue']
603 >>> for q, a in zip(questions, answers):
604 ... print('What is your {0}? It is {1}.'.format(q, a))
605 ...
606 What is your name? It is lancelot.
607 What is your quest? It is the holy grail.
608 What is your favorite color? It is blue.
609
610 To loop over a sequence in reverse, first specify the sequence in a forward
611 direction and then call the :func:`reversed` function. ::
612
613 >>> for i in reversed(range(1, 10, 2)):
614 ... print(i)
615 ...
616 9
617 7
618 5
619 3
620 1
621
622 To loop over a sequence in sorted order, use the :func:`sorted` function which
623 returns a new sorted list while leaving the source unaltered. ::
624
625 >>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
626 >>> for i in sorted(basket):
627 ... print(i)
628 ...
629 apple
630 apple
631 banana
632 orange
633 orange
634 pear
635
636 Using :func:`set` on a sequence eliminates duplicate elements. The use of
637 :func:`sorted` in combination with :func:`set` over a sequence is an idiomatic
638 way to loop over unique elements of the sequence in sorted order. ::
639
640 >>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
641 >>> for f in sorted(set(basket)):
642 ... print(f)
643 ...
644 apple
645 banana
646 orange
647 pear
648
649 It is sometimes tempting to change a list while you are looping over it;
650 however, it is often simpler and safer to create a new list instead. ::
651
652 >>> import math
653 >>> raw_data = [56.2, float('NaN'), 51.7, 55.3, 52.5, float('NaN'), 47.8]
654 >>> filtered_data = []
655 >>> for value in raw_data:
656 ... if not math.isnan(value):
657 ... filtered_data.append(value)
658 ...
659 >>> filtered_data
660 [56.2, 51.7, 55.3, 52.5, 47.8]
661
662
663 .. _tut-conditions:
664
665 More on Conditions
666 ==================
667
668 The conditions used in ``while`` and ``if`` statements can contain any
669 operators, not just comparisons.
670
671
672 The comparison operators ``in`` and ``not in`` are membership tests that
673 determine whether a value is in (or not in) a container. The operators ``is``
674 and ``is not`` compare whether two objects are really the same object. All
675 comparison operators have the same priority, which is lower than that of all
676 numerical operators.
677
678 Comparisons can be chained. For example, ``a < b == c`` tests whether ``a`` is
679 less than ``b`` and moreover ``b`` equals ``c``.
680
681 Comparisons may be combined using the Boolean operators ``and`` and ``or``, and
682 the outcome of a comparison (or of any other Boolean expression) may be negated
683 with ``not``. These have lower priorities than comparison operators; between
684 them, ``not`` has the highest priority and ``or`` the lowest, so that ``A and
685 not B or C`` is equivalent to ``(A and (not B)) or C``. As always, parentheses
686 can be used to express the desired composition.
687
688 The Boolean operators ``and`` and ``or`` are so-called *short-circuit*
689 operators: their arguments are evaluated from left to right, and evaluation
690 stops as soon as the outcome is determined. For example, if ``A`` and ``C`` are
691 true but ``B`` is false, ``A and B and C`` does not evaluate the expression
692 ``C``. When used as a general value and not as a Boolean, the return value of a
693 short-circuit operator is the last evaluated argument.
694
695 It is possible to assign the result of a comparison or other Boolean expression
696 to a variable. For example, ::
697
698 >>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance'
699 >>> non_null = string1 or string2 or string3
700 >>> non_null
701 'Trondheim'
702
703 Note that in Python, unlike C, assignment inside expressions must be done
704 explicitly with the
705 :ref:`walrus operator <why-can-t-i-use-an-assignment-in-an-expression>` ``:=``.
706 This avoids a common class of problems encountered in C programs: typing ``=``
707 in an expression when ``==`` was intended.
708
709
710 .. _tut-comparing:
711
712 Comparing Sequences and Other Types
713 ===================================
714 Sequence objects typically may be compared to other objects with the same sequence
715 type. The comparison uses *lexicographical* ordering: first the first two
716 items are compared, and if they differ this determines the outcome of the
717 comparison; if they are equal, the next two items are compared, and so on, until
718 either sequence is exhausted. If two items to be compared are themselves
719 sequences of the same type, the lexicographical comparison is carried out
720 recursively. If all items of two sequences compare equal, the sequences are
721 considered equal. If one sequence is an initial sub-sequence of the other, the
722 shorter sequence is the smaller (lesser) one. Lexicographical ordering for
723 strings uses the Unicode code point number to order individual characters.
724 Some examples of comparisons between sequences of the same type::
725
726 (1, 2, 3) < (1, 2, 4)
727 [1, 2, 3] < [1, 2, 4]
728 'ABC' < 'C' < 'Pascal' < 'Python'
729 (1, 2, 3, 4) < (1, 2, 4)
730 (1, 2) < (1, 2, -1)
731 (1, 2, 3) == (1.0, 2.0, 3.0)
732 (1, 2, ('aa', 'ab')) < (1, 2, ('abc', 'a'), 4)
733
734 Note that comparing objects of different types with ``<`` or ``>`` is legal
735 provided that the objects have appropriate comparison methods. For example,
736 mixed numeric types are compared according to their numeric value, so 0 equals
737 0.0, etc. Otherwise, rather than providing an arbitrary ordering, the
738 interpreter will raise a :exc:`TypeError` exception.
739
740
741 .. rubric:: Footnotes
742
743 .. [#] Other languages may return the mutated object, which allows method
744 chaining, such as ``d->insert("a")->remove("b")->sort();``.