blob: 0ee4dca04f12d073c2f7483ca21fccb35a8edcb4 [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
Chris Jerdonekfd448da2012-09-28 07:07:12 -0700184This is also equivalent to ``squares = list(map(lambda x: x**2, range(10)))``,
Ezio Melotti91621e22011-12-13 15:36:19 +0200185but 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
Sandro Tosi0a90a822012-08-12 10:24:50 +0200295 >>> list(zip(*matrix))
Ezio Melotti91621e22011-12-13 15:36:19 +0200296 [(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))
Ezio Melottif90ea1f2012-06-17 14:10:59 +0200352 >>> # Tuples are immutable:
353 ... t[0] = 88888
354 Traceback (most recent call last):
355 File "<stdin>", line 1, in <module>
356 TypeError: 'tuple' object does not support item assignment
357 >>> # but they can contain mutable objects:
358 ... v = ([1, 2, 3], [3, 2, 1])
359 >>> v
360 ([1, 2, 3], [3, 2, 1])
361
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000362
363As you see, on output tuples are always enclosed in parentheses, so that nested
364tuples are interpreted correctly; they may be input with or without surrounding
365parentheses, although often parentheses are necessary anyway (if the tuple is
Ezio Melottif90ea1f2012-06-17 14:10:59 +0200366part of a larger expression). It is not possible to assign to the individual
367items of a tuple, however it is possible to create tuples which contain mutable
368objects, such as lists.
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000369
Ezio Melottif90ea1f2012-06-17 14:10:59 +0200370Though tuples may seem similar to lists, they are often used in different
371situations and for different purposes.
372Tuples are :term:`immutable`, and usually contain an heterogeneous sequence of
373elements that are accessed via unpacking (see later in this section) or indexing
374(or even by attribute in the case of :func:`namedtuples <collections.namedtuple>`).
375Lists are :term:`mutable`, and their elements are usually homogeneous and are
376accessed by iterating over the list.
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000377
378A special problem is the construction of tuples containing 0 or 1 items: the
379syntax has some extra quirks to accommodate these. Empty tuples are constructed
380by an empty pair of parentheses; a tuple with one item is constructed by
381following a value with a comma (it is not sufficient to enclose a single value
382in parentheses). Ugly, but effective. For example::
383
384 >>> empty = ()
385 >>> singleton = 'hello', # <-- note trailing comma
386 >>> len(empty)
387 0
388 >>> len(singleton)
389 1
390 >>> singleton
391 ('hello',)
392
393The statement ``t = 12345, 54321, 'hello!'`` is an example of *tuple packing*:
394the values ``12345``, ``54321`` and ``'hello!'`` are packed together in a tuple.
395The reverse operation is also possible::
396
397 >>> x, y, z = t
398
Benjamin Petersond23f8222009-04-05 19:13:16 +0000399This is called, appropriately enough, *sequence unpacking* and works for any
Georg Brandl7ae90dd2009-06-08 18:59:09 +0000400sequence on the right-hand side. Sequence unpacking requires that there are as
401many variables on the left side of the equals sign as there are elements in the
Benjamin Petersond23f8222009-04-05 19:13:16 +0000402sequence. Note that multiple assignment is really just a combination of tuple
403packing and sequence unpacking.
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000404
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000405
Georg Brandl116aa622007-08-15 14:28:22 +0000406.. _tut-sets:
407
408Sets
409====
410
411Python also includes a data type for *sets*. A set is an unordered collection
412with no duplicate elements. Basic uses include membership testing and
413eliminating duplicate entries. Set objects also support mathematical operations
414like union, intersection, difference, and symmetric difference.
415
Ezio Melotti89b03b02012-11-17 12:06:01 +0200416Curly braces or the :func:`set` function can be used to create sets. Note: to
Georg Brandl10e0e302009-06-08 20:25:55 +0000417create an empty set you have to use ``set()``, not ``{}``; the latter creates an
418empty dictionary, a data structure that we discuss in the next section.
Guido van Rossum0616b792007-08-31 03:25:11 +0000419
Georg Brandl116aa622007-08-15 14:28:22 +0000420Here is a brief demonstration::
421
Raymond Hettingerafdeca92010-08-08 01:30:45 +0000422 >>> basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
423 >>> print(basket) # show that duplicates have been removed
Georg Brandl1790ed22010-11-10 07:57:10 +0000424 {'orange', 'banana', 'pear', 'apple'}
Raymond Hettingerafdeca92010-08-08 01:30:45 +0000425 >>> 'orange' in basket # fast membership testing
Georg Brandl116aa622007-08-15 14:28:22 +0000426 True
Raymond Hettingerafdeca92010-08-08 01:30:45 +0000427 >>> 'crabgrass' in basket
Georg Brandl116aa622007-08-15 14:28:22 +0000428 False
429
430 >>> # Demonstrate set operations on unique letters from two words
431 ...
432 >>> a = set('abracadabra')
433 >>> b = set('alacazam')
434 >>> a # unique letters in a
Guido van Rossum0616b792007-08-31 03:25:11 +0000435 {'a', 'r', 'b', 'c', 'd'}
Georg Brandl116aa622007-08-15 14:28:22 +0000436 >>> a - b # letters in a but not in b
Guido van Rossum0616b792007-08-31 03:25:11 +0000437 {'r', 'd', 'b'}
Georg Brandl116aa622007-08-15 14:28:22 +0000438 >>> a | b # letters in either a or b
Guido van Rossum0616b792007-08-31 03:25:11 +0000439 {'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}
Georg Brandl116aa622007-08-15 14:28:22 +0000440 >>> a & b # letters in both a and b
Guido van Rossum0616b792007-08-31 03:25:11 +0000441 {'a', 'c'}
Georg Brandl116aa622007-08-15 14:28:22 +0000442 >>> a ^ b # letters in a or b but not both
Guido van Rossum0616b792007-08-31 03:25:11 +0000443 {'r', 'd', 'b', 'm', 'z', 'l'}
444
Ezio Melotti89b03b02012-11-17 12:06:01 +0200445Similarly to :ref:`list comprehensions <tut-listcomps>`, set comprehensions
446are also supported::
Georg Brandlf6945182008-02-01 11:56:49 +0000447
448 >>> a = {x for x in 'abracadabra' if x not in 'abc'}
449 >>> a
450 {'r', 'd'}
Guido van Rossum0616b792007-08-31 03:25:11 +0000451
Georg Brandl116aa622007-08-15 14:28:22 +0000452
Georg Brandl116aa622007-08-15 14:28:22 +0000453.. _tut-dictionaries:
454
455Dictionaries
456============
457
458Another useful data type built into Python is the *dictionary* (see
459:ref:`typesmapping`). Dictionaries are sometimes found in other languages as
460"associative memories" or "associative arrays". Unlike sequences, which are
461indexed by a range of numbers, dictionaries are indexed by *keys*, which can be
462any immutable type; strings and numbers can always be keys. Tuples can be used
463as keys if they contain only strings, numbers, or tuples; if a tuple contains
464any mutable object either directly or indirectly, it cannot be used as a key.
465You can't use lists as keys, since lists can be modified in place using index
466assignments, slice assignments, or methods like :meth:`append` and
467:meth:`extend`.
468
469It is best to think of a dictionary as an unordered set of *key: value* pairs,
470with the requirement that the keys are unique (within one dictionary). A pair of
471braces creates an empty dictionary: ``{}``. Placing a comma-separated list of
472key:value pairs within the braces adds initial key:value pairs to the
473dictionary; this is also the way dictionaries are written on output.
474
475The main operations on a dictionary are storing a value with some key and
476extracting the value given the key. It is also possible to delete a key:value
477pair with ``del``. If you store using a key that is already in use, the old
478value associated with that key is forgotten. It is an error to extract a value
479using a non-existent key.
480
Georg Brandlabffe712008-12-15 08:28:37 +0000481Performing ``list(d.keys())`` on a dictionary returns a list of all the keys
Georg Brandlfc11f272009-06-16 19:22:10 +0000482used in the dictionary, in arbitrary order (if you want it sorted, just use
483``sorted(d.keys())`` instead). [1]_ To check whether a single key is in the
484dictionary, use the :keyword:`in` keyword.
Georg Brandl116aa622007-08-15 14:28:22 +0000485
486Here is a small example using a dictionary::
487
488 >>> tel = {'jack': 4098, 'sape': 4139}
489 >>> tel['guido'] = 4127
490 >>> tel
491 {'sape': 4139, 'guido': 4127, 'jack': 4098}
492 >>> tel['jack']
493 4098
494 >>> del tel['sape']
495 >>> tel['irv'] = 4127
496 >>> tel
497 {'guido': 4127, 'irv': 4127, 'jack': 4098}
Neal Norwitze0906d12007-08-31 03:46:28 +0000498 >>> list(tel.keys())
Georg Brandlabffe712008-12-15 08:28:37 +0000499 ['irv', 'guido', 'jack']
500 >>> sorted(tel.keys())
Georg Brandl116aa622007-08-15 14:28:22 +0000501 ['guido', 'irv', 'jack']
Georg Brandl116aa622007-08-15 14:28:22 +0000502 >>> 'guido' in tel
503 True
Neal Norwitze0906d12007-08-31 03:46:28 +0000504 >>> 'jack' not in tel
505 False
Georg Brandl116aa622007-08-15 14:28:22 +0000506
Georg Brandlfc11f272009-06-16 19:22:10 +0000507The :func:`dict` constructor builds dictionaries directly from sequences of
Raymond Hettinger8699aea2009-06-16 20:49:30 +0000508key-value pairs::
Georg Brandl116aa622007-08-15 14:28:22 +0000509
510 >>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
511 {'sape': 4139, 'jack': 4098, 'guido': 4127}
Georg Brandl116aa622007-08-15 14:28:22 +0000512
Georg Brandlf6945182008-02-01 11:56:49 +0000513In addition, dict comprehensions can be used to create dictionaries from
514arbitrary key and value expressions::
515
516 >>> {x: x**2 for x in (2, 4, 6)}
517 {2: 4, 4: 16, 6: 36}
Georg Brandl116aa622007-08-15 14:28:22 +0000518
519When the keys are simple strings, it is sometimes easier to specify pairs using
520keyword arguments::
521
522 >>> dict(sape=4139, guido=4127, jack=4098)
523 {'sape': 4139, 'jack': 4098, 'guido': 4127}
524
525
526.. _tut-loopidioms:
527
528Looping Techniques
529==================
530
531When looping through dictionaries, the key and corresponding value can be
Neal Norwitze0906d12007-08-31 03:46:28 +0000532retrieved at the same time using the :meth:`items` method. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000533
534 >>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
Neal Norwitze0906d12007-08-31 03:46:28 +0000535 >>> for k, v in knights.items():
Guido van Rossum0616b792007-08-31 03:25:11 +0000536 ... print(k, v)
Georg Brandl116aa622007-08-15 14:28:22 +0000537 ...
538 gallahad the pure
539 robin the brave
540
541When looping through a sequence, the position index and corresponding value can
542be retrieved at the same time using the :func:`enumerate` function. ::
543
544 >>> for i, v in enumerate(['tic', 'tac', 'toe']):
Guido van Rossum0616b792007-08-31 03:25:11 +0000545 ... print(i, v)
Georg Brandl116aa622007-08-15 14:28:22 +0000546 ...
547 0 tic
548 1 tac
549 2 toe
550
551To loop over two or more sequences at the same time, the entries can be paired
552with the :func:`zip` function. ::
553
554 >>> questions = ['name', 'quest', 'favorite color']
555 >>> answers = ['lancelot', 'the holy grail', 'blue']
556 >>> for q, a in zip(questions, answers):
Benjamin Petersone6f00632008-05-26 01:03:56 +0000557 ... print('What is your {0}? It is {1}.'.format(q, a))
Georg Brandl06788c92009-01-03 21:31:47 +0000558 ...
Georg Brandl116aa622007-08-15 14:28:22 +0000559 What is your name? It is lancelot.
560 What is your quest? It is the holy grail.
561 What is your favorite color? It is blue.
562
563To loop over a sequence in reverse, first specify the sequence in a forward
564direction and then call the :func:`reversed` function. ::
565
Georg Brandle4ac7502007-09-03 07:10:24 +0000566 >>> for i in reversed(range(1, 10, 2)):
Guido van Rossum0616b792007-08-31 03:25:11 +0000567 ... print(i)
Georg Brandl116aa622007-08-15 14:28:22 +0000568 ...
569 9
570 7
571 5
572 3
573 1
574
575To loop over a sequence in sorted order, use the :func:`sorted` function which
576returns a new sorted list while leaving the source unaltered. ::
577
578 >>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
579 >>> for f in sorted(set(basket)):
Guido van Rossum0616b792007-08-31 03:25:11 +0000580 ... print(f)
Georg Brandl06788c92009-01-03 21:31:47 +0000581 ...
Georg Brandl116aa622007-08-15 14:28:22 +0000582 apple
583 banana
584 orange
585 pear
586
Chris Jerdonek4fab8f02012-10-15 19:44:47 -0700587To change a sequence you are iterating over while inside the loop (for
588example to duplicate certain items), it is recommended that you first make
589a copy. Looping over a sequence does not implicitly make a copy. The slice
590notation makes this especially convenient::
591
592 >>> words = ['cat', 'window', 'defenestrate']
593 >>> for w in words[:]: # Loop over a slice copy of the entire list.
594 ... if len(w) > 6:
595 ... words.insert(0, w)
596 ...
597 >>> words
598 ['defenestrate', 'cat', 'window', 'defenestrate']
599
Georg Brandl116aa622007-08-15 14:28:22 +0000600
601.. _tut-conditions:
602
603More on Conditions
604==================
605
606The conditions used in ``while`` and ``if`` statements can contain any
607operators, not just comparisons.
608
609The comparison operators ``in`` and ``not in`` check whether a value occurs
610(does not occur) in a sequence. The operators ``is`` and ``is not`` compare
611whether two objects are really the same object; this only matters for mutable
612objects like lists. All comparison operators have the same priority, which is
613lower than that of all numerical operators.
614
615Comparisons can be chained. For example, ``a < b == c`` tests whether ``a`` is
616less than ``b`` and moreover ``b`` equals ``c``.
617
618Comparisons may be combined using the Boolean operators ``and`` and ``or``, and
619the outcome of a comparison (or of any other Boolean expression) may be negated
620with ``not``. These have lower priorities than comparison operators; between
621them, ``not`` has the highest priority and ``or`` the lowest, so that ``A and
622not B or C`` is equivalent to ``(A and (not B)) or C``. As always, parentheses
623can be used to express the desired composition.
624
625The Boolean operators ``and`` and ``or`` are so-called *short-circuit*
626operators: their arguments are evaluated from left to right, and evaluation
627stops as soon as the outcome is determined. For example, if ``A`` and ``C`` are
628true but ``B`` is false, ``A and B and C`` does not evaluate the expression
629``C``. When used as a general value and not as a Boolean, the return value of a
630short-circuit operator is the last evaluated argument.
631
632It is possible to assign the result of a comparison or other Boolean expression
633to a variable. For example, ::
634
635 >>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance'
636 >>> non_null = string1 or string2 or string3
637 >>> non_null
638 'Trondheim'
639
640Note that in Python, unlike C, assignment cannot occur inside expressions. C
641programmers may grumble about this, but it avoids a common class of problems
642encountered in C programs: typing ``=`` in an expression when ``==`` was
643intended.
644
645
646.. _tut-comparing:
647
648Comparing Sequences and Other Types
649===================================
650
651Sequence objects may be compared to other objects with the same sequence type.
652The comparison uses *lexicographical* ordering: first the first two items are
653compared, and if they differ this determines the outcome of the comparison; if
654they are equal, the next two items are compared, and so on, until either
655sequence is exhausted. If two items to be compared are themselves sequences of
656the same type, the lexicographical comparison is carried out recursively. If
657all items of two sequences compare equal, the sequences are considered equal.
658If one sequence is an initial sub-sequence of the other, the shorter sequence is
Georg Brandlfc11f272009-06-16 19:22:10 +0000659the smaller (lesser) one. Lexicographical ordering for strings uses the Unicode
660codepoint number to order individual characters. Some examples of comparisons
661between sequences of the same type::
Georg Brandl116aa622007-08-15 14:28:22 +0000662
663 (1, 2, 3) < (1, 2, 4)
664 [1, 2, 3] < [1, 2, 4]
665 'ABC' < 'C' < 'Pascal' < 'Python'
666 (1, 2, 3, 4) < (1, 2, 4)
667 (1, 2) < (1, 2, -1)
668 (1, 2, 3) == (1.0, 2.0, 3.0)
669 (1, 2, ('aa', 'ab')) < (1, 2, ('abc', 'a'), 4)
670
Georg Brandl9f2c39a2007-10-08 14:08:36 +0000671Note that comparing objects of different types with ``<`` or ``>`` is legal
672provided that the objects have appropriate comparison methods. For example,
673mixed numeric types are compared according to their numeric value, so 0 equals
6740.0, etc. Otherwise, rather than providing an arbitrary ordering, the
675interpreter will raise a :exc:`TypeError` exception.
Georg Brandlfc11f272009-06-16 19:22:10 +0000676
677
678.. rubric:: Footnotes
679
680.. [1] Calling ``d.keys()`` will return a :dfn:`dictionary view` object. It
681 supports operations like membership test and iteration, but its contents
682 are not independent of the original dictionary -- it is only a *view*.