blob: 201fa729b3735a9720f3a4f8ca4be2724044e23f [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)
Christian Heimes4fbc72b2008-03-22 00:47:35 +000086 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +000087
88 Add an item to the end of the list; equivalent to ``a[len(a):] = [x]``.
89
90
91.. method:: list.extend(L)
Christian Heimes4fbc72b2008-03-22 00:47:35 +000092 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +000093
94 Extend the list by appending all the items in the given list; equivalent to
95 ``a[len(a):] = L``.
96
97
98.. method:: list.insert(i, x)
Christian Heimes4fbc72b2008-03-22 00:47:35 +000099 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +0000100
101 Insert an item at a given position. The first argument is the index of the
102 element before which to insert, so ``a.insert(0, x)`` inserts at the front of
103 the list, and ``a.insert(len(a), x)`` is equivalent to ``a.append(x)``.
104
105
106.. method:: list.remove(x)
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000107 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +0000108
109 Remove the first item from the list whose value is *x*. It is an error if there
110 is no such item.
111
112
113.. method:: list.pop([i])
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000114 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +0000115
116 Remove the item at the given position in the list, and return it. If no index
117 is specified, ``a.pop()`` removes and returns the last item in the list. (The
118 square brackets around the *i* in the method signature denote that the parameter
119 is optional, not that you should type square brackets at that position. You
120 will see this notation frequently in the Python Library Reference.)
121
122
123.. method:: list.index(x)
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000124 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +0000125
126 Return the index in the list of the first item whose value is *x*. It is an
127 error if there is no such item.
128
129
130.. method:: list.count(x)
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000131 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +0000132
133 Return the number of times *x* appears in the list.
134
135
136.. method:: list.sort()
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000137 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +0000138
139 Sort the items of the list, in place.
140
141
142.. method:: list.reverse()
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000143 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +0000144
145 Reverse the elements of the list, in place.
146
147An example that uses most of the list methods::
148
149 >>> a = [66.25, 333, 333, 1, 1234.5]
Guido van Rossum0616b792007-08-31 03:25:11 +0000150 >>> print(a.count(333), a.count(66.25), a.count('x'))
Georg Brandl116aa622007-08-15 14:28:22 +0000151 2 1 0
152 >>> a.insert(2, -1)
153 >>> a.append(333)
154 >>> a
155 [66.25, 333, -1, 333, 1, 1234.5, 333]
156 >>> a.index(333)
157 1
158 >>> a.remove(333)
159 >>> a
160 [66.25, -1, 333, 1, 1234.5, 333]
161 >>> a.reverse()
162 >>> a
163 [333, 1234.5, 1, 333, -1, 66.25]
164 >>> a.sort()
165 >>> a
166 [-1, 1, 66.25, 333, 333, 1234.5]
167
168
169.. _tut-lists-as-stacks:
170
171Using Lists as Stacks
172---------------------
173
174.. sectionauthor:: Ka-Ping Yee <ping@lfw.org>
175
176
177The list methods make it very easy to use a list as a stack, where the last
178element added is the first element retrieved ("last-in, first-out"). To add an
179item to the top of the stack, use :meth:`append`. To retrieve an item from the
180top of the stack, use :meth:`pop` without an explicit index. For example::
181
182 >>> stack = [3, 4, 5]
183 >>> stack.append(6)
184 >>> stack.append(7)
185 >>> stack
186 [3, 4, 5, 6, 7]
187 >>> stack.pop()
188 7
189 >>> stack
190 [3, 4, 5, 6]
191 >>> stack.pop()
192 6
193 >>> stack.pop()
194 5
195 >>> stack
196 [3, 4]
197
198
199.. _tut-lists-as-queues:
200
201Using Lists as Queues
202---------------------
203
204.. sectionauthor:: Ka-Ping Yee <ping@lfw.org>
205
206
207You can also use a list conveniently as a queue, where the first element added
208is the first element retrieved ("first-in, first-out"). To add an item to the
209back of the queue, use :meth:`append`. To retrieve an item from the front of
210the queue, use :meth:`pop` with ``0`` as the index. For example::
211
212 >>> queue = ["Eric", "John", "Michael"]
213 >>> queue.append("Terry") # Terry arrives
214 >>> queue.append("Graham") # Graham arrives
215 >>> queue.pop(0)
216 'Eric'
217 >>> queue.pop(0)
218 'John'
219 >>> queue
220 ['Michael', 'Terry', 'Graham']
221
222
Georg Brandl116aa622007-08-15 14:28:22 +0000223List Comprehensions
224-------------------
225
Guido van Rossum0616b792007-08-31 03:25:11 +0000226List comprehensions provide a concise way to create lists from sequences.
227Common applications are to make lists where each element is the result of
228some operations applied to each member of the sequence, or to create a
229subsequence of those elements that satisfy a certain condition.
230
231
Georg Brandl116aa622007-08-15 14:28:22 +0000232Each list comprehension consists of an expression followed by a :keyword:`for`
233clause, then zero or more :keyword:`for` or :keyword:`if` clauses. The result
234will be a list resulting from evaluating the expression in the context of the
235:keyword:`for` and :keyword:`if` clauses which follow it. If the expression
Guido van Rossum0616b792007-08-31 03:25:11 +0000236would evaluate to a tuple, it must be parenthesized.
237
238Here we take a list of numbers and return a list of three times each number::
239
240 >>> vec = [2, 4, 6]
241 >>> [3*x for x in vec]
242 [6, 12, 18]
243
244Now we get a little fancier::
245
Georg Brandle4ac7502007-09-03 07:10:24 +0000246 >>> [[x, x**2] for x in vec]
Guido van Rossum0616b792007-08-31 03:25:11 +0000247 [[2, 4], [4, 16], [6, 36]]
248
249Here we apply a method call to each item in a sequence::
Georg Brandl116aa622007-08-15 14:28:22 +0000250
251 >>> freshfruit = [' banana', ' loganberry ', 'passion fruit ']
252 >>> [weapon.strip() for weapon in freshfruit]
253 ['banana', 'loganberry', 'passion fruit']
Guido van Rossum0616b792007-08-31 03:25:11 +0000254
Georg Brandle4ac7502007-09-03 07:10:24 +0000255Using the :keyword:`if` clause we can filter the stream::
Guido van Rossum0616b792007-08-31 03:25:11 +0000256
Georg Brandl116aa622007-08-15 14:28:22 +0000257 >>> [3*x for x in vec if x > 3]
258 [12, 18]
259 >>> [3*x for x in vec if x < 2]
260 []
Guido van Rossum0616b792007-08-31 03:25:11 +0000261
262Tuples can often be created without their parentheses, but not here::
263
Georg Brandl116aa622007-08-15 14:28:22 +0000264 >>> [x, x**2 for x in vec] # error - parens required for tuples
265 File "<stdin>", line 1, in ?
266 [x, x**2 for x in vec]
267 ^
268 SyntaxError: invalid syntax
269 >>> [(x, x**2) for x in vec]
270 [(2, 4), (4, 16), (6, 36)]
Guido van Rossum0616b792007-08-31 03:25:11 +0000271
Georg Brandle4ac7502007-09-03 07:10:24 +0000272Here are some nested for loops and other fancy behavior::
Guido van Rossum0616b792007-08-31 03:25:11 +0000273
Georg Brandl116aa622007-08-15 14:28:22 +0000274 >>> vec1 = [2, 4, 6]
275 >>> vec2 = [4, 3, -9]
276 >>> [x*y for x in vec1 for y in vec2]
277 [8, 6, -18, 16, 12, -36, 24, 18, -54]
278 >>> [x+y for x in vec1 for y in vec2]
279 [6, 5, -7, 8, 7, -5, 10, 9, -3]
280 >>> [vec1[i]*vec2[i] for i in range(len(vec1))]
281 [8, 12, -54]
282
Guido van Rossum0616b792007-08-31 03:25:11 +0000283List comprehensions can be applied to complex expressions and nested functions::
Georg Brandl116aa622007-08-15 14:28:22 +0000284
Georg Brandlf6945182008-02-01 11:56:49 +0000285 >>> [str(round(355/113, i)) for i in range(1, 6)]
Georg Brandl116aa622007-08-15 14:28:22 +0000286 ['3.1', '3.14', '3.142', '3.1416', '3.14159']
287
288
Christian Heimes0449f632007-12-15 01:27:15 +0000289Nested List Comprehensions
290--------------------------
291
292If you've got the stomach for it, list comprehensions can be nested. They are a
293powerful tool but -- like all powerful tools -- they need to be used carefully,
294if at all.
295
296Consider the following example of a 3x3 matrix held as a list containing three
297lists, one list per row::
298
299 >>> mat = [
300 ... [1, 2, 3],
301 ... [4, 5, 6],
302 ... [7, 8, 9],
303 ... ]
304
305Now, if you wanted to swap rows and columns, you could use a list
306comprehension::
307
308 >>> print [[row[i] for row in mat] for i in [0, 1, 2]]
309 [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
310
311Special care has to be taken for the *nested* list comprehension:
312
313 To avoid apprehension when nesting list comprehensions, read from right to
314 left.
315
316A more verbose version of this snippet shows the flow explicitly::
317
318 for i in [0, 1, 2]:
319 for row in mat:
320 print row[i],
321 print
322
323In real world, you should prefer builtin functions to complex flow statements.
324The :func:`zip` function would do a great job for this use case::
325
326 >>> zip(*mat)
327 [(1, 4, 7), (2, 5, 8), (3, 6, 9)]
328
329See :ref:`tut-unpacking-arguments` for details on the asterisk in this line.
330
Georg Brandl116aa622007-08-15 14:28:22 +0000331.. _tut-del:
332
333The :keyword:`del` statement
334============================
335
336There is a way to remove an item from a list given its index instead of its
337value: the :keyword:`del` statement. This differs from the :meth:`pop` method
338which returns a value. The :keyword:`del` statement can also be used to remove
339slices from a list or clear the entire list (which we did earlier by assignment
340of an empty list to the slice). For example::
341
342 >>> a = [-1, 1, 66.25, 333, 333, 1234.5]
343 >>> del a[0]
344 >>> a
345 [1, 66.25, 333, 333, 1234.5]
346 >>> del a[2:4]
347 >>> a
348 [1, 66.25, 1234.5]
349 >>> del a[:]
350 >>> a
351 []
352
353:keyword:`del` can also be used to delete entire variables::
354
355 >>> del a
356
357Referencing the name ``a`` hereafter is an error (at least until another value
358is assigned to it). We'll find other uses for :keyword:`del` later.
359
360
Georg Brandl116aa622007-08-15 14:28:22 +0000361
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000362Tuples and Sequences
363====================
364
365We saw that lists and strings have many common properties, such as indexing and
366slicing operations. They are two examples of *sequence* data types (see
367:ref:`typesseq`). Since Python is an evolving language, other sequence data
368types may be added. There is also another standard sequence data type: the
369*tuple*.
370
371A tuple consists of a number of values separated by commas, for instance::
372
373 >>> t = 12345, 54321, 'hello!'
374 >>> t[0]
375 12345
376 >>> t
377 (12345, 54321, 'hello!')
378 >>> # Tuples may be nested:
379 ... u = t, (1, 2, 3, 4, 5)
380 >>> u
381 ((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))
382
383As you see, on output tuples are always enclosed in parentheses, so that nested
384tuples are interpreted correctly; they may be input with or without surrounding
385parentheses, although often parentheses are necessary anyway (if the tuple is
386part of a larger expression).
387
388Tuples have many uses. For example: (x, y) coordinate pairs, employee records
389from a database, etc. Tuples, like strings, are immutable: it is not possible
390to assign to the individual items of a tuple (you can simulate much of the same
391effect with slicing and concatenation, though). It is also possible to create
392tuples which contain mutable objects, such as lists.
393
394A special problem is the construction of tuples containing 0 or 1 items: the
395syntax has some extra quirks to accommodate these. Empty tuples are constructed
396by an empty pair of parentheses; a tuple with one item is constructed by
397following a value with a comma (it is not sufficient to enclose a single value
398in parentheses). Ugly, but effective. For example::
399
400 >>> empty = ()
401 >>> singleton = 'hello', # <-- note trailing comma
402 >>> len(empty)
403 0
404 >>> len(singleton)
405 1
406 >>> singleton
407 ('hello',)
408
409The statement ``t = 12345, 54321, 'hello!'`` is an example of *tuple packing*:
410the values ``12345``, ``54321`` and ``'hello!'`` are packed together in a tuple.
411The reverse operation is also possible::
412
413 >>> x, y, z = t
414
415This is called, appropriately enough, *sequence unpacking*. Sequence unpacking
416requires the list of variables on the left to have the same number of elements
417as the length of the sequence. Note that multiple assignment is really just a
418combination of tuple packing and sequence unpacking!
419
420There is a small bit of asymmetry here: packing multiple values always creates
421a tuple, and unpacking works for any sequence.
422
423.. XXX Add a bit on the difference between tuples and lists.
424
425
Georg Brandl116aa622007-08-15 14:28:22 +0000426.. _tut-sets:
427
428Sets
429====
430
431Python also includes a data type for *sets*. A set is an unordered collection
432with no duplicate elements. Basic uses include membership testing and
433eliminating duplicate entries. Set objects also support mathematical operations
434like union, intersection, difference, and symmetric difference.
435
Guido van Rossum0616b792007-08-31 03:25:11 +0000436Curly braces or the :func:`set` function can be use to create sets. Note:
437To create an empty set you have to use set(), not {}; the latter creates
438an empty dictionary, a data structure that we discuss in the next section.
439
Georg Brandl116aa622007-08-15 14:28:22 +0000440Here is a brief demonstration::
441
Guido van Rossum0616b792007-08-31 03:25:11 +0000442 >>> basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
443 >>> print(basket)
444 {'orange', 'bananna', 'pear', 'apple'}
445 >>> fruit = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
Georg Brandl116aa622007-08-15 14:28:22 +0000446 >>> fruit = set(basket) # create a set without duplicates
447 >>> fruit
Guido van Rossum0616b792007-08-31 03:25:11 +0000448 {'orange', 'pear', 'apple', 'banana'}
Georg Brandlf6945182008-02-01 11:56:49 +0000449 >>> fruit = {'orange', 'apple'} # {} syntax is equivalent to [] for lists
450 >>> fruit
451 {'orange', 'apple'}
Georg Brandl116aa622007-08-15 14:28:22 +0000452 >>> 'orange' in fruit # fast membership testing
453 True
454 >>> 'crabgrass' in fruit
455 False
456
457 >>> # Demonstrate set operations on unique letters from two words
458 ...
459 >>> a = set('abracadabra')
460 >>> b = set('alacazam')
461 >>> a # unique letters in a
Guido van Rossum0616b792007-08-31 03:25:11 +0000462 {'a', 'r', 'b', 'c', 'd'}
Georg Brandl116aa622007-08-15 14:28:22 +0000463 >>> a - b # letters in a but not in b
Guido van Rossum0616b792007-08-31 03:25:11 +0000464 {'r', 'd', 'b'}
Georg Brandl116aa622007-08-15 14:28:22 +0000465 >>> a | b # letters in either a or b
Guido van Rossum0616b792007-08-31 03:25:11 +0000466 {'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}
Georg Brandl116aa622007-08-15 14:28:22 +0000467 >>> a & b # letters in both a and b
Guido van Rossum0616b792007-08-31 03:25:11 +0000468 {'a', 'c'}
Georg Brandl116aa622007-08-15 14:28:22 +0000469 >>> a ^ b # letters in a or b but not both
Guido van Rossum0616b792007-08-31 03:25:11 +0000470 {'r', 'd', 'b', 'm', 'z', 'l'}
471
Georg Brandlf6945182008-02-01 11:56:49 +0000472Like for lists, there is a set comprehension syntax::
473
474 >>> a = {x for x in 'abracadabra' if x not in 'abc'}
475 >>> a
476 {'r', 'd'}
Guido van Rossum0616b792007-08-31 03:25:11 +0000477
Georg Brandl116aa622007-08-15 14:28:22 +0000478
479
480.. _tut-dictionaries:
481
482Dictionaries
483============
484
485Another useful data type built into Python is the *dictionary* (see
486:ref:`typesmapping`). Dictionaries are sometimes found in other languages as
487"associative memories" or "associative arrays". Unlike sequences, which are
488indexed by a range of numbers, dictionaries are indexed by *keys*, which can be
489any immutable type; strings and numbers can always be keys. Tuples can be used
490as keys if they contain only strings, numbers, or tuples; if a tuple contains
491any mutable object either directly or indirectly, it cannot be used as a key.
492You can't use lists as keys, since lists can be modified in place using index
493assignments, slice assignments, or methods like :meth:`append` and
494:meth:`extend`.
495
496It is best to think of a dictionary as an unordered set of *key: value* pairs,
497with the requirement that the keys are unique (within one dictionary). A pair of
498braces creates an empty dictionary: ``{}``. Placing a comma-separated list of
499key:value pairs within the braces adds initial key:value pairs to the
500dictionary; this is also the way dictionaries are written on output.
501
502The main operations on a dictionary are storing a value with some key and
503extracting the value given the key. It is also possible to delete a key:value
504pair with ``del``. If you store using a key that is already in use, the old
505value associated with that key is forgotten. It is an error to extract a value
506using a non-existent key.
507
508The :meth:`keys` method of a dictionary object returns a list of all the keys
509used in the dictionary, in arbitrary order (if you want it sorted, just apply
510the :meth:`sort` method to the list of keys). To check whether a single key is
Collin Winter19ab2bd2007-09-10 00:20:46 +0000511in the dictionary, use the :keyword:`in` keyword.
Georg Brandl116aa622007-08-15 14:28:22 +0000512
513Here is a small example using a dictionary::
514
515 >>> tel = {'jack': 4098, 'sape': 4139}
516 >>> tel['guido'] = 4127
517 >>> tel
518 {'sape': 4139, 'guido': 4127, 'jack': 4098}
519 >>> tel['jack']
520 4098
521 >>> del tel['sape']
522 >>> tel['irv'] = 4127
523 >>> tel
524 {'guido': 4127, 'irv': 4127, 'jack': 4098}
Neal Norwitze0906d12007-08-31 03:46:28 +0000525 >>> list(tel.keys())
Georg Brandl116aa622007-08-15 14:28:22 +0000526 ['guido', 'irv', 'jack']
Georg Brandl116aa622007-08-15 14:28:22 +0000527 >>> 'guido' in tel
528 True
Neal Norwitze0906d12007-08-31 03:46:28 +0000529 >>> 'jack' not in tel
530 False
Georg Brandl116aa622007-08-15 14:28:22 +0000531
532The :func:`dict` constructor builds dictionaries directly from lists of
533key-value pairs stored as tuples. When the pairs form a pattern, list
534comprehensions can compactly specify the key-value list. ::
535
536 >>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
537 {'sape': 4139, 'jack': 4098, 'guido': 4127}
Georg Brandl116aa622007-08-15 14:28:22 +0000538
Georg Brandlf6945182008-02-01 11:56:49 +0000539In addition, dict comprehensions can be used to create dictionaries from
540arbitrary key and value expressions::
541
542 >>> {x: x**2 for x in (2, 4, 6)}
543 {2: 4, 4: 16, 6: 36}
Georg Brandl116aa622007-08-15 14:28:22 +0000544
545When the keys are simple strings, it is sometimes easier to specify pairs using
546keyword arguments::
547
548 >>> dict(sape=4139, guido=4127, jack=4098)
549 {'sape': 4139, 'jack': 4098, 'guido': 4127}
550
551
Georg Brandlf6945182008-02-01 11:56:49 +0000552.. XXX Find out the right way to do these DUBOIS
Georg Brandl116aa622007-08-15 14:28:22 +0000553.. _tut-loopidioms:
554
555Looping Techniques
556==================
557
558When looping through dictionaries, the key and corresponding value can be
Neal Norwitze0906d12007-08-31 03:46:28 +0000559retrieved at the same time using the :meth:`items` method. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000560
561 >>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
Neal Norwitze0906d12007-08-31 03:46:28 +0000562 >>> for k, v in knights.items():
Guido van Rossum0616b792007-08-31 03:25:11 +0000563 ... print(k, v)
Georg Brandl116aa622007-08-15 14:28:22 +0000564 ...
565 gallahad the pure
566 robin the brave
567
568When looping through a sequence, the position index and corresponding value can
569be retrieved at the same time using the :func:`enumerate` function. ::
570
571 >>> for i, v in enumerate(['tic', 'tac', 'toe']):
Guido van Rossum0616b792007-08-31 03:25:11 +0000572 ... print(i, v)
Georg Brandl116aa622007-08-15 14:28:22 +0000573 ...
574 0 tic
575 1 tac
576 2 toe
577
578To loop over two or more sequences at the same time, the entries can be paired
579with the :func:`zip` function. ::
580
581 >>> questions = ['name', 'quest', 'favorite color']
582 >>> answers = ['lancelot', 'the holy grail', 'blue']
583 >>> for q, a in zip(questions, answers):
Guido van Rossum0616b792007-08-31 03:25:11 +0000584 ... print('What is your %s? It is %s.' % (q, a))
Georg Brandl116aa622007-08-15 14:28:22 +0000585 ...
586 What is your name? It is lancelot.
587 What is your quest? It is the holy grail.
588 What is your favorite color? It is blue.
589
590To loop over a sequence in reverse, first specify the sequence in a forward
591direction and then call the :func:`reversed` function. ::
592
Georg Brandle4ac7502007-09-03 07:10:24 +0000593 >>> for i in reversed(range(1, 10, 2)):
Guido van Rossum0616b792007-08-31 03:25:11 +0000594 ... print(i)
Georg Brandl116aa622007-08-15 14:28:22 +0000595 ...
596 9
597 7
598 5
599 3
600 1
601
602To loop over a sequence in sorted order, use the :func:`sorted` function which
603returns a new sorted list while leaving the source unaltered. ::
604
605 >>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
606 >>> for f in sorted(set(basket)):
Guido van Rossum0616b792007-08-31 03:25:11 +0000607 ... print(f)
Georg Brandl116aa622007-08-15 14:28:22 +0000608 ...
609 apple
610 banana
611 orange
612 pear
613
614
615.. _tut-conditions:
616
617More on Conditions
618==================
619
620The conditions used in ``while`` and ``if`` statements can contain any
621operators, not just comparisons.
622
623The comparison operators ``in`` and ``not in`` check whether a value occurs
624(does not occur) in a sequence. The operators ``is`` and ``is not`` compare
625whether two objects are really the same object; this only matters for mutable
626objects like lists. All comparison operators have the same priority, which is
627lower than that of all numerical operators.
628
629Comparisons can be chained. For example, ``a < b == c`` tests whether ``a`` is
630less than ``b`` and moreover ``b`` equals ``c``.
631
632Comparisons may be combined using the Boolean operators ``and`` and ``or``, and
633the outcome of a comparison (or of any other Boolean expression) may be negated
634with ``not``. These have lower priorities than comparison operators; between
635them, ``not`` has the highest priority and ``or`` the lowest, so that ``A and
636not B or C`` is equivalent to ``(A and (not B)) or C``. As always, parentheses
637can be used to express the desired composition.
638
639The Boolean operators ``and`` and ``or`` are so-called *short-circuit*
640operators: their arguments are evaluated from left to right, and evaluation
641stops as soon as the outcome is determined. For example, if ``A`` and ``C`` are
642true but ``B`` is false, ``A and B and C`` does not evaluate the expression
643``C``. When used as a general value and not as a Boolean, the return value of a
644short-circuit operator is the last evaluated argument.
645
646It is possible to assign the result of a comparison or other Boolean expression
647to a variable. For example, ::
648
649 >>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance'
650 >>> non_null = string1 or string2 or string3
651 >>> non_null
652 'Trondheim'
653
654Note that in Python, unlike C, assignment cannot occur inside expressions. C
655programmers may grumble about this, but it avoids a common class of problems
656encountered in C programs: typing ``=`` in an expression when ``==`` was
657intended.
658
659
660.. _tut-comparing:
661
662Comparing Sequences and Other Types
663===================================
664
665Sequence objects may be compared to other objects with the same sequence type.
666The comparison uses *lexicographical* ordering: first the first two items are
667compared, and if they differ this determines the outcome of the comparison; if
668they are equal, the next two items are compared, and so on, until either
669sequence is exhausted. If two items to be compared are themselves sequences of
670the same type, the lexicographical comparison is carried out recursively. If
671all items of two sequences compare equal, the sequences are considered equal.
672If one sequence is an initial sub-sequence of the other, the shorter sequence is
673the smaller (lesser) one. Lexicographical ordering for strings uses the ASCII
674ordering for individual characters. Some examples of comparisons between
675sequences of the same type::
676
677 (1, 2, 3) < (1, 2, 4)
678 [1, 2, 3] < [1, 2, 4]
679 'ABC' < 'C' < 'Pascal' < 'Python'
680 (1, 2, 3, 4) < (1, 2, 4)
681 (1, 2) < (1, 2, -1)
682 (1, 2, 3) == (1.0, 2.0, 3.0)
683 (1, 2, ('aa', 'ab')) < (1, 2, ('abc', 'a'), 4)
684
Georg Brandl9f2c39a2007-10-08 14:08:36 +0000685Note that comparing objects of different types with ``<`` or ``>`` is legal
686provided that the objects have appropriate comparison methods. For example,
687mixed numeric types are compared according to their numeric value, so 0 equals
6880.0, etc. Otherwise, rather than providing an arbitrary ordering, the
689interpreter will raise a :exc:`TypeError` exception.