blob: 36abc9cac25b92b033d6b7e1d6d2cd6eb961ed55 [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
Georg Brandl388349a2011-10-08 18:32:40 +020022 Add an item to the end of the list. Equivalent to ``a[len(a):] = [x]``.
Georg Brandl116aa622007-08-15 14:28:22 +000023
24
25.. method:: list.extend(L)
Christian Heimes4fbc72b2008-03-22 00:47:35 +000026 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +000027
Georg Brandl388349a2011-10-08 18:32:40 +020028 Extend the list by appending all the items in the given list. Equivalent to
Georg Brandl116aa622007-08-15 14:28:22 +000029 ``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
Georg Brandl388349a2011-10-08 18:32:40 +020043 Remove the first item from the list whose value is *x*. It is an error if
44 there is no such item.
Georg Brandl116aa622007-08-15 14:28:22 +000045
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
Georg Brandl388349a2011-10-08 18:32:40 +020073 Sort the items of the list in place.
Georg Brandl116aa622007-08-15 14:28:22 +000074
75
76.. method:: list.reverse()
Christian Heimes4fbc72b2008-03-22 00:47:35 +000077 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +000078
Georg Brandl388349a2011-10-08 18:32:40 +020079 Reverse the elements of the list in place.
80
Georg Brandl116aa622007-08-15 14:28:22 +000081
82An example that uses most of the list methods::
83
84 >>> a = [66.25, 333, 333, 1, 1234.5]
Guido van Rossum0616b792007-08-31 03:25:11 +000085 >>> print(a.count(333), a.count(66.25), a.count('x'))
Georg Brandl116aa622007-08-15 14:28:22 +000086 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
Georg Brandl388349a2011-10-08 18:32:40 +0200103You might have noticed that methods like ``insert``, ``remove`` or ``sort`` that
104modify the list have no return value printed -- they return ``None``. [1]_ This
105is a design principle for all mutable data structures in Python.
106
Georg Brandl116aa622007-08-15 14:28:22 +0000107
108.. _tut-lists-as-stacks:
109
110Using Lists as Stacks
111---------------------
112
113.. sectionauthor:: Ka-Ping Yee <ping@lfw.org>
114
115
116The list methods make it very easy to use a list as a stack, where the last
117element added is the first element retrieved ("last-in, first-out"). To add an
118item to the top of the stack, use :meth:`append`. To retrieve an item from the
119top of the stack, use :meth:`pop` without an explicit index. For example::
120
121 >>> stack = [3, 4, 5]
122 >>> stack.append(6)
123 >>> stack.append(7)
124 >>> stack
125 [3, 4, 5, 6, 7]
126 >>> stack.pop()
127 7
128 >>> stack
129 [3, 4, 5, 6]
130 >>> stack.pop()
131 6
132 >>> stack.pop()
133 5
134 >>> stack
135 [3, 4]
136
137
138.. _tut-lists-as-queues:
139
140Using Lists as Queues
141---------------------
142
143.. sectionauthor:: Ka-Ping Yee <ping@lfw.org>
144
Ezio Melotti8f8db142010-03-31 07:45:32 +0000145It is also possible to use a list as a queue, where the first element added is
146the first element retrieved ("first-in, first-out"); however, lists are not
147efficient for this purpose. While appends and pops from the end of list are
148fast, doing inserts or pops from the beginning of a list is slow (because all
149of the other elements have to be shifted by one).
Georg Brandl116aa622007-08-15 14:28:22 +0000150
Ezio Melotti8f8db142010-03-31 07:45:32 +0000151To implement a queue, use :class:`collections.deque` which was designed to
152have fast appends and pops from both ends. For example::
Georg Brandl116aa622007-08-15 14:28:22 +0000153
Ezio Melotti8f8db142010-03-31 07:45:32 +0000154 >>> from collections import deque
155 >>> queue = deque(["Eric", "John", "Michael"])
Georg Brandl116aa622007-08-15 14:28:22 +0000156 >>> queue.append("Terry") # Terry arrives
157 >>> queue.append("Graham") # Graham arrives
Ezio Melotti8f8db142010-03-31 07:45:32 +0000158 >>> queue.popleft() # The first to arrive now leaves
Georg Brandl116aa622007-08-15 14:28:22 +0000159 'Eric'
Ezio Melotti8f8db142010-03-31 07:45:32 +0000160 >>> queue.popleft() # The second to arrive now leaves
Georg Brandl116aa622007-08-15 14:28:22 +0000161 'John'
Ezio Melotti8f8db142010-03-31 07:45:32 +0000162 >>> queue # Remaining queue in order of arrival
163 deque(['Michael', 'Terry', 'Graham'])
Georg Brandl718ce2c2010-03-21 09:51:44 +0000164
Georg Brandl116aa622007-08-15 14:28:22 +0000165
Georg Brandlfc11f272009-06-16 19:22:10 +0000166.. _tut-listcomps:
167
Georg Brandl116aa622007-08-15 14:28:22 +0000168List Comprehensions
169-------------------
170
Ezio Melotti91621e22011-12-13 15:36:19 +0200171List comprehensions provide a concise way to create lists.
172Common applications are to make new lists where each element is the result of
173some operations applied to each member of another sequence or iterable, or to
174create a subsequence of those elements that satisfy a certain condition.
175
176For example, assume we want to create a list of squares, like::
177
178 >>> squares = []
179 >>> for x in range(10):
180 ... squares.append(x**2)
181 ...
182 >>> squares
183 [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
184
185We can obtain the same result with::
186
187 squares = [x**2 for x in range(10)]
188
Chris Jerdonekfd448da2012-09-28 07:07:12 -0700189This is also equivalent to ``squares = list(map(lambda x: x**2, range(10)))``,
Ezio Melotti91621e22011-12-13 15:36:19 +0200190but it's more concise and readable.
Guido van Rossum0616b792007-08-31 03:25:11 +0000191
Georg Brandl7ae90dd2009-06-08 18:59:09 +0000192A list comprehension consists of brackets containing an expression followed
193by a :keyword:`for` clause, then zero or more :keyword:`for` or :keyword:`if`
Ezio Melotti91621e22011-12-13 15:36:19 +0200194clauses. The result will be a new list resulting from evaluating the expression
195in the context of the :keyword:`for` and :keyword:`if` clauses which follow it.
196For example, this listcomp combines the elements of two lists if they are not
197equal::
Guido van Rossum0616b792007-08-31 03:25:11 +0000198
Ezio Melotti91621e22011-12-13 15:36:19 +0200199 >>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
200 [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
Guido van Rossum0616b792007-08-31 03:25:11 +0000201
Ezio Melotti91621e22011-12-13 15:36:19 +0200202and it's equivalent to::
Guido van Rossum0616b792007-08-31 03:25:11 +0000203
Ezio Melotti91621e22011-12-13 15:36:19 +0200204 >>> combs = []
205 >>> for x in [1,2,3]:
206 ... for y in [3,1,4]:
207 ... if x != y:
208 ... combs.append((x, y))
209 ...
210 >>> combs
211 [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
Guido van Rossum0616b792007-08-31 03:25:11 +0000212
Ezio Melotti91621e22011-12-13 15:36:19 +0200213Note how the order of the :keyword:`for` and :keyword:`if` statements is the
214same in both these snippets.
Guido van Rossum0616b792007-08-31 03:25:11 +0000215
Ezio Melotti91621e22011-12-13 15:36:19 +0200216If the expression is a tuple (e.g. the ``(x, y)`` in the previous example),
217it must be parenthesized. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000218
Ezio Melotti91621e22011-12-13 15:36:19 +0200219 >>> vec = [-4, -2, 0, 2, 4]
220 >>> # create a new list with the values doubled
221 >>> [x*2 for x in vec]
222 [-8, -4, 0, 4, 8]
223 >>> # filter the list to exclude negative numbers
224 >>> [x for x in vec if x >= 0]
225 [0, 2, 4]
226 >>> # apply a function to all the elements
227 >>> [abs(x) for x in vec]
228 [4, 2, 0, 2, 4]
229 >>> # call a method on each element
Georg Brandl116aa622007-08-15 14:28:22 +0000230 >>> freshfruit = [' banana', ' loganberry ', 'passion fruit ']
231 >>> [weapon.strip() for weapon in freshfruit]
232 ['banana', 'loganberry', 'passion fruit']
Ezio Melotti91621e22011-12-13 15:36:19 +0200233 >>> # create a list of 2-tuples like (number, square)
234 >>> [(x, x**2) for x in range(6)]
235 [(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]
236 >>> # the tuple must be parenthesized, otherwise an error is raised
237 >>> [x, x**2 for x in range(6)]
Georg Brandl116aa622007-08-15 14:28:22 +0000238 File "<stdin>", line 1, in ?
Ezio Melotti91621e22011-12-13 15:36:19 +0200239 [x, x**2 for x in range(6)]
Georg Brandl116aa622007-08-15 14:28:22 +0000240 ^
241 SyntaxError: invalid syntax
Ezio Melotti91621e22011-12-13 15:36:19 +0200242 >>> # flatten a list using a listcomp with two 'for'
243 >>> vec = [[1,2,3], [4,5,6], [7,8,9]]
244 >>> [num for elem in vec for num in elem]
245 [1, 2, 3, 4, 5, 6, 7, 8, 9]
Guido van Rossum0616b792007-08-31 03:25:11 +0000246
Ezio Melotti91621e22011-12-13 15:36:19 +0200247List comprehensions can contain complex expressions and nested functions::
Guido van Rossum0616b792007-08-31 03:25:11 +0000248
Ezio Melotti91621e22011-12-13 15:36:19 +0200249 >>> from math import pi
250 >>> [str(round(pi, i)) for i in range(1, 6)]
Georg Brandl116aa622007-08-15 14:28:22 +0000251 ['3.1', '3.14', '3.142', '3.1416', '3.14159']
252
Christian Heimes0449f632007-12-15 01:27:15 +0000253Nested List Comprehensions
254--------------------------
255
Ezio Melotti91621e22011-12-13 15:36:19 +0200256The initial expression in a list comprehension can be any arbitrary expression,
257including another list comprehension.
Christian Heimes0449f632007-12-15 01:27:15 +0000258
Ezio Melotti91621e22011-12-13 15:36:19 +0200259Consider the following example of a 3x4 matrix implemented as a list of
2603 lists of length 4::
Christian Heimes0449f632007-12-15 01:27:15 +0000261
Ezio Melotti91621e22011-12-13 15:36:19 +0200262 >>> matrix = [
263 ... [1, 2, 3, 4],
264 ... [5, 6, 7, 8],
265 ... [9, 10, 11, 12],
266 ... ]
Christian Heimes0449f632007-12-15 01:27:15 +0000267
Ezio Melotti91621e22011-12-13 15:36:19 +0200268The following list comprehension will transpose rows and columns::
Christian Heimes0449f632007-12-15 01:27:15 +0000269
Ezio Melotti91621e22011-12-13 15:36:19 +0200270 >>> [[row[i] for row in matrix] for i in range(4)]
271 [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
Christian Heimes0449f632007-12-15 01:27:15 +0000272
Ezio Melotti91621e22011-12-13 15:36:19 +0200273As we saw in the previous section, the nested listcomp is evaluated in
274the context of the :keyword:`for` that follows it, so this example is
275equivalent to::
Christian Heimes0449f632007-12-15 01:27:15 +0000276
Ezio Melotti91621e22011-12-13 15:36:19 +0200277 >>> transposed = []
278 >>> for i in range(4):
279 ... transposed.append([row[i] for row in matrix])
280 ...
281 >>> transposed
282 [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
Christian Heimes0449f632007-12-15 01:27:15 +0000283
Ezio Melotti91621e22011-12-13 15:36:19 +0200284which, in turn, is the same as::
Christian Heimes0449f632007-12-15 01:27:15 +0000285
Ezio Melotti91621e22011-12-13 15:36:19 +0200286 >>> transposed = []
287 >>> for i in range(4):
288 ... # the following 3 lines implement the nested listcomp
289 ... transposed_row = []
290 ... for row in matrix:
291 ... transposed_row.append(row[i])
292 ... transposed.append(transposed_row)
293 ...
294 >>> transposed
295 [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
Christian Heimes0449f632007-12-15 01:27:15 +0000296
Ezio Melotti91621e22011-12-13 15:36:19 +0200297In the real world, you should prefer built-in functions to complex flow statements.
Christian Heimes0449f632007-12-15 01:27:15 +0000298The :func:`zip` function would do a great job for this use case::
299
Sandro Tosi0a90a822012-08-12 10:24:50 +0200300 >>> list(zip(*matrix))
Ezio Melotti91621e22011-12-13 15:36:19 +0200301 [(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]
Christian Heimes0449f632007-12-15 01:27:15 +0000302
303See :ref:`tut-unpacking-arguments` for details on the asterisk in this line.
304
Georg Brandl116aa622007-08-15 14:28:22 +0000305.. _tut-del:
306
307The :keyword:`del` statement
308============================
309
310There is a way to remove an item from a list given its index instead of its
311value: the :keyword:`del` statement. This differs from the :meth:`pop` method
312which returns a value. The :keyword:`del` statement can also be used to remove
313slices from a list or clear the entire list (which we did earlier by assignment
314of an empty list to the slice). For example::
315
316 >>> a = [-1, 1, 66.25, 333, 333, 1234.5]
317 >>> del a[0]
318 >>> a
319 [1, 66.25, 333, 333, 1234.5]
320 >>> del a[2:4]
321 >>> a
322 [1, 66.25, 1234.5]
323 >>> del a[:]
324 >>> a
325 []
326
327:keyword:`del` can also be used to delete entire variables::
328
329 >>> del a
330
331Referencing the name ``a`` hereafter is an error (at least until another value
332is assigned to it). We'll find other uses for :keyword:`del` later.
333
334
Georg Brandl5d955ed2008-09-13 17:18:21 +0000335.. _tut-tuples:
Georg Brandl116aa622007-08-15 14:28:22 +0000336
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000337Tuples and Sequences
338====================
339
340We saw that lists and strings have many common properties, such as indexing and
341slicing operations. They are two examples of *sequence* data types (see
342:ref:`typesseq`). Since Python is an evolving language, other sequence data
343types may be added. There is also another standard sequence data type: the
344*tuple*.
345
346A tuple consists of a number of values separated by commas, for instance::
347
348 >>> t = 12345, 54321, 'hello!'
349 >>> t[0]
350 12345
351 >>> t
352 (12345, 54321, 'hello!')
353 >>> # Tuples may be nested:
354 ... u = t, (1, 2, 3, 4, 5)
355 >>> u
356 ((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))
Ezio Melottif90ea1f2012-06-17 14:10:59 +0200357 >>> # Tuples are immutable:
358 ... t[0] = 88888
359 Traceback (most recent call last):
360 File "<stdin>", line 1, in <module>
361 TypeError: 'tuple' object does not support item assignment
362 >>> # but they can contain mutable objects:
363 ... v = ([1, 2, 3], [3, 2, 1])
364 >>> v
365 ([1, 2, 3], [3, 2, 1])
366
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000367
368As you see, on output tuples are always enclosed in parentheses, so that nested
369tuples are interpreted correctly; they may be input with or without surrounding
370parentheses, although often parentheses are necessary anyway (if the tuple is
Ezio Melottif90ea1f2012-06-17 14:10:59 +0200371part of a larger expression). It is not possible to assign to the individual
372items of a tuple, however it is possible to create tuples which contain mutable
373objects, such as lists.
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000374
Ezio Melottif90ea1f2012-06-17 14:10:59 +0200375Though tuples may seem similar to lists, they are often used in different
376situations and for different purposes.
377Tuples are :term:`immutable`, and usually contain an heterogeneous sequence of
378elements that are accessed via unpacking (see later in this section) or indexing
379(or even by attribute in the case of :func:`namedtuples <collections.namedtuple>`).
380Lists are :term:`mutable`, and their elements are usually homogeneous and are
381accessed by iterating over the list.
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000382
383A special problem is the construction of tuples containing 0 or 1 items: the
384syntax has some extra quirks to accommodate these. Empty tuples are constructed
385by an empty pair of parentheses; a tuple with one item is constructed by
386following a value with a comma (it is not sufficient to enclose a single value
387in parentheses). Ugly, but effective. For example::
388
389 >>> empty = ()
390 >>> singleton = 'hello', # <-- note trailing comma
391 >>> len(empty)
392 0
393 >>> len(singleton)
394 1
395 >>> singleton
396 ('hello',)
397
398The statement ``t = 12345, 54321, 'hello!'`` is an example of *tuple packing*:
399the values ``12345``, ``54321`` and ``'hello!'`` are packed together in a tuple.
400The reverse operation is also possible::
401
402 >>> x, y, z = t
403
Benjamin Petersond23f8222009-04-05 19:13:16 +0000404This is called, appropriately enough, *sequence unpacking* and works for any
Georg Brandl7ae90dd2009-06-08 18:59:09 +0000405sequence on the right-hand side. Sequence unpacking requires that there are as
406many variables on the left side of the equals sign as there are elements in the
Benjamin Petersond23f8222009-04-05 19:13:16 +0000407sequence. Note that multiple assignment is really just a combination of tuple
408packing and sequence unpacking.
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000409
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000410
Georg Brandl116aa622007-08-15 14:28:22 +0000411.. _tut-sets:
412
413Sets
414====
415
416Python also includes a data type for *sets*. A set is an unordered collection
417with no duplicate elements. Basic uses include membership testing and
418eliminating duplicate entries. Set objects also support mathematical operations
419like union, intersection, difference, and symmetric difference.
420
Georg Brandl448f20b2010-09-20 06:27:02 +0000421Curly braces or the :func:`set` function can be used to create sets. Note: To
Georg Brandl10e0e302009-06-08 20:25:55 +0000422create an empty set you have to use ``set()``, not ``{}``; the latter creates an
423empty dictionary, a data structure that we discuss in the next section.
Guido van Rossum0616b792007-08-31 03:25:11 +0000424
Georg Brandl116aa622007-08-15 14:28:22 +0000425Here is a brief demonstration::
426
Raymond Hettingerafdeca92010-08-08 01:30:45 +0000427 >>> basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
428 >>> print(basket) # show that duplicates have been removed
Georg Brandl1790ed22010-11-10 07:57:10 +0000429 {'orange', 'banana', 'pear', 'apple'}
Raymond Hettingerafdeca92010-08-08 01:30:45 +0000430 >>> 'orange' in basket # fast membership testing
Georg Brandl116aa622007-08-15 14:28:22 +0000431 True
Raymond Hettingerafdeca92010-08-08 01:30:45 +0000432 >>> 'crabgrass' in basket
Georg Brandl116aa622007-08-15 14:28:22 +0000433 False
434
435 >>> # Demonstrate set operations on unique letters from two words
436 ...
437 >>> a = set('abracadabra')
438 >>> b = set('alacazam')
439 >>> a # unique letters in a
Guido van Rossum0616b792007-08-31 03:25:11 +0000440 {'a', 'r', 'b', 'c', 'd'}
Georg Brandl116aa622007-08-15 14:28:22 +0000441 >>> a - b # letters in a but not in b
Guido van Rossum0616b792007-08-31 03:25:11 +0000442 {'r', 'd', 'b'}
Georg Brandl116aa622007-08-15 14:28:22 +0000443 >>> a | b # letters in either a or b
Guido van Rossum0616b792007-08-31 03:25:11 +0000444 {'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}
Georg Brandl116aa622007-08-15 14:28:22 +0000445 >>> a & b # letters in both a and b
Guido van Rossum0616b792007-08-31 03:25:11 +0000446 {'a', 'c'}
Georg Brandl116aa622007-08-15 14:28:22 +0000447 >>> a ^ b # letters in a or b but not both
Guido van Rossum0616b792007-08-31 03:25:11 +0000448 {'r', 'd', 'b', 'm', 'z', 'l'}
449
Georg Brandlfc11f272009-06-16 19:22:10 +0000450Like :ref:`for lists <tut-listcomps>`, there is a set comprehension syntax::
Georg Brandlf6945182008-02-01 11:56:49 +0000451
452 >>> a = {x for x in 'abracadabra' if x not in 'abc'}
453 >>> a
454 {'r', 'd'}
Guido van Rossum0616b792007-08-31 03:25:11 +0000455
Georg Brandl116aa622007-08-15 14:28:22 +0000456
457
458.. _tut-dictionaries:
459
460Dictionaries
461============
462
463Another useful data type built into Python is the *dictionary* (see
464:ref:`typesmapping`). Dictionaries are sometimes found in other languages as
465"associative memories" or "associative arrays". Unlike sequences, which are
466indexed by a range of numbers, dictionaries are indexed by *keys*, which can be
467any immutable type; strings and numbers can always be keys. Tuples can be used
468as keys if they contain only strings, numbers, or tuples; if a tuple contains
469any mutable object either directly or indirectly, it cannot be used as a key.
470You can't use lists as keys, since lists can be modified in place using index
471assignments, slice assignments, or methods like :meth:`append` and
472:meth:`extend`.
473
474It is best to think of a dictionary as an unordered set of *key: value* pairs,
475with the requirement that the keys are unique (within one dictionary). A pair of
476braces creates an empty dictionary: ``{}``. Placing a comma-separated list of
477key:value pairs within the braces adds initial key:value pairs to the
478dictionary; this is also the way dictionaries are written on output.
479
480The main operations on a dictionary are storing a value with some key and
481extracting the value given the key. It is also possible to delete a key:value
482pair with ``del``. If you store using a key that is already in use, the old
483value associated with that key is forgotten. It is an error to extract a value
484using a non-existent key.
485
Georg Brandlabffe712008-12-15 08:28:37 +0000486Performing ``list(d.keys())`` on a dictionary returns a list of all the keys
Georg Brandlfc11f272009-06-16 19:22:10 +0000487used in the dictionary, in arbitrary order (if you want it sorted, just use
Georg Brandl388349a2011-10-08 18:32:40 +0200488``sorted(d.keys())`` instead). [2]_ To check whether a single key is in the
Georg Brandlfc11f272009-06-16 19:22:10 +0000489dictionary, use the :keyword:`in` keyword.
Georg Brandl116aa622007-08-15 14:28:22 +0000490
491Here is a small example using a dictionary::
492
493 >>> tel = {'jack': 4098, 'sape': 4139}
494 >>> tel['guido'] = 4127
495 >>> tel
496 {'sape': 4139, 'guido': 4127, 'jack': 4098}
497 >>> tel['jack']
498 4098
499 >>> del tel['sape']
500 >>> tel['irv'] = 4127
501 >>> tel
502 {'guido': 4127, 'irv': 4127, 'jack': 4098}
Neal Norwitze0906d12007-08-31 03:46:28 +0000503 >>> list(tel.keys())
Georg Brandlabffe712008-12-15 08:28:37 +0000504 ['irv', 'guido', 'jack']
505 >>> sorted(tel.keys())
Georg Brandl116aa622007-08-15 14:28:22 +0000506 ['guido', 'irv', 'jack']
Georg Brandl116aa622007-08-15 14:28:22 +0000507 >>> 'guido' in tel
508 True
Neal Norwitze0906d12007-08-31 03:46:28 +0000509 >>> 'jack' not in tel
510 False
Georg Brandl116aa622007-08-15 14:28:22 +0000511
Georg Brandlfc11f272009-06-16 19:22:10 +0000512The :func:`dict` constructor builds dictionaries directly from sequences of
Raymond Hettinger8699aea2009-06-16 20:49:30 +0000513key-value pairs::
Georg Brandl116aa622007-08-15 14:28:22 +0000514
515 >>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
516 {'sape': 4139, 'jack': 4098, 'guido': 4127}
Georg Brandl116aa622007-08-15 14:28:22 +0000517
Georg Brandlf6945182008-02-01 11:56:49 +0000518In addition, dict comprehensions can be used to create dictionaries from
519arbitrary key and value expressions::
520
521 >>> {x: x**2 for x in (2, 4, 6)}
522 {2: 4, 4: 16, 6: 36}
Georg Brandl116aa622007-08-15 14:28:22 +0000523
524When the keys are simple strings, it is sometimes easier to specify pairs using
525keyword arguments::
526
527 >>> dict(sape=4139, guido=4127, jack=4098)
528 {'sape': 4139, 'jack': 4098, 'guido': 4127}
529
530
531.. _tut-loopidioms:
532
533Looping Techniques
534==================
535
536When looping through dictionaries, the key and corresponding value can be
Neal Norwitze0906d12007-08-31 03:46:28 +0000537retrieved at the same time using the :meth:`items` method. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000538
539 >>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
Neal Norwitze0906d12007-08-31 03:46:28 +0000540 >>> for k, v in knights.items():
Guido van Rossum0616b792007-08-31 03:25:11 +0000541 ... print(k, v)
Georg Brandl116aa622007-08-15 14:28:22 +0000542 ...
543 gallahad the pure
544 robin the brave
545
546When looping through a sequence, the position index and corresponding value can
547be retrieved at the same time using the :func:`enumerate` function. ::
548
549 >>> for i, v in enumerate(['tic', 'tac', 'toe']):
Guido van Rossum0616b792007-08-31 03:25:11 +0000550 ... print(i, v)
Georg Brandl116aa622007-08-15 14:28:22 +0000551 ...
552 0 tic
553 1 tac
554 2 toe
555
556To loop over two or more sequences at the same time, the entries can be paired
557with the :func:`zip` function. ::
558
559 >>> questions = ['name', 'quest', 'favorite color']
560 >>> answers = ['lancelot', 'the holy grail', 'blue']
561 >>> for q, a in zip(questions, answers):
Benjamin Petersone6f00632008-05-26 01:03:56 +0000562 ... print('What is your {0}? It is {1}.'.format(q, a))
Georg Brandl06788c92009-01-03 21:31:47 +0000563 ...
Georg Brandl116aa622007-08-15 14:28:22 +0000564 What is your name? It is lancelot.
565 What is your quest? It is the holy grail.
566 What is your favorite color? It is blue.
567
568To loop over a sequence in reverse, first specify the sequence in a forward
569direction and then call the :func:`reversed` function. ::
570
Georg Brandle4ac7502007-09-03 07:10:24 +0000571 >>> for i in reversed(range(1, 10, 2)):
Guido van Rossum0616b792007-08-31 03:25:11 +0000572 ... print(i)
Georg Brandl116aa622007-08-15 14:28:22 +0000573 ...
574 9
575 7
576 5
577 3
578 1
579
580To loop over a sequence in sorted order, use the :func:`sorted` function which
581returns a new sorted list while leaving the source unaltered. ::
582
583 >>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
584 >>> for f in sorted(set(basket)):
Guido van Rossum0616b792007-08-31 03:25:11 +0000585 ... print(f)
Georg Brandl06788c92009-01-03 21:31:47 +0000586 ...
Georg Brandl116aa622007-08-15 14:28:22 +0000587 apple
588 banana
589 orange
590 pear
591
Chris Jerdonek4fab8f02012-10-15 19:44:47 -0700592To change a sequence you are iterating over while inside the loop (for
593example to duplicate certain items), it is recommended that you first make
594a copy. Looping over a sequence does not implicitly make a copy. The slice
595notation makes this especially convenient::
596
597 >>> words = ['cat', 'window', 'defenestrate']
598 >>> for w in words[:]: # Loop over a slice copy of the entire list.
599 ... if len(w) > 6:
600 ... words.insert(0, w)
601 ...
602 >>> words
603 ['defenestrate', 'cat', 'window', 'defenestrate']
604
Georg Brandl116aa622007-08-15 14:28:22 +0000605
606.. _tut-conditions:
607
608More on Conditions
609==================
610
611The conditions used in ``while`` and ``if`` statements can contain any
612operators, not just comparisons.
613
614The comparison operators ``in`` and ``not in`` check whether a value occurs
615(does not occur) in a sequence. The operators ``is`` and ``is not`` compare
616whether two objects are really the same object; this only matters for mutable
617objects like lists. All comparison operators have the same priority, which is
618lower than that of all numerical operators.
619
620Comparisons can be chained. For example, ``a < b == c`` tests whether ``a`` is
621less than ``b`` and moreover ``b`` equals ``c``.
622
623Comparisons may be combined using the Boolean operators ``and`` and ``or``, and
624the outcome of a comparison (or of any other Boolean expression) may be negated
625with ``not``. These have lower priorities than comparison operators; between
626them, ``not`` has the highest priority and ``or`` the lowest, so that ``A and
627not B or C`` is equivalent to ``(A and (not B)) or C``. As always, parentheses
628can be used to express the desired composition.
629
630The Boolean operators ``and`` and ``or`` are so-called *short-circuit*
631operators: their arguments are evaluated from left to right, and evaluation
632stops as soon as the outcome is determined. For example, if ``A`` and ``C`` are
633true but ``B`` is false, ``A and B and C`` does not evaluate the expression
634``C``. When used as a general value and not as a Boolean, the return value of a
635short-circuit operator is the last evaluated argument.
636
637It is possible to assign the result of a comparison or other Boolean expression
638to a variable. For example, ::
639
640 >>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance'
641 >>> non_null = string1 or string2 or string3
642 >>> non_null
643 'Trondheim'
644
645Note that in Python, unlike C, assignment cannot occur inside expressions. C
646programmers may grumble about this, but it avoids a common class of problems
647encountered in C programs: typing ``=`` in an expression when ``==`` was
648intended.
649
650
651.. _tut-comparing:
652
653Comparing Sequences and Other Types
654===================================
655
656Sequence objects may be compared to other objects with the same sequence type.
657The comparison uses *lexicographical* ordering: first the first two items are
658compared, and if they differ this determines the outcome of the comparison; if
659they are equal, the next two items are compared, and so on, until either
660sequence is exhausted. If two items to be compared are themselves sequences of
661the same type, the lexicographical comparison is carried out recursively. If
662all items of two sequences compare equal, the sequences are considered equal.
663If one sequence is an initial sub-sequence of the other, the shorter sequence is
Georg Brandlfc11f272009-06-16 19:22:10 +0000664the smaller (lesser) one. Lexicographical ordering for strings uses the Unicode
665codepoint number to order individual characters. Some examples of comparisons
666between sequences of the same type::
Georg Brandl116aa622007-08-15 14:28:22 +0000667
668 (1, 2, 3) < (1, 2, 4)
669 [1, 2, 3] < [1, 2, 4]
670 'ABC' < 'C' < 'Pascal' < 'Python'
671 (1, 2, 3, 4) < (1, 2, 4)
672 (1, 2) < (1, 2, -1)
673 (1, 2, 3) == (1.0, 2.0, 3.0)
674 (1, 2, ('aa', 'ab')) < (1, 2, ('abc', 'a'), 4)
675
Georg Brandl9f2c39a2007-10-08 14:08:36 +0000676Note that comparing objects of different types with ``<`` or ``>`` is legal
677provided that the objects have appropriate comparison methods. For example,
678mixed numeric types are compared according to their numeric value, so 0 equals
6790.0, etc. Otherwise, rather than providing an arbitrary ordering, the
680interpreter will raise a :exc:`TypeError` exception.
Georg Brandlfc11f272009-06-16 19:22:10 +0000681
682
683.. rubric:: Footnotes
684
Georg Brandl388349a2011-10-08 18:32:40 +0200685.. [1] Other languages may return the mutated object, which allows method
686 chaining, such as ``d->insert("a")->remove("b")->sort();``.
687
688.. [2] Calling ``d.keys()`` will return a :dfn:`dictionary view` object. It
Georg Brandlfc11f272009-06-16 19:22:10 +0000689 supports operations like membership test and iteration, but its contents
690 are not independent of the original dictionary -- it is only a *view*.