blob: e2f218ce8e20ef19cb10cca590681aafe67688e8 [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 Brandlf6945182008-02-01 11:56:49 +0000276 >>> [str(round(355/113, 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 Brandlf6945182008-02-01 11:56:49 +0000440 >>> fruit = {'orange', 'apple'} # {} syntax is equivalent to [] for lists
441 >>> fruit
442 {'orange', 'apple'}
Georg Brandl116aa622007-08-15 14:28:22 +0000443 >>> 'orange' in fruit # fast membership testing
444 True
445 >>> 'crabgrass' in fruit
446 False
447
448 >>> # Demonstrate set operations on unique letters from two words
449 ...
450 >>> a = set('abracadabra')
451 >>> b = set('alacazam')
452 >>> a # unique letters in a
Guido van Rossum0616b792007-08-31 03:25:11 +0000453 {'a', 'r', 'b', 'c', 'd'}
Georg Brandl116aa622007-08-15 14:28:22 +0000454 >>> a - b # letters in a but not in b
Guido van Rossum0616b792007-08-31 03:25:11 +0000455 {'r', 'd', 'b'}
Georg Brandl116aa622007-08-15 14:28:22 +0000456 >>> a | b # letters in either a or b
Guido van Rossum0616b792007-08-31 03:25:11 +0000457 {'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}
Georg Brandl116aa622007-08-15 14:28:22 +0000458 >>> a & b # letters in both a and b
Guido van Rossum0616b792007-08-31 03:25:11 +0000459 {'a', 'c'}
Georg Brandl116aa622007-08-15 14:28:22 +0000460 >>> a ^ b # letters in a or b but not both
Guido van Rossum0616b792007-08-31 03:25:11 +0000461 {'r', 'd', 'b', 'm', 'z', 'l'}
462
Georg Brandlf6945182008-02-01 11:56:49 +0000463Like for lists, there is a set comprehension syntax::
464
465 >>> a = {x for x in 'abracadabra' if x not in 'abc'}
466 >>> a
467 {'r', 'd'}
Guido van Rossum0616b792007-08-31 03:25:11 +0000468
Georg Brandl116aa622007-08-15 14:28:22 +0000469
470
471.. _tut-dictionaries:
472
473Dictionaries
474============
475
476Another useful data type built into Python is the *dictionary* (see
477:ref:`typesmapping`). Dictionaries are sometimes found in other languages as
478"associative memories" or "associative arrays". Unlike sequences, which are
479indexed by a range of numbers, dictionaries are indexed by *keys*, which can be
480any immutable type; strings and numbers can always be keys. Tuples can be used
481as keys if they contain only strings, numbers, or tuples; if a tuple contains
482any mutable object either directly or indirectly, it cannot be used as a key.
483You can't use lists as keys, since lists can be modified in place using index
484assignments, slice assignments, or methods like :meth:`append` and
485:meth:`extend`.
486
487It is best to think of a dictionary as an unordered set of *key: value* pairs,
488with the requirement that the keys are unique (within one dictionary). A pair of
489braces creates an empty dictionary: ``{}``. Placing a comma-separated list of
490key:value pairs within the braces adds initial key:value pairs to the
491dictionary; this is also the way dictionaries are written on output.
492
493The main operations on a dictionary are storing a value with some key and
494extracting the value given the key. It is also possible to delete a key:value
495pair with ``del``. If you store using a key that is already in use, the old
496value associated with that key is forgotten. It is an error to extract a value
497using a non-existent key.
498
499The :meth:`keys` method of a dictionary object returns a list of all the keys
500used in the dictionary, in arbitrary order (if you want it sorted, just apply
501the :meth:`sort` method to the list of keys). To check whether a single key is
Collin Winter19ab2bd2007-09-10 00:20:46 +0000502in the dictionary, use the :keyword:`in` keyword.
Georg Brandl116aa622007-08-15 14:28:22 +0000503
504Here is a small example using a dictionary::
505
506 >>> tel = {'jack': 4098, 'sape': 4139}
507 >>> tel['guido'] = 4127
508 >>> tel
509 {'sape': 4139, 'guido': 4127, 'jack': 4098}
510 >>> tel['jack']
511 4098
512 >>> del tel['sape']
513 >>> tel['irv'] = 4127
514 >>> tel
515 {'guido': 4127, 'irv': 4127, 'jack': 4098}
Neal Norwitze0906d12007-08-31 03:46:28 +0000516 >>> list(tel.keys())
Georg Brandl116aa622007-08-15 14:28:22 +0000517 ['guido', 'irv', 'jack']
Georg Brandl116aa622007-08-15 14:28:22 +0000518 >>> 'guido' in tel
519 True
Neal Norwitze0906d12007-08-31 03:46:28 +0000520 >>> 'jack' not in tel
521 False
Georg Brandl116aa622007-08-15 14:28:22 +0000522
523The :func:`dict` constructor builds dictionaries directly from lists of
524key-value pairs stored as tuples. When the pairs form a pattern, list
525comprehensions can compactly specify the key-value list. ::
526
527 >>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
528 {'sape': 4139, 'jack': 4098, 'guido': 4127}
Georg Brandl116aa622007-08-15 14:28:22 +0000529
Georg Brandlf6945182008-02-01 11:56:49 +0000530In addition, dict comprehensions can be used to create dictionaries from
531arbitrary key and value expressions::
532
533 >>> {x: x**2 for x in (2, 4, 6)}
534 {2: 4, 4: 16, 6: 36}
Georg Brandl116aa622007-08-15 14:28:22 +0000535
536When the keys are simple strings, it is sometimes easier to specify pairs using
537keyword arguments::
538
539 >>> dict(sape=4139, guido=4127, jack=4098)
540 {'sape': 4139, 'jack': 4098, 'guido': 4127}
541
542
Georg Brandlf6945182008-02-01 11:56:49 +0000543.. XXX Find out the right way to do these DUBOIS
Georg Brandl116aa622007-08-15 14:28:22 +0000544.. _tut-loopidioms:
545
546Looping Techniques
547==================
548
549When looping through dictionaries, the key and corresponding value can be
Neal Norwitze0906d12007-08-31 03:46:28 +0000550retrieved at the same time using the :meth:`items` method. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000551
552 >>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
Neal Norwitze0906d12007-08-31 03:46:28 +0000553 >>> for k, v in knights.items():
Guido van Rossum0616b792007-08-31 03:25:11 +0000554 ... print(k, v)
Georg Brandl116aa622007-08-15 14:28:22 +0000555 ...
556 gallahad the pure
557 robin the brave
558
559When looping through a sequence, the position index and corresponding value can
560be retrieved at the same time using the :func:`enumerate` function. ::
561
562 >>> for i, v in enumerate(['tic', 'tac', 'toe']):
Guido van Rossum0616b792007-08-31 03:25:11 +0000563 ... print(i, v)
Georg Brandl116aa622007-08-15 14:28:22 +0000564 ...
565 0 tic
566 1 tac
567 2 toe
568
569To loop over two or more sequences at the same time, the entries can be paired
570with the :func:`zip` function. ::
571
572 >>> questions = ['name', 'quest', 'favorite color']
573 >>> answers = ['lancelot', 'the holy grail', 'blue']
574 >>> for q, a in zip(questions, answers):
Guido van Rossum0616b792007-08-31 03:25:11 +0000575 ... print('What is your %s? It is %s.' % (q, a))
Georg Brandl116aa622007-08-15 14:28:22 +0000576 ...
577 What is your name? It is lancelot.
578 What is your quest? It is the holy grail.
579 What is your favorite color? It is blue.
580
581To loop over a sequence in reverse, first specify the sequence in a forward
582direction and then call the :func:`reversed` function. ::
583
Georg Brandle4ac7502007-09-03 07:10:24 +0000584 >>> for i in reversed(range(1, 10, 2)):
Guido van Rossum0616b792007-08-31 03:25:11 +0000585 ... print(i)
Georg Brandl116aa622007-08-15 14:28:22 +0000586 ...
587 9
588 7
589 5
590 3
591 1
592
593To loop over a sequence in sorted order, use the :func:`sorted` function which
594returns a new sorted list while leaving the source unaltered. ::
595
596 >>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
597 >>> for f in sorted(set(basket)):
Guido van Rossum0616b792007-08-31 03:25:11 +0000598 ... print(f)
Georg Brandl116aa622007-08-15 14:28:22 +0000599 ...
600 apple
601 banana
602 orange
603 pear
604
605
606.. _tut-conditions:
607
608More on Conditions
609==================
610
611The conditions used in ``while`` and ``if`` statements can contain any
612operators, not just comparisons.
613
614The comparison operators ``in`` and ``not in`` check whether a value occurs
615(does not occur) in a sequence. The operators ``is`` and ``is not`` compare
616whether two objects are really the same object; this only matters for mutable
617objects like lists. All comparison operators have the same priority, which is
618lower than that of all numerical operators.
619
620Comparisons can be chained. For example, ``a < b == c`` tests whether ``a`` is
621less than ``b`` and moreover ``b`` equals ``c``.
622
623Comparisons may be combined using the Boolean operators ``and`` and ``or``, and
624the outcome of a comparison (or of any other Boolean expression) may be negated
625with ``not``. These have lower priorities than comparison operators; between
626them, ``not`` has the highest priority and ``or`` the lowest, so that ``A and
627not B or C`` is equivalent to ``(A and (not B)) or C``. As always, parentheses
628can be used to express the desired composition.
629
630The Boolean operators ``and`` and ``or`` are so-called *short-circuit*
631operators: their arguments are evaluated from left to right, and evaluation
632stops as soon as the outcome is determined. For example, if ``A`` and ``C`` are
633true but ``B`` is false, ``A and B and C`` does not evaluate the expression
634``C``. When used as a general value and not as a Boolean, the return value of a
635short-circuit operator is the last evaluated argument.
636
637It is possible to assign the result of a comparison or other Boolean expression
638to a variable. For example, ::
639
640 >>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance'
641 >>> non_null = string1 or string2 or string3
642 >>> non_null
643 'Trondheim'
644
645Note that in Python, unlike C, assignment cannot occur inside expressions. C
646programmers may grumble about this, but it avoids a common class of problems
647encountered in C programs: typing ``=`` in an expression when ``==`` was
648intended.
649
650
651.. _tut-comparing:
652
653Comparing Sequences and Other Types
654===================================
655
656Sequence objects may be compared to other objects with the same sequence type.
657The comparison uses *lexicographical* ordering: first the first two items are
658compared, and if they differ this determines the outcome of the comparison; if
659they are equal, the next two items are compared, and so on, until either
660sequence is exhausted. If two items to be compared are themselves sequences of
661the same type, the lexicographical comparison is carried out recursively. If
662all items of two sequences compare equal, the sequences are considered equal.
663If one sequence is an initial sub-sequence of the other, the shorter sequence is
664the smaller (lesser) one. Lexicographical ordering for strings uses the ASCII
665ordering for individual characters. Some examples of comparisons between
666sequences of the same type::
667
668 (1, 2, 3) < (1, 2, 4)
669 [1, 2, 3] < [1, 2, 4]
670 'ABC' < 'C' < 'Pascal' < 'Python'
671 (1, 2, 3, 4) < (1, 2, 4)
672 (1, 2) < (1, 2, -1)
673 (1, 2, 3) == (1.0, 2.0, 3.0)
674 (1, 2, ('aa', 'ab')) < (1, 2, ('abc', 'a'), 4)
675
Georg Brandl9f2c39a2007-10-08 14:08:36 +0000676Note that comparing objects of different types with ``<`` or ``>`` is legal
677provided that the objects have appropriate comparison methods. For example,
678mixed numeric types are compared according to their numeric value, so 0 equals
6790.0, etc. Otherwise, rather than providing an arbitrary ordering, the
680interpreter will raise a :exc:`TypeError` exception.