blob: 5fb72fdbaf002eb228d03f1743b584711880a17e [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
Georg Brandl116aa622007-08-15 14:28:22 +000010.. _tut-morelists:
11
12More on Lists
13=============
14
15The list data type has some more methods. Here are all of the methods of list
16objects:
17
18
19.. method:: list.append(x)
Christian Heimes4fbc72b2008-03-22 00:47:35 +000020 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +000021
22 Add an item to the end of the list; equivalent to ``a[len(a):] = [x]``.
23
24
25.. method:: list.extend(L)
Christian Heimes4fbc72b2008-03-22 00:47:35 +000026 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +000027
28 Extend the list by appending all the items in the given list; equivalent to
29 ``a[len(a):] = L``.
30
31
32.. method:: list.insert(i, x)
Christian Heimes4fbc72b2008-03-22 00:47:35 +000033 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +000034
35 Insert an item at a given position. The first argument is the index of the
36 element before which to insert, so ``a.insert(0, x)`` inserts at the front of
37 the list, and ``a.insert(len(a), x)`` is equivalent to ``a.append(x)``.
38
39
40.. method:: list.remove(x)
Christian Heimes4fbc72b2008-03-22 00:47:35 +000041 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +000042
43 Remove the first item from the list whose value is *x*. It is an error if there
44 is no such item.
45
46
47.. method:: list.pop([i])
Christian Heimes4fbc72b2008-03-22 00:47:35 +000048 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +000049
50 Remove the item at the given position in the list, and return it. If no index
51 is specified, ``a.pop()`` removes and returns the last item in the list. (The
52 square brackets around the *i* in the method signature denote that the parameter
53 is optional, not that you should type square brackets at that position. You
54 will see this notation frequently in the Python Library Reference.)
55
56
57.. method:: list.index(x)
Christian Heimes4fbc72b2008-03-22 00:47:35 +000058 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +000059
60 Return the index in the list of the first item whose value is *x*. It is an
61 error if there is no such item.
62
63
64.. method:: list.count(x)
Christian Heimes4fbc72b2008-03-22 00:47:35 +000065 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +000066
67 Return the number of times *x* appears in the list.
68
69
70.. method:: list.sort()
Christian Heimes4fbc72b2008-03-22 00:47:35 +000071 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +000072
73 Sort the items of the list, in place.
74
75
76.. method:: list.reverse()
Christian Heimes4fbc72b2008-03-22 00:47:35 +000077 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +000078
79 Reverse the elements of the list, in place.
80
81An example that uses most of the list methods::
82
83 >>> a = [66.25, 333, 333, 1, 1234.5]
Guido van Rossum0616b792007-08-31 03:25:11 +000084 >>> print(a.count(333), a.count(66.25), a.count('x'))
Georg Brandl116aa622007-08-15 14:28:22 +000085 2 1 0
86 >>> a.insert(2, -1)
87 >>> a.append(333)
88 >>> a
89 [66.25, 333, -1, 333, 1, 1234.5, 333]
90 >>> a.index(333)
91 1
92 >>> a.remove(333)
93 >>> a
94 [66.25, -1, 333, 1, 1234.5, 333]
95 >>> a.reverse()
96 >>> a
97 [333, 1234.5, 1, 333, -1, 66.25]
98 >>> a.sort()
99 >>> a
100 [-1, 1, 66.25, 333, 333, 1234.5]
101
102
103.. _tut-lists-as-stacks:
104
105Using Lists as Stacks
106---------------------
107
108.. sectionauthor:: Ka-Ping Yee <ping@lfw.org>
109
110
111The list methods make it very easy to use a list as a stack, where the last
112element added is the first element retrieved ("last-in, first-out"). To add an
113item to the top of the stack, use :meth:`append`. To retrieve an item from the
114top of the stack, use :meth:`pop` without an explicit index. For example::
115
116 >>> stack = [3, 4, 5]
117 >>> stack.append(6)
118 >>> stack.append(7)
119 >>> stack
120 [3, 4, 5, 6, 7]
121 >>> stack.pop()
122 7
123 >>> stack
124 [3, 4, 5, 6]
125 >>> stack.pop()
126 6
127 >>> stack.pop()
128 5
129 >>> stack
130 [3, 4]
131
132
133.. _tut-lists-as-queues:
134
135Using Lists as Queues
136---------------------
137
138.. sectionauthor:: Ka-Ping Yee <ping@lfw.org>
139
Ezio Melotti8f8db142010-03-31 07:45:32 +0000140It is also possible to use a list as a queue, where the first element added is
141the first element retrieved ("first-in, first-out"); however, lists are not
142efficient for this purpose. While appends and pops from the end of list are
143fast, doing inserts or pops from the beginning of a list is slow (because all
144of the other elements have to be shifted by one).
Georg Brandl116aa622007-08-15 14:28:22 +0000145
Ezio Melotti8f8db142010-03-31 07:45:32 +0000146To implement a queue, use :class:`collections.deque` which was designed to
147have fast appends and pops from both ends. For example::
Georg Brandl116aa622007-08-15 14:28:22 +0000148
Ezio Melotti8f8db142010-03-31 07:45:32 +0000149 >>> from collections import deque
150 >>> queue = deque(["Eric", "John", "Michael"])
Georg Brandl116aa622007-08-15 14:28:22 +0000151 >>> queue.append("Terry") # Terry arrives
152 >>> queue.append("Graham") # Graham arrives
Ezio Melotti8f8db142010-03-31 07:45:32 +0000153 >>> queue.popleft() # The first to arrive now leaves
Georg Brandl116aa622007-08-15 14:28:22 +0000154 'Eric'
Ezio Melotti8f8db142010-03-31 07:45:32 +0000155 >>> queue.popleft() # The second to arrive now leaves
Georg Brandl116aa622007-08-15 14:28:22 +0000156 'John'
Ezio Melotti8f8db142010-03-31 07:45:32 +0000157 >>> queue # Remaining queue in order of arrival
158 deque(['Michael', 'Terry', 'Graham'])
Georg Brandl718ce2c2010-03-21 09:51:44 +0000159
Georg Brandl116aa622007-08-15 14:28:22 +0000160
Georg Brandlfc11f272009-06-16 19:22:10 +0000161.. _tut-listcomps:
162
Georg Brandl116aa622007-08-15 14:28:22 +0000163List Comprehensions
164-------------------
165
Ezio Melotti91621e22011-12-13 15:36:19 +0200166List comprehensions provide a concise way to create lists.
167Common applications are to make new lists where each element is the result of
168some operations applied to each member of another sequence or iterable, or to
169create a subsequence of those elements that satisfy a certain condition.
170
171For example, assume we want to create a list of squares, like::
172
173 >>> squares = []
174 >>> for x in range(10):
175 ... squares.append(x**2)
176 ...
177 >>> squares
178 [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
179
180We can obtain the same result with::
181
182 squares = [x**2 for x in range(10)]
183
184This is also equivalent to ``squares = map(lambda x: x**2, range(10))``,
185but it's more concise and readable.
Guido van Rossum0616b792007-08-31 03:25:11 +0000186
Georg Brandl7ae90dd2009-06-08 18:59:09 +0000187A list comprehension consists of brackets containing an expression followed
188by a :keyword:`for` clause, then zero or more :keyword:`for` or :keyword:`if`
Ezio Melotti91621e22011-12-13 15:36:19 +0200189clauses. The result will be a new list resulting from evaluating the expression
190in the context of the :keyword:`for` and :keyword:`if` clauses which follow it.
191For example, this listcomp combines the elements of two lists if they are not
192equal::
Guido van Rossum0616b792007-08-31 03:25:11 +0000193
Ezio Melotti91621e22011-12-13 15:36:19 +0200194 >>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
195 [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
Guido van Rossum0616b792007-08-31 03:25:11 +0000196
Ezio Melotti91621e22011-12-13 15:36:19 +0200197and it's equivalent to::
Guido van Rossum0616b792007-08-31 03:25:11 +0000198
Ezio Melotti91621e22011-12-13 15:36:19 +0200199 >>> combs = []
200 >>> for x in [1,2,3]:
201 ... for y in [3,1,4]:
202 ... if x != y:
203 ... combs.append((x, y))
204 ...
205 >>> combs
206 [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
Guido van Rossum0616b792007-08-31 03:25:11 +0000207
Ezio Melotti91621e22011-12-13 15:36:19 +0200208Note how the order of the :keyword:`for` and :keyword:`if` statements is the
209same in both these snippets.
Guido van Rossum0616b792007-08-31 03:25:11 +0000210
Ezio Melotti91621e22011-12-13 15:36:19 +0200211If the expression is a tuple (e.g. the ``(x, y)`` in the previous example),
212it must be parenthesized. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000213
Ezio Melotti91621e22011-12-13 15:36:19 +0200214 >>> vec = [-4, -2, 0, 2, 4]
215 >>> # create a new list with the values doubled
216 >>> [x*2 for x in vec]
217 [-8, -4, 0, 4, 8]
218 >>> # filter the list to exclude negative numbers
219 >>> [x for x in vec if x >= 0]
220 [0, 2, 4]
221 >>> # apply a function to all the elements
222 >>> [abs(x) for x in vec]
223 [4, 2, 0, 2, 4]
224 >>> # call a method on each element
Georg Brandl116aa622007-08-15 14:28:22 +0000225 >>> freshfruit = [' banana', ' loganberry ', 'passion fruit ']
226 >>> [weapon.strip() for weapon in freshfruit]
227 ['banana', 'loganberry', 'passion fruit']
Ezio Melotti91621e22011-12-13 15:36:19 +0200228 >>> # create a list of 2-tuples like (number, square)
229 >>> [(x, x**2) for x in range(6)]
230 [(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]
231 >>> # the tuple must be parenthesized, otherwise an error is raised
232 >>> [x, x**2 for x in range(6)]
Georg Brandl116aa622007-08-15 14:28:22 +0000233 File "<stdin>", line 1, in ?
Ezio Melotti91621e22011-12-13 15:36:19 +0200234 [x, x**2 for x in range(6)]
Georg Brandl116aa622007-08-15 14:28:22 +0000235 ^
236 SyntaxError: invalid syntax
Ezio Melotti91621e22011-12-13 15:36:19 +0200237 >>> # flatten a list using a listcomp with two 'for'
238 >>> vec = [[1,2,3], [4,5,6], [7,8,9]]
239 >>> [num for elem in vec for num in elem]
240 [1, 2, 3, 4, 5, 6, 7, 8, 9]
Guido van Rossum0616b792007-08-31 03:25:11 +0000241
Ezio Melotti91621e22011-12-13 15:36:19 +0200242List comprehensions can contain complex expressions and nested functions::
Guido van Rossum0616b792007-08-31 03:25:11 +0000243
Ezio Melotti91621e22011-12-13 15:36:19 +0200244 >>> from math import pi
245 >>> [str(round(pi, i)) for i in range(1, 6)]
Georg Brandl116aa622007-08-15 14:28:22 +0000246 ['3.1', '3.14', '3.142', '3.1416', '3.14159']
247
Christian Heimes0449f632007-12-15 01:27:15 +0000248Nested List Comprehensions
249--------------------------
250
Ezio Melotti91621e22011-12-13 15:36:19 +0200251The initial expression in a list comprehension can be any arbitrary expression,
252including another list comprehension.
Christian Heimes0449f632007-12-15 01:27:15 +0000253
Ezio Melotti91621e22011-12-13 15:36:19 +0200254Consider the following example of a 3x4 matrix implemented as a list of
2553 lists of length 4::
Christian Heimes0449f632007-12-15 01:27:15 +0000256
Ezio Melotti91621e22011-12-13 15:36:19 +0200257 >>> matrix = [
258 ... [1, 2, 3, 4],
259 ... [5, 6, 7, 8],
260 ... [9, 10, 11, 12],
261 ... ]
Christian Heimes0449f632007-12-15 01:27:15 +0000262
Ezio Melotti91621e22011-12-13 15:36:19 +0200263The following list comprehension will transpose rows and columns::
Christian Heimes0449f632007-12-15 01:27:15 +0000264
Ezio Melotti91621e22011-12-13 15:36:19 +0200265 >>> [[row[i] for row in matrix] for i in range(4)]
266 [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
Christian Heimes0449f632007-12-15 01:27:15 +0000267
Ezio Melotti91621e22011-12-13 15:36:19 +0200268As we saw in the previous section, the nested listcomp is evaluated in
269the context of the :keyword:`for` that follows it, so this example is
270equivalent to::
Christian Heimes0449f632007-12-15 01:27:15 +0000271
Ezio Melotti91621e22011-12-13 15:36:19 +0200272 >>> transposed = []
273 >>> for i in range(4):
274 ... transposed.append([row[i] for row in matrix])
275 ...
276 >>> transposed
277 [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
Christian Heimes0449f632007-12-15 01:27:15 +0000278
Ezio Melotti91621e22011-12-13 15:36:19 +0200279which, in turn, is the same as::
Christian Heimes0449f632007-12-15 01:27:15 +0000280
Ezio Melotti91621e22011-12-13 15:36:19 +0200281 >>> transposed = []
282 >>> for i in range(4):
283 ... # the following 3 lines implement the nested listcomp
284 ... transposed_row = []
285 ... for row in matrix:
286 ... transposed_row.append(row[i])
287 ... transposed.append(transposed_row)
288 ...
289 >>> transposed
290 [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
Christian Heimes0449f632007-12-15 01:27:15 +0000291
Ezio Melotti91621e22011-12-13 15:36:19 +0200292In the real world, you should prefer built-in functions to complex flow statements.
Christian Heimes0449f632007-12-15 01:27:15 +0000293The :func:`zip` function would do a great job for this use case::
294
Ezio Melotti91621e22011-12-13 15:36:19 +0200295 >>> zip(*matrix)
296 [(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]
Christian Heimes0449f632007-12-15 01:27:15 +0000297
298See :ref:`tut-unpacking-arguments` for details on the asterisk in this line.
299
Georg Brandl116aa622007-08-15 14:28:22 +0000300.. _tut-del:
301
302The :keyword:`del` statement
303============================
304
305There is a way to remove an item from a list given its index instead of its
306value: the :keyword:`del` statement. This differs from the :meth:`pop` method
307which returns a value. The :keyword:`del` statement can also be used to remove
308slices from a list or clear the entire list (which we did earlier by assignment
309of an empty list to the slice). For example::
310
311 >>> a = [-1, 1, 66.25, 333, 333, 1234.5]
312 >>> del a[0]
313 >>> a
314 [1, 66.25, 333, 333, 1234.5]
315 >>> del a[2:4]
316 >>> a
317 [1, 66.25, 1234.5]
318 >>> del a[:]
319 >>> a
320 []
321
322:keyword:`del` can also be used to delete entire variables::
323
324 >>> del a
325
326Referencing the name ``a`` hereafter is an error (at least until another value
327is assigned to it). We'll find other uses for :keyword:`del` later.
328
329
Georg Brandl5d955ed2008-09-13 17:18:21 +0000330.. _tut-tuples:
Georg Brandl116aa622007-08-15 14:28:22 +0000331
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000332Tuples and Sequences
333====================
334
335We saw that lists and strings have many common properties, such as indexing and
336slicing operations. They are two examples of *sequence* data types (see
337:ref:`typesseq`). Since Python is an evolving language, other sequence data
338types may be added. There is also another standard sequence data type: the
339*tuple*.
340
341A tuple consists of a number of values separated by commas, for instance::
342
343 >>> t = 12345, 54321, 'hello!'
344 >>> t[0]
345 12345
346 >>> t
347 (12345, 54321, 'hello!')
348 >>> # Tuples may be nested:
349 ... u = t, (1, 2, 3, 4, 5)
350 >>> u
351 ((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))
352
353As you see, on output tuples are always enclosed in parentheses, so that nested
354tuples are interpreted correctly; they may be input with or without surrounding
355parentheses, although often parentheses are necessary anyway (if the tuple is
356part of a larger expression).
357
358Tuples have many uses. For example: (x, y) coordinate pairs, employee records
359from a database, etc. Tuples, like strings, are immutable: it is not possible
360to assign to the individual items of a tuple (you can simulate much of the same
361effect with slicing and concatenation, though). It is also possible to create
362tuples which contain mutable objects, such as lists.
363
364A special problem is the construction of tuples containing 0 or 1 items: the
365syntax has some extra quirks to accommodate these. Empty tuples are constructed
366by an empty pair of parentheses; a tuple with one item is constructed by
367following a value with a comma (it is not sufficient to enclose a single value
368in parentheses). Ugly, but effective. For example::
369
370 >>> empty = ()
371 >>> singleton = 'hello', # <-- note trailing comma
372 >>> len(empty)
373 0
374 >>> len(singleton)
375 1
376 >>> singleton
377 ('hello',)
378
379The statement ``t = 12345, 54321, 'hello!'`` is an example of *tuple packing*:
380the values ``12345``, ``54321`` and ``'hello!'`` are packed together in a tuple.
381The reverse operation is also possible::
382
383 >>> x, y, z = t
384
Benjamin Petersond23f8222009-04-05 19:13:16 +0000385This is called, appropriately enough, *sequence unpacking* and works for any
Georg Brandl7ae90dd2009-06-08 18:59:09 +0000386sequence on the right-hand side. Sequence unpacking requires that there are as
387many variables on the left side of the equals sign as there are elements in the
Benjamin Petersond23f8222009-04-05 19:13:16 +0000388sequence. Note that multiple assignment is really just a combination of tuple
389packing and sequence unpacking.
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000390
391.. XXX Add a bit on the difference between tuples and lists.
392
393
Georg Brandl116aa622007-08-15 14:28:22 +0000394.. _tut-sets:
395
396Sets
397====
398
399Python also includes a data type for *sets*. A set is an unordered collection
400with no duplicate elements. Basic uses include membership testing and
401eliminating duplicate entries. Set objects also support mathematical operations
402like union, intersection, difference, and symmetric difference.
403
Georg Brandl448f20b2010-09-20 06:27:02 +0000404Curly braces or the :func:`set` function can be used to create sets. Note: To
Georg Brandl10e0e302009-06-08 20:25:55 +0000405create an empty set you have to use ``set()``, not ``{}``; the latter creates an
406empty dictionary, a data structure that we discuss in the next section.
Guido van Rossum0616b792007-08-31 03:25:11 +0000407
Georg Brandl116aa622007-08-15 14:28:22 +0000408Here is a brief demonstration::
409
Raymond Hettingerafdeca92010-08-08 01:30:45 +0000410 >>> basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
411 >>> print(basket) # show that duplicates have been removed
Georg Brandl1790ed22010-11-10 07:57:10 +0000412 {'orange', 'banana', 'pear', 'apple'}
Raymond Hettingerafdeca92010-08-08 01:30:45 +0000413 >>> 'orange' in basket # fast membership testing
Georg Brandl116aa622007-08-15 14:28:22 +0000414 True
Raymond Hettingerafdeca92010-08-08 01:30:45 +0000415 >>> 'crabgrass' in basket
Georg Brandl116aa622007-08-15 14:28:22 +0000416 False
417
418 >>> # Demonstrate set operations on unique letters from two words
419 ...
420 >>> a = set('abracadabra')
421 >>> b = set('alacazam')
422 >>> a # unique letters in a
Guido van Rossum0616b792007-08-31 03:25:11 +0000423 {'a', 'r', 'b', 'c', 'd'}
Georg Brandl116aa622007-08-15 14:28:22 +0000424 >>> a - b # letters in a but not in b
Guido van Rossum0616b792007-08-31 03:25:11 +0000425 {'r', 'd', 'b'}
Georg Brandl116aa622007-08-15 14:28:22 +0000426 >>> a | b # letters in either a or b
Guido van Rossum0616b792007-08-31 03:25:11 +0000427 {'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}
Georg Brandl116aa622007-08-15 14:28:22 +0000428 >>> a & b # letters in both a and b
Guido van Rossum0616b792007-08-31 03:25:11 +0000429 {'a', 'c'}
Georg Brandl116aa622007-08-15 14:28:22 +0000430 >>> a ^ b # letters in a or b but not both
Guido van Rossum0616b792007-08-31 03:25:11 +0000431 {'r', 'd', 'b', 'm', 'z', 'l'}
432
Georg Brandlfc11f272009-06-16 19:22:10 +0000433Like :ref:`for lists <tut-listcomps>`, there is a set comprehension syntax::
Georg Brandlf6945182008-02-01 11:56:49 +0000434
435 >>> a = {x for x in 'abracadabra' if x not in 'abc'}
436 >>> a
437 {'r', 'd'}
Guido van Rossum0616b792007-08-31 03:25:11 +0000438
Georg Brandl116aa622007-08-15 14:28:22 +0000439
440
441.. _tut-dictionaries:
442
443Dictionaries
444============
445
446Another useful data type built into Python is the *dictionary* (see
447:ref:`typesmapping`). Dictionaries are sometimes found in other languages as
448"associative memories" or "associative arrays". Unlike sequences, which are
449indexed by a range of numbers, dictionaries are indexed by *keys*, which can be
450any immutable type; strings and numbers can always be keys. Tuples can be used
451as keys if they contain only strings, numbers, or tuples; if a tuple contains
452any mutable object either directly or indirectly, it cannot be used as a key.
453You can't use lists as keys, since lists can be modified in place using index
454assignments, slice assignments, or methods like :meth:`append` and
455:meth:`extend`.
456
457It is best to think of a dictionary as an unordered set of *key: value* pairs,
458with the requirement that the keys are unique (within one dictionary). A pair of
459braces creates an empty dictionary: ``{}``. Placing a comma-separated list of
460key:value pairs within the braces adds initial key:value pairs to the
461dictionary; this is also the way dictionaries are written on output.
462
463The main operations on a dictionary are storing a value with some key and
464extracting the value given the key. It is also possible to delete a key:value
465pair with ``del``. If you store using a key that is already in use, the old
466value associated with that key is forgotten. It is an error to extract a value
467using a non-existent key.
468
Georg Brandlabffe712008-12-15 08:28:37 +0000469Performing ``list(d.keys())`` on a dictionary returns a list of all the keys
Georg Brandlfc11f272009-06-16 19:22:10 +0000470used in the dictionary, in arbitrary order (if you want it sorted, just use
471``sorted(d.keys())`` instead). [1]_ To check whether a single key is in the
472dictionary, use the :keyword:`in` keyword.
Georg Brandl116aa622007-08-15 14:28:22 +0000473
474Here is a small example using a dictionary::
475
476 >>> tel = {'jack': 4098, 'sape': 4139}
477 >>> tel['guido'] = 4127
478 >>> tel
479 {'sape': 4139, 'guido': 4127, 'jack': 4098}
480 >>> tel['jack']
481 4098
482 >>> del tel['sape']
483 >>> tel['irv'] = 4127
484 >>> tel
485 {'guido': 4127, 'irv': 4127, 'jack': 4098}
Neal Norwitze0906d12007-08-31 03:46:28 +0000486 >>> list(tel.keys())
Georg Brandlabffe712008-12-15 08:28:37 +0000487 ['irv', 'guido', 'jack']
488 >>> sorted(tel.keys())
Georg Brandl116aa622007-08-15 14:28:22 +0000489 ['guido', 'irv', 'jack']
Georg Brandl116aa622007-08-15 14:28:22 +0000490 >>> 'guido' in tel
491 True
Neal Norwitze0906d12007-08-31 03:46:28 +0000492 >>> 'jack' not in tel
493 False
Georg Brandl116aa622007-08-15 14:28:22 +0000494
Georg Brandlfc11f272009-06-16 19:22:10 +0000495The :func:`dict` constructor builds dictionaries directly from sequences of
Raymond Hettinger8699aea2009-06-16 20:49:30 +0000496key-value pairs::
Georg Brandl116aa622007-08-15 14:28:22 +0000497
498 >>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
499 {'sape': 4139, 'jack': 4098, 'guido': 4127}
Georg Brandl116aa622007-08-15 14:28:22 +0000500
Georg Brandlf6945182008-02-01 11:56:49 +0000501In addition, dict comprehensions can be used to create dictionaries from
502arbitrary key and value expressions::
503
504 >>> {x: x**2 for x in (2, 4, 6)}
505 {2: 4, 4: 16, 6: 36}
Georg Brandl116aa622007-08-15 14:28:22 +0000506
507When the keys are simple strings, it is sometimes easier to specify pairs using
508keyword arguments::
509
510 >>> dict(sape=4139, guido=4127, jack=4098)
511 {'sape': 4139, 'jack': 4098, 'guido': 4127}
512
513
514.. _tut-loopidioms:
515
516Looping Techniques
517==================
518
519When looping through dictionaries, the key and corresponding value can be
Neal Norwitze0906d12007-08-31 03:46:28 +0000520retrieved at the same time using the :meth:`items` method. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000521
522 >>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
Neal Norwitze0906d12007-08-31 03:46:28 +0000523 >>> for k, v in knights.items():
Guido van Rossum0616b792007-08-31 03:25:11 +0000524 ... print(k, v)
Georg Brandl116aa622007-08-15 14:28:22 +0000525 ...
526 gallahad the pure
527 robin the brave
528
529When looping through a sequence, the position index and corresponding value can
530be retrieved at the same time using the :func:`enumerate` function. ::
531
532 >>> for i, v in enumerate(['tic', 'tac', 'toe']):
Guido van Rossum0616b792007-08-31 03:25:11 +0000533 ... print(i, v)
Georg Brandl116aa622007-08-15 14:28:22 +0000534 ...
535 0 tic
536 1 tac
537 2 toe
538
539To loop over two or more sequences at the same time, the entries can be paired
540with the :func:`zip` function. ::
541
542 >>> questions = ['name', 'quest', 'favorite color']
543 >>> answers = ['lancelot', 'the holy grail', 'blue']
544 >>> for q, a in zip(questions, answers):
Benjamin Petersone6f00632008-05-26 01:03:56 +0000545 ... print('What is your {0}? It is {1}.'.format(q, a))
Georg Brandl06788c92009-01-03 21:31:47 +0000546 ...
Georg Brandl116aa622007-08-15 14:28:22 +0000547 What is your name? It is lancelot.
548 What is your quest? It is the holy grail.
549 What is your favorite color? It is blue.
550
551To loop over a sequence in reverse, first specify the sequence in a forward
552direction and then call the :func:`reversed` function. ::
553
Georg Brandle4ac7502007-09-03 07:10:24 +0000554 >>> for i in reversed(range(1, 10, 2)):
Guido van Rossum0616b792007-08-31 03:25:11 +0000555 ... print(i)
Georg Brandl116aa622007-08-15 14:28:22 +0000556 ...
557 9
558 7
559 5
560 3
561 1
562
563To loop over a sequence in sorted order, use the :func:`sorted` function which
564returns a new sorted list while leaving the source unaltered. ::
565
566 >>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
567 >>> for f in sorted(set(basket)):
Guido van Rossum0616b792007-08-31 03:25:11 +0000568 ... print(f)
Georg Brandl06788c92009-01-03 21:31:47 +0000569 ...
Georg Brandl116aa622007-08-15 14:28:22 +0000570 apple
571 banana
572 orange
573 pear
574
575
576.. _tut-conditions:
577
578More on Conditions
579==================
580
581The conditions used in ``while`` and ``if`` statements can contain any
582operators, not just comparisons.
583
584The comparison operators ``in`` and ``not in`` check whether a value occurs
585(does not occur) in a sequence. The operators ``is`` and ``is not`` compare
586whether two objects are really the same object; this only matters for mutable
587objects like lists. All comparison operators have the same priority, which is
588lower than that of all numerical operators.
589
590Comparisons can be chained. For example, ``a < b == c`` tests whether ``a`` is
591less than ``b`` and moreover ``b`` equals ``c``.
592
593Comparisons may be combined using the Boolean operators ``and`` and ``or``, and
594the outcome of a comparison (or of any other Boolean expression) may be negated
595with ``not``. These have lower priorities than comparison operators; between
596them, ``not`` has the highest priority and ``or`` the lowest, so that ``A and
597not B or C`` is equivalent to ``(A and (not B)) or C``. As always, parentheses
598can be used to express the desired composition.
599
600The Boolean operators ``and`` and ``or`` are so-called *short-circuit*
601operators: their arguments are evaluated from left to right, and evaluation
602stops as soon as the outcome is determined. For example, if ``A`` and ``C`` are
603true but ``B`` is false, ``A and B and C`` does not evaluate the expression
604``C``. When used as a general value and not as a Boolean, the return value of a
605short-circuit operator is the last evaluated argument.
606
607It is possible to assign the result of a comparison or other Boolean expression
608to a variable. For example, ::
609
610 >>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance'
611 >>> non_null = string1 or string2 or string3
612 >>> non_null
613 'Trondheim'
614
615Note that in Python, unlike C, assignment cannot occur inside expressions. C
616programmers may grumble about this, but it avoids a common class of problems
617encountered in C programs: typing ``=`` in an expression when ``==`` was
618intended.
619
620
621.. _tut-comparing:
622
623Comparing Sequences and Other Types
624===================================
625
626Sequence objects may be compared to other objects with the same sequence type.
627The comparison uses *lexicographical* ordering: first the first two items are
628compared, and if they differ this determines the outcome of the comparison; if
629they are equal, the next two items are compared, and so on, until either
630sequence is exhausted. If two items to be compared are themselves sequences of
631the same type, the lexicographical comparison is carried out recursively. If
632all items of two sequences compare equal, the sequences are considered equal.
633If one sequence is an initial sub-sequence of the other, the shorter sequence is
Georg Brandlfc11f272009-06-16 19:22:10 +0000634the smaller (lesser) one. Lexicographical ordering for strings uses the Unicode
635codepoint number to order individual characters. Some examples of comparisons
636between sequences of the same type::
Georg Brandl116aa622007-08-15 14:28:22 +0000637
638 (1, 2, 3) < (1, 2, 4)
639 [1, 2, 3] < [1, 2, 4]
640 'ABC' < 'C' < 'Pascal' < 'Python'
641 (1, 2, 3, 4) < (1, 2, 4)
642 (1, 2) < (1, 2, -1)
643 (1, 2, 3) == (1.0, 2.0, 3.0)
644 (1, 2, ('aa', 'ab')) < (1, 2, ('abc', 'a'), 4)
645
Georg Brandl9f2c39a2007-10-08 14:08:36 +0000646Note that comparing objects of different types with ``<`` or ``>`` is legal
647provided that the objects have appropriate comparison methods. For example,
648mixed numeric types are compared according to their numeric value, so 0 equals
6490.0, etc. Otherwise, rather than providing an arbitrary ordering, the
650interpreter will raise a :exc:`TypeError` exception.
Georg Brandlfc11f272009-06-16 19:22:10 +0000651
652
653.. rubric:: Footnotes
654
655.. [1] Calling ``d.keys()`` will return a :dfn:`dictionary view` object. It
656 supports operations like membership test and iteration, but its contents
657 are not independent of the original dictionary -- it is only a *view*.