blob: f55674e8fd4f9ea99066f14ac9159bd03ea8e218 [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
Ezio Melotti4a72d1a2011-12-13 14:50:21 +0200238List comprehensions provide a concise way to create lists.
239Common applications are to make new lists where each element is the result of
240some operations applied to each member of another sequence or iterable, or to
241create a subsequence of those elements that satisfy a certain condition.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000242
Ezio Melotti4a72d1a2011-12-13 14:50:21 +0200243For example, assume we want to create a list of squares, like::
244
245 >>> squares = []
246 >>> for x in range(10):
247 ... squares.append(x**2)
248 ...
249 >>> squares
250 [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
251
252We can obtain the same result with::
253
254 squares = [x**2 for x in range(10)]
255
256This is also equivalent to ``squares = map(lambda x: x**2, range(10))``,
257but it's more concise and readable.
258
259A list comprehension consists of brackets containing an expression followed
260by a :keyword:`for` clause, then zero or more :keyword:`for` or :keyword:`if`
261clauses. The result will be a new list resulting from evaluating the expression
262in the context of the :keyword:`for` and :keyword:`if` clauses which follow it.
263For example, this listcomp combines the elements of two lists if they are not
264equal::
265
266 >>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
267 [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
268
269and it's equivalent to:
270
271 >>> combs = []
272 >>> for x in [1,2,3]:
273 ... for y in [3,1,4]:
274 ... if x != y:
275 ... combs.append((x, y))
276 ...
277 >>> combs
278 [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
279
280Note how the order of the :keyword:`for` and :keyword:`if` statements is the
281same in both these snippets.
282
283If the expression is a tuple (e.g. the ``(x, y)`` in the previous example),
284it must be parenthesized. ::
285
286 >>> vec = [-4, -2, 0, 2, 4]
287 >>> # create a new list with the values doubled
288 >>> [x*2 for x in vec]
289 [-8, -4, 0, 4, 8]
290 >>> # filter the list to exclude negative numbers
291 >>> [x for x in vec if x >= 0]
292 [0, 2, 4]
293 >>> # apply a function to all the elements
294 >>> [abs(x) for x in vec]
295 [4, 2, 0, 2, 4]
296 >>> # call a method on each element
Georg Brandl8ec7f652007-08-15 14:28:01 +0000297 >>> freshfruit = [' banana', ' loganberry ', 'passion fruit ']
298 >>> [weapon.strip() for weapon in freshfruit]
299 ['banana', 'loganberry', 'passion fruit']
Ezio Melotti4a72d1a2011-12-13 14:50:21 +0200300 >>> # create a list of 2-tuples like (number, square)
301 >>> [(x, x**2) for x in range(6)]
302 [(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]
303 >>> # the tuple must be parenthesized, otherwise an error is raised
304 >>> [x, x**2 for x in range(6)]
305 File "<stdin>", line 1
306 [x, x**2 for x in range(6)]
Georg Brandl8ec7f652007-08-15 14:28:01 +0000307 ^
308 SyntaxError: invalid syntax
Ezio Melotti4a72d1a2011-12-13 14:50:21 +0200309 >>> # flatten a list using a listcomp with two 'for'
310 >>> vec = [[1,2,3], [4,5,6], [7,8,9]]
311 >>> [num for elem in vec for num in elem]
312 [1, 2, 3, 4, 5, 6, 7, 8, 9]
Georg Brandl8ec7f652007-08-15 14:28:01 +0000313
Ezio Melotti4a72d1a2011-12-13 14:50:21 +0200314List comprehensions can contain complex expressions and nested functions::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000315
Ezio Melotti4a72d1a2011-12-13 14:50:21 +0200316 >>> from math import pi
317 >>> [str(round(pi, i)) for i in range(1, 6)]
Georg Brandl8ec7f652007-08-15 14:28:01 +0000318 ['3.1', '3.14', '3.142', '3.1416', '3.14159']
319
320
Georg Brandladbda842007-12-14 19:03:36 +0000321Nested List Comprehensions
Ezio Melotti4a72d1a2011-12-13 14:50:21 +0200322''''''''''''''''''''''''''
Georg Brandladbda842007-12-14 19:03:36 +0000323
Ezio Melotti4a72d1a2011-12-13 14:50:21 +0200324The initial expression in a list comprehension can be any arbitrary expression,
325including another list comprehension.
Georg Brandladbda842007-12-14 19:03:36 +0000326
Ezio Melotti4a72d1a2011-12-13 14:50:21 +0200327Consider the following example of a 3x4 matrix implemented as a list of
3283 lists of length 4::
Georg Brandladbda842007-12-14 19:03:36 +0000329
Ezio Melotti4a72d1a2011-12-13 14:50:21 +0200330 >>> matrix = [
331 ... [1, 2, 3, 4],
332 ... [5, 6, 7, 8],
333 ... [9, 10, 11, 12],
334 ... ]
Georg Brandladbda842007-12-14 19:03:36 +0000335
Ezio Melotti4a72d1a2011-12-13 14:50:21 +0200336The following list comprehension will transpose rows and columns::
Georg Brandladbda842007-12-14 19:03:36 +0000337
Ezio Melotti4a72d1a2011-12-13 14:50:21 +0200338 >>> [[row[i] for row in matrix] for i in range(4)]
339 [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
Georg Brandladbda842007-12-14 19:03:36 +0000340
Ezio Melotti4a72d1a2011-12-13 14:50:21 +0200341As we saw in the previous section, the nested listcomp is evaluated in
342the context of the :keyword:`for` that follows it, so this example is
343equivalent to::
Georg Brandladbda842007-12-14 19:03:36 +0000344
Ezio Melotti4a72d1a2011-12-13 14:50:21 +0200345 >>> transposed = []
346 >>> for i in range(4):
347 ... transposed.append([row[i] for row in matrix])
348 ...
349 >>> transposed
350 [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
Georg Brandladbda842007-12-14 19:03:36 +0000351
Ezio Melotti4a72d1a2011-12-13 14:50:21 +0200352which, in turn, is the same as::
Georg Brandladbda842007-12-14 19:03:36 +0000353
Ezio Melotti4a72d1a2011-12-13 14:50:21 +0200354 >>> transposed = []
355 >>> for i in range(4):
356 ... # the following 3 lines implement the nested listcomp
357 ... transposed_row = []
358 ... for row in matrix:
359 ... transposed_row.append(row[i])
360 ... transposed.append(transposed_row)
361 ...
362 >>> transposed
363 [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
Georg Brandladbda842007-12-14 19:03:36 +0000364
Ezio Melotti4a72d1a2011-12-13 14:50:21 +0200365
366In the real world, you should prefer built-in functions to complex flow statements.
Georg Brandladbda842007-12-14 19:03:36 +0000367The :func:`zip` function would do a great job for this use case::
368
Ezio Melotti4a72d1a2011-12-13 14:50:21 +0200369 >>> zip(*matrix)
370 [(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]
Georg Brandladbda842007-12-14 19:03:36 +0000371
372See :ref:`tut-unpacking-arguments` for details on the asterisk in this line.
373
Georg Brandl8ec7f652007-08-15 14:28:01 +0000374.. _tut-del:
375
376The :keyword:`del` statement
377============================
378
379There is a way to remove an item from a list given its index instead of its
380value: the :keyword:`del` statement. This differs from the :meth:`pop` method
381which returns a value. The :keyword:`del` statement can also be used to remove
382slices from a list or clear the entire list (which we did earlier by assignment
383of an empty list to the slice). For example::
384
385 >>> a = [-1, 1, 66.25, 333, 333, 1234.5]
386 >>> del a[0]
387 >>> a
388 [1, 66.25, 333, 333, 1234.5]
389 >>> del a[2:4]
390 >>> a
391 [1, 66.25, 1234.5]
392 >>> del a[:]
393 >>> a
394 []
395
396:keyword:`del` can also be used to delete entire variables::
397
398 >>> del a
399
400Referencing the name ``a`` hereafter is an error (at least until another value
401is assigned to it). We'll find other uses for :keyword:`del` later.
402
403
404.. _tut-tuples:
405
406Tuples and Sequences
407====================
408
409We saw that lists and strings have many common properties, such as indexing and
410slicing operations. They are two examples of *sequence* data types (see
411:ref:`typesseq`). Since Python is an evolving language, other sequence data
412types may be added. There is also another standard sequence data type: the
413*tuple*.
414
415A tuple consists of a number of values separated by commas, for instance::
416
417 >>> t = 12345, 54321, 'hello!'
418 >>> t[0]
419 12345
420 >>> t
421 (12345, 54321, 'hello!')
422 >>> # Tuples may be nested:
423 ... u = t, (1, 2, 3, 4, 5)
424 >>> u
425 ((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))
Ezio Melottif6379202012-06-17 14:10:59 +0200426 >>> # Tuples are immutable:
427 ... t[0] = 88888
428 Traceback (most recent call last):
429 File "<stdin>", line 1, in <module>
430 TypeError: 'tuple' object does not support item assignment
431 >>> # but they can contain mutable objects:
432 ... v = ([1, 2, 3], [3, 2, 1])
433 >>> v
434 ([1, 2, 3], [3, 2, 1])
435
Georg Brandl8ec7f652007-08-15 14:28:01 +0000436
437As you see, on output tuples are always enclosed in parentheses, so that nested
438tuples are interpreted correctly; they may be input with or without surrounding
439parentheses, although often parentheses are necessary anyway (if the tuple is
Ezio Melottif6379202012-06-17 14:10:59 +0200440part of a larger expression). It is not possible to assign to the individual
441items of a tuple, however it is possible to create tuples which contain mutable
442objects, such as lists.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000443
Ezio Melottif6379202012-06-17 14:10:59 +0200444Though tuples may seem similar to lists, they are often used in different
445situations and for different purposes.
446Tuples are :term:`immutable`, and usually contain an heterogeneous sequence of
447elements that are accessed via unpacking (see later in this section) or indexing
448(or even by attribute in the case of :func:`namedtuples <collections.namedtuple>`).
449Lists are :term:`mutable`, and their elements are usually homogeneous and are
450accessed by iterating over the list.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000451
452A special problem is the construction of tuples containing 0 or 1 items: the
453syntax has some extra quirks to accommodate these. Empty tuples are constructed
454by an empty pair of parentheses; a tuple with one item is constructed by
455following a value with a comma (it is not sufficient to enclose a single value
456in parentheses). Ugly, but effective. For example::
457
458 >>> empty = ()
459 >>> singleton = 'hello', # <-- note trailing comma
460 >>> len(empty)
461 0
462 >>> len(singleton)
463 1
464 >>> singleton
465 ('hello',)
466
467The statement ``t = 12345, 54321, 'hello!'`` is an example of *tuple packing*:
468the values ``12345``, ``54321`` and ``'hello!'`` are packed together in a tuple.
469The reverse operation is also possible::
470
471 >>> x, y, z = t
472
Georg Brandl354e4cb2009-03-31 22:40:16 +0000473This is called, appropriately enough, *sequence unpacking* and works for any
474sequence on the right-hand side. Sequence unpacking requires the list of
475variables on the left to have the same number of elements as the length of the
476sequence. Note that multiple assignment is really just a combination of tuple
Georg Brandla08867d2009-03-31 23:01:27 +0000477packing and sequence unpacking.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000478
Georg Brandl8ec7f652007-08-15 14:28:01 +0000479
480.. _tut-sets:
481
482Sets
483====
484
485Python also includes a data type for *sets*. A set is an unordered collection
486with no duplicate elements. Basic uses include membership testing and
487eliminating duplicate entries. Set objects also support mathematical operations
488like union, intersection, difference, and symmetric difference.
489
490Here is a brief demonstration::
491
492 >>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
493 >>> fruit = set(basket) # create a set without duplicates
494 >>> fruit
495 set(['orange', 'pear', 'apple', 'banana'])
496 >>> 'orange' in fruit # fast membership testing
497 True
498 >>> 'crabgrass' in fruit
499 False
500
501 >>> # Demonstrate set operations on unique letters from two words
502 ...
503 >>> a = set('abracadabra')
504 >>> b = set('alacazam')
505 >>> a # unique letters in a
506 set(['a', 'r', 'b', 'c', 'd'])
507 >>> a - b # letters in a but not in b
508 set(['r', 'd', 'b'])
509 >>> a | b # letters in either a or b
510 set(['a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'])
511 >>> a & b # letters in both a and b
512 set(['a', 'c'])
513 >>> a ^ b # letters in a or b but not both
514 set(['r', 'd', 'b', 'm', 'z', 'l'])
515
516
517.. _tut-dictionaries:
518
519Dictionaries
520============
521
522Another useful data type built into Python is the *dictionary* (see
523:ref:`typesmapping`). Dictionaries are sometimes found in other languages as
524"associative memories" or "associative arrays". Unlike sequences, which are
525indexed by a range of numbers, dictionaries are indexed by *keys*, which can be
526any immutable type; strings and numbers can always be keys. Tuples can be used
527as keys if they contain only strings, numbers, or tuples; if a tuple contains
528any mutable object either directly or indirectly, it cannot be used as a key.
529You can't use lists as keys, since lists can be modified in place using index
530assignments, slice assignments, or methods like :meth:`append` and
531:meth:`extend`.
532
533It is best to think of a dictionary as an unordered set of *key: value* pairs,
534with the requirement that the keys are unique (within one dictionary). A pair of
535braces creates an empty dictionary: ``{}``. Placing a comma-separated list of
536key:value pairs within the braces adds initial key:value pairs to the
537dictionary; this is also the way dictionaries are written on output.
538
539The main operations on a dictionary are storing a value with some key and
540extracting the value given the key. It is also possible to delete a key:value
541pair with ``del``. If you store using a key that is already in use, the old
542value associated with that key is forgotten. It is an error to extract a value
543using a non-existent key.
544
545The :meth:`keys` method of a dictionary object returns a list of all the keys
546used in the dictionary, in arbitrary order (if you want it sorted, just apply
Georg Brandl44c3ceb2010-10-15 15:31:09 +0000547the :func:`sorted` function to it). To check whether a single key is in the
548dictionary, use the :keyword:`in` keyword.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000549
550Here is a small example using a dictionary::
551
552 >>> tel = {'jack': 4098, 'sape': 4139}
553 >>> tel['guido'] = 4127
554 >>> tel
555 {'sape': 4139, 'guido': 4127, 'jack': 4098}
556 >>> tel['jack']
557 4098
558 >>> del tel['sape']
559 >>> tel['irv'] = 4127
560 >>> tel
561 {'guido': 4127, 'irv': 4127, 'jack': 4098}
562 >>> tel.keys()
563 ['guido', 'irv', 'jack']
Georg Brandl8ec7f652007-08-15 14:28:01 +0000564 >>> 'guido' in tel
565 True
566
567The :func:`dict` constructor builds dictionaries directly from lists of
568key-value pairs stored as tuples. When the pairs form a pattern, list
569comprehensions can compactly specify the key-value list. ::
570
571 >>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
572 {'sape': 4139, 'jack': 4098, 'guido': 4127}
573 >>> dict([(x, x**2) for x in (2, 4, 6)]) # use a list comprehension
574 {2: 4, 4: 16, 6: 36}
575
576Later in the tutorial, we will learn about Generator Expressions which are even
577better suited for the task of supplying key-values pairs to the :func:`dict`
578constructor.
579
580When the keys are simple strings, it is sometimes easier to specify pairs using
581keyword arguments::
582
583 >>> dict(sape=4139, guido=4127, jack=4098)
584 {'sape': 4139, 'jack': 4098, 'guido': 4127}
585
586
587.. _tut-loopidioms:
588
589Looping Techniques
590==================
591
Georg Brandl8ec7f652007-08-15 14:28:01 +0000592When looping through a sequence, the position index and corresponding value can
593be retrieved at the same time using the :func:`enumerate` function. ::
594
595 >>> for i, v in enumerate(['tic', 'tac', 'toe']):
596 ... print i, v
597 ...
598 0 tic
599 1 tac
600 2 toe
601
602To loop over two or more sequences at the same time, the entries can be paired
603with the :func:`zip` function. ::
604
605 >>> questions = ['name', 'quest', 'favorite color']
606 >>> answers = ['lancelot', 'the holy grail', 'blue']
607 >>> for q, a in zip(questions, answers):
Benjamin Petersonf9ef9882008-05-26 00:54:22 +0000608 ... print 'What is your {0}? It is {1}.'.format(q, a)
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000609 ...
Georg Brandl8ec7f652007-08-15 14:28:01 +0000610 What is your name? It is lancelot.
611 What is your quest? It is the holy grail.
612 What is your favorite color? It is blue.
613
614To loop over a sequence in reverse, first specify the sequence in a forward
615direction and then call the :func:`reversed` function. ::
616
617 >>> for i in reversed(xrange(1,10,2)):
618 ... print i
619 ...
620 9
621 7
622 5
623 3
624 1
625
626To loop over a sequence in sorted order, use the :func:`sorted` function which
627returns a new sorted list while leaving the source unaltered. ::
628
629 >>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
630 >>> for f in sorted(set(basket)):
631 ... print f
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000632 ...
Georg Brandl8ec7f652007-08-15 14:28:01 +0000633 apple
634 banana
635 orange
636 pear
637
Raymond Hettinger4c8d3922012-04-23 21:24:15 -0700638When looping through dictionaries, the key and corresponding value can be
639retrieved at the same time using the :meth:`iteritems` method. ::
640
641 >>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
642 >>> for k, v in knights.iteritems():
643 ... print k, v
644 ...
645 gallahad the pure
646 robin the brave
647
Georg Brandl8ec7f652007-08-15 14:28:01 +0000648
649.. _tut-conditions:
650
651More on Conditions
652==================
653
654The conditions used in ``while`` and ``if`` statements can contain any
655operators, not just comparisons.
656
657The comparison operators ``in`` and ``not in`` check whether a value occurs
658(does not occur) in a sequence. The operators ``is`` and ``is not`` compare
659whether two objects are really the same object; this only matters for mutable
660objects like lists. All comparison operators have the same priority, which is
661lower than that of all numerical operators.
662
663Comparisons can be chained. For example, ``a < b == c`` tests whether ``a`` is
664less than ``b`` and moreover ``b`` equals ``c``.
665
666Comparisons may be combined using the Boolean operators ``and`` and ``or``, and
667the outcome of a comparison (or of any other Boolean expression) may be negated
668with ``not``. These have lower priorities than comparison operators; between
669them, ``not`` has the highest priority and ``or`` the lowest, so that ``A and
670not B or C`` is equivalent to ``(A and (not B)) or C``. As always, parentheses
671can be used to express the desired composition.
672
673The Boolean operators ``and`` and ``or`` are so-called *short-circuit*
674operators: their arguments are evaluated from left to right, and evaluation
675stops as soon as the outcome is determined. For example, if ``A`` and ``C`` are
676true but ``B`` is false, ``A and B and C`` does not evaluate the expression
677``C``. When used as a general value and not as a Boolean, the return value of a
678short-circuit operator is the last evaluated argument.
679
680It is possible to assign the result of a comparison or other Boolean expression
681to a variable. For example, ::
682
683 >>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance'
684 >>> non_null = string1 or string2 or string3
685 >>> non_null
686 'Trondheim'
687
688Note that in Python, unlike C, assignment cannot occur inside expressions. C
689programmers may grumble about this, but it avoids a common class of problems
690encountered in C programs: typing ``=`` in an expression when ``==`` was
691intended.
692
693
694.. _tut-comparing:
695
696Comparing Sequences and Other Types
697===================================
698
699Sequence objects may be compared to other objects with the same sequence type.
700The comparison uses *lexicographical* ordering: first the first two items are
701compared, and if they differ this determines the outcome of the comparison; if
702they are equal, the next two items are compared, and so on, until either
703sequence is exhausted. If two items to be compared are themselves sequences of
704the same type, the lexicographical comparison is carried out recursively. If
705all items of two sequences compare equal, the sequences are considered equal.
706If one sequence is an initial sub-sequence of the other, the shorter sequence is
707the smaller (lesser) one. Lexicographical ordering for strings uses the ASCII
708ordering for individual characters. Some examples of comparisons between
709sequences of the same type::
710
711 (1, 2, 3) < (1, 2, 4)
712 [1, 2, 3] < [1, 2, 4]
713 'ABC' < 'C' < 'Pascal' < 'Python'
714 (1, 2, 3, 4) < (1, 2, 4)
715 (1, 2) < (1, 2, -1)
716 (1, 2, 3) == (1.0, 2.0, 3.0)
717 (1, 2, ('aa', 'ab')) < (1, 2, ('abc', 'a'), 4)
718
719Note that comparing objects of different types is legal. The outcome is
720deterministic but arbitrary: the types are ordered by their name. Thus, a list
721is always smaller than a string, a string is always smaller than a tuple, etc.
722[#]_ Mixed numeric types are compared according to their numeric value, so 0
723equals 0.0, etc.
724
725
726.. rubric:: Footnotes
727
728.. [#] The rules for comparing objects of different types should not be relied upon;
729 they may change in a future version of the language.
730