blob: 24d2d2ec3aa3962b9fb1846655da4f7b9f47b75f [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
Georg Brandla12b6822013-10-06 13:01:19 +020057.. method:: list.clear()
58 :noindex:
59
60 Remove all items from the list. Equivalent to ``del a[:]``.
61
62
Georg Brandl116aa622007-08-15 14:28:22 +000063.. method:: list.index(x)
Christian Heimes4fbc72b2008-03-22 00:47:35 +000064 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +000065
66 Return the index in the list of the first item whose value is *x*. It is an
67 error if there is no such item.
68
69
70.. method:: list.count(x)
Christian Heimes4fbc72b2008-03-22 00:47:35 +000071 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +000072
73 Return the number of times *x* appears in the list.
74
75
76.. method:: list.sort()
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 Sort the items of the list in place.
Georg Brandl116aa622007-08-15 14:28:22 +000080
81
82.. method:: list.reverse()
Christian Heimes4fbc72b2008-03-22 00:47:35 +000083 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +000084
Georg Brandl388349a2011-10-08 18:32:40 +020085 Reverse the elements of the list in place.
86
Georg Brandl116aa622007-08-15 14:28:22 +000087
Georg Brandla12b6822013-10-06 13:01:19 +020088.. method:: list.copy()
89 :noindex:
90
91 Return a shallow copy of the list. Equivalent to ``a[:]``.
92
93
Georg Brandl116aa622007-08-15 14:28:22 +000094An example that uses most of the list methods::
95
96 >>> a = [66.25, 333, 333, 1, 1234.5]
Guido van Rossum0616b792007-08-31 03:25:11 +000097 >>> print(a.count(333), a.count(66.25), a.count('x'))
Georg Brandl116aa622007-08-15 14:28:22 +000098 2 1 0
99 >>> a.insert(2, -1)
100 >>> a.append(333)
101 >>> a
102 [66.25, 333, -1, 333, 1, 1234.5, 333]
103 >>> a.index(333)
104 1
105 >>> a.remove(333)
106 >>> a
107 [66.25, -1, 333, 1, 1234.5, 333]
108 >>> a.reverse()
109 >>> a
110 [333, 1234.5, 1, 333, -1, 66.25]
111 >>> a.sort()
112 >>> a
113 [-1, 1, 66.25, 333, 333, 1234.5]
114
Georg Brandl388349a2011-10-08 18:32:40 +0200115You might have noticed that methods like ``insert``, ``remove`` or ``sort`` that
116modify the list have no return value printed -- they return ``None``. [1]_ This
117is a design principle for all mutable data structures in Python.
118
Georg Brandl116aa622007-08-15 14:28:22 +0000119
120.. _tut-lists-as-stacks:
121
122Using Lists as Stacks
123---------------------
124
125.. sectionauthor:: Ka-Ping Yee <ping@lfw.org>
126
127
128The list methods make it very easy to use a list as a stack, where the last
129element added is the first element retrieved ("last-in, first-out"). To add an
130item to the top of the stack, use :meth:`append`. To retrieve an item from the
131top of the stack, use :meth:`pop` without an explicit index. For example::
132
133 >>> stack = [3, 4, 5]
134 >>> stack.append(6)
135 >>> stack.append(7)
136 >>> stack
137 [3, 4, 5, 6, 7]
138 >>> stack.pop()
139 7
140 >>> stack
141 [3, 4, 5, 6]
142 >>> stack.pop()
143 6
144 >>> stack.pop()
145 5
146 >>> stack
147 [3, 4]
148
149
150.. _tut-lists-as-queues:
151
152Using Lists as Queues
153---------------------
154
155.. sectionauthor:: Ka-Ping Yee <ping@lfw.org>
156
Ezio Melotti8f8db142010-03-31 07:45:32 +0000157It is also possible to use a list as a queue, where the first element added is
158the first element retrieved ("first-in, first-out"); however, lists are not
159efficient for this purpose. While appends and pops from the end of list are
160fast, doing inserts or pops from the beginning of a list is slow (because all
161of the other elements have to be shifted by one).
Georg Brandl116aa622007-08-15 14:28:22 +0000162
Ezio Melotti8f8db142010-03-31 07:45:32 +0000163To implement a queue, use :class:`collections.deque` which was designed to
164have fast appends and pops from both ends. For example::
Georg Brandl116aa622007-08-15 14:28:22 +0000165
Ezio Melotti8f8db142010-03-31 07:45:32 +0000166 >>> from collections import deque
167 >>> queue = deque(["Eric", "John", "Michael"])
Georg Brandl116aa622007-08-15 14:28:22 +0000168 >>> queue.append("Terry") # Terry arrives
169 >>> queue.append("Graham") # Graham arrives
Ezio Melotti8f8db142010-03-31 07:45:32 +0000170 >>> queue.popleft() # The first to arrive now leaves
Georg Brandl116aa622007-08-15 14:28:22 +0000171 'Eric'
Ezio Melotti8f8db142010-03-31 07:45:32 +0000172 >>> queue.popleft() # The second to arrive now leaves
Georg Brandl116aa622007-08-15 14:28:22 +0000173 'John'
Ezio Melotti8f8db142010-03-31 07:45:32 +0000174 >>> queue # Remaining queue in order of arrival
175 deque(['Michael', 'Terry', 'Graham'])
Georg Brandl718ce2c2010-03-21 09:51:44 +0000176
Georg Brandl116aa622007-08-15 14:28:22 +0000177
Georg Brandlfc11f272009-06-16 19:22:10 +0000178.. _tut-listcomps:
179
Georg Brandl116aa622007-08-15 14:28:22 +0000180List Comprehensions
181-------------------
182
Ezio Melotti91621e22011-12-13 15:36:19 +0200183List comprehensions provide a concise way to create lists.
184Common applications are to make new lists where each element is the result of
185some operations applied to each member of another sequence or iterable, or to
186create a subsequence of those elements that satisfy a certain condition.
187
188For example, assume we want to create a list of squares, like::
189
190 >>> squares = []
191 >>> for x in range(10):
192 ... squares.append(x**2)
193 ...
194 >>> squares
195 [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
196
197We can obtain the same result with::
198
199 squares = [x**2 for x in range(10)]
200
Chris Jerdonekfd448da2012-09-28 07:07:12 -0700201This is also equivalent to ``squares = list(map(lambda x: x**2, range(10)))``,
Ezio Melotti91621e22011-12-13 15:36:19 +0200202but it's more concise and readable.
Guido van Rossum0616b792007-08-31 03:25:11 +0000203
Georg Brandl7ae90dd2009-06-08 18:59:09 +0000204A list comprehension consists of brackets containing an expression followed
205by a :keyword:`for` clause, then zero or more :keyword:`for` or :keyword:`if`
Ezio Melotti91621e22011-12-13 15:36:19 +0200206clauses. The result will be a new list resulting from evaluating the expression
207in the context of the :keyword:`for` and :keyword:`if` clauses which follow it.
208For example, this listcomp combines the elements of two lists if they are not
209equal::
Guido van Rossum0616b792007-08-31 03:25:11 +0000210
Ezio Melotti91621e22011-12-13 15:36:19 +0200211 >>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
212 [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
Guido van Rossum0616b792007-08-31 03:25:11 +0000213
Ezio Melotti91621e22011-12-13 15:36:19 +0200214and it's equivalent to::
Guido van Rossum0616b792007-08-31 03:25:11 +0000215
Ezio Melotti91621e22011-12-13 15:36:19 +0200216 >>> combs = []
217 >>> for x in [1,2,3]:
218 ... for y in [3,1,4]:
219 ... if x != y:
220 ... combs.append((x, y))
221 ...
222 >>> combs
223 [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
Guido van Rossum0616b792007-08-31 03:25:11 +0000224
Ezio Melotti91621e22011-12-13 15:36:19 +0200225Note how the order of the :keyword:`for` and :keyword:`if` statements is the
226same in both these snippets.
Guido van Rossum0616b792007-08-31 03:25:11 +0000227
Ezio Melotti91621e22011-12-13 15:36:19 +0200228If the expression is a tuple (e.g. the ``(x, y)`` in the previous example),
229it must be parenthesized. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000230
Ezio Melotti91621e22011-12-13 15:36:19 +0200231 >>> vec = [-4, -2, 0, 2, 4]
232 >>> # create a new list with the values doubled
233 >>> [x*2 for x in vec]
234 [-8, -4, 0, 4, 8]
235 >>> # filter the list to exclude negative numbers
236 >>> [x for x in vec if x >= 0]
237 [0, 2, 4]
238 >>> # apply a function to all the elements
239 >>> [abs(x) for x in vec]
240 [4, 2, 0, 2, 4]
241 >>> # call a method on each element
Georg Brandl116aa622007-08-15 14:28:22 +0000242 >>> freshfruit = [' banana', ' loganberry ', 'passion fruit ']
243 >>> [weapon.strip() for weapon in freshfruit]
244 ['banana', 'loganberry', 'passion fruit']
Ezio Melotti91621e22011-12-13 15:36:19 +0200245 >>> # create a list of 2-tuples like (number, square)
246 >>> [(x, x**2) for x in range(6)]
247 [(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]
248 >>> # the tuple must be parenthesized, otherwise an error is raised
249 >>> [x, x**2 for x in range(6)]
Georg Brandl116aa622007-08-15 14:28:22 +0000250 File "<stdin>", line 1, in ?
Ezio Melotti91621e22011-12-13 15:36:19 +0200251 [x, x**2 for x in range(6)]
Georg Brandl116aa622007-08-15 14:28:22 +0000252 ^
253 SyntaxError: invalid syntax
Ezio Melotti91621e22011-12-13 15:36:19 +0200254 >>> # flatten a list using a listcomp with two 'for'
255 >>> vec = [[1,2,3], [4,5,6], [7,8,9]]
256 >>> [num for elem in vec for num in elem]
257 [1, 2, 3, 4, 5, 6, 7, 8, 9]
Guido van Rossum0616b792007-08-31 03:25:11 +0000258
Ezio Melotti91621e22011-12-13 15:36:19 +0200259List comprehensions can contain complex expressions and nested functions::
Guido van Rossum0616b792007-08-31 03:25:11 +0000260
Ezio Melotti91621e22011-12-13 15:36:19 +0200261 >>> from math import pi
262 >>> [str(round(pi, i)) for i in range(1, 6)]
Georg Brandl116aa622007-08-15 14:28:22 +0000263 ['3.1', '3.14', '3.142', '3.1416', '3.14159']
264
Christian Heimes0449f632007-12-15 01:27:15 +0000265Nested List Comprehensions
266--------------------------
267
Ezio Melotti91621e22011-12-13 15:36:19 +0200268The initial expression in a list comprehension can be any arbitrary expression,
269including another list comprehension.
Christian Heimes0449f632007-12-15 01:27:15 +0000270
Ezio Melotti91621e22011-12-13 15:36:19 +0200271Consider the following example of a 3x4 matrix implemented as a list of
2723 lists of length 4::
Christian Heimes0449f632007-12-15 01:27:15 +0000273
Ezio Melotti91621e22011-12-13 15:36:19 +0200274 >>> matrix = [
275 ... [1, 2, 3, 4],
276 ... [5, 6, 7, 8],
277 ... [9, 10, 11, 12],
278 ... ]
Christian Heimes0449f632007-12-15 01:27:15 +0000279
Ezio Melotti91621e22011-12-13 15:36:19 +0200280The following list comprehension will transpose rows and columns::
Christian Heimes0449f632007-12-15 01:27:15 +0000281
Ezio Melotti91621e22011-12-13 15:36:19 +0200282 >>> [[row[i] for row in matrix] for i in range(4)]
283 [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
Christian Heimes0449f632007-12-15 01:27:15 +0000284
Ezio Melotti91621e22011-12-13 15:36:19 +0200285As we saw in the previous section, the nested listcomp is evaluated in
286the context of the :keyword:`for` that follows it, so this example is
287equivalent to::
Christian Heimes0449f632007-12-15 01:27:15 +0000288
Ezio Melotti91621e22011-12-13 15:36:19 +0200289 >>> transposed = []
290 >>> for i in range(4):
291 ... transposed.append([row[i] for row in matrix])
292 ...
293 >>> transposed
294 [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
Christian Heimes0449f632007-12-15 01:27:15 +0000295
Ezio Melotti91621e22011-12-13 15:36:19 +0200296which, in turn, is the same as::
Christian Heimes0449f632007-12-15 01:27:15 +0000297
Ezio Melotti91621e22011-12-13 15:36:19 +0200298 >>> transposed = []
299 >>> for i in range(4):
300 ... # the following 3 lines implement the nested listcomp
301 ... transposed_row = []
302 ... for row in matrix:
303 ... transposed_row.append(row[i])
304 ... transposed.append(transposed_row)
305 ...
306 >>> transposed
307 [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
Christian Heimes0449f632007-12-15 01:27:15 +0000308
Ezio Melotti91621e22011-12-13 15:36:19 +0200309In the real world, you should prefer built-in functions to complex flow statements.
Christian Heimes0449f632007-12-15 01:27:15 +0000310The :func:`zip` function would do a great job for this use case::
311
Sandro Tosi0a90a822012-08-12 10:24:50 +0200312 >>> list(zip(*matrix))
Ezio Melotti91621e22011-12-13 15:36:19 +0200313 [(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]
Christian Heimes0449f632007-12-15 01:27:15 +0000314
315See :ref:`tut-unpacking-arguments` for details on the asterisk in this line.
316
Georg Brandl116aa622007-08-15 14:28:22 +0000317.. _tut-del:
318
319The :keyword:`del` statement
320============================
321
322There is a way to remove an item from a list given its index instead of its
323value: the :keyword:`del` statement. This differs from the :meth:`pop` method
324which returns a value. The :keyword:`del` statement can also be used to remove
325slices from a list or clear the entire list (which we did earlier by assignment
326of an empty list to the slice). For example::
327
328 >>> a = [-1, 1, 66.25, 333, 333, 1234.5]
329 >>> del a[0]
330 >>> a
331 [1, 66.25, 333, 333, 1234.5]
332 >>> del a[2:4]
333 >>> a
334 [1, 66.25, 1234.5]
335 >>> del a[:]
336 >>> a
337 []
338
339:keyword:`del` can also be used to delete entire variables::
340
341 >>> del a
342
343Referencing the name ``a`` hereafter is an error (at least until another value
344is assigned to it). We'll find other uses for :keyword:`del` later.
345
346
Georg Brandl5d955ed2008-09-13 17:18:21 +0000347.. _tut-tuples:
Georg Brandl116aa622007-08-15 14:28:22 +0000348
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000349Tuples and Sequences
350====================
351
352We saw that lists and strings have many common properties, such as indexing and
353slicing operations. They are two examples of *sequence* data types (see
354:ref:`typesseq`). Since Python is an evolving language, other sequence data
355types may be added. There is also another standard sequence data type: the
356*tuple*.
357
358A tuple consists of a number of values separated by commas, for instance::
359
360 >>> t = 12345, 54321, 'hello!'
361 >>> t[0]
362 12345
363 >>> t
364 (12345, 54321, 'hello!')
365 >>> # Tuples may be nested:
366 ... u = t, (1, 2, 3, 4, 5)
367 >>> u
368 ((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))
Ezio Melottif90ea1f2012-06-17 14:10:59 +0200369 >>> # Tuples are immutable:
370 ... t[0] = 88888
371 Traceback (most recent call last):
372 File "<stdin>", line 1, in <module>
373 TypeError: 'tuple' object does not support item assignment
374 >>> # but they can contain mutable objects:
375 ... v = ([1, 2, 3], [3, 2, 1])
376 >>> v
377 ([1, 2, 3], [3, 2, 1])
378
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000379
380As you see, on output tuples are always enclosed in parentheses, so that nested
381tuples are interpreted correctly; they may be input with or without surrounding
382parentheses, although often parentheses are necessary anyway (if the tuple is
Ezio Melottif90ea1f2012-06-17 14:10:59 +0200383part of a larger expression). It is not possible to assign to the individual
384items of a tuple, however it is possible to create tuples which contain mutable
385objects, such as lists.
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000386
Ezio Melottif90ea1f2012-06-17 14:10:59 +0200387Though tuples may seem similar to lists, they are often used in different
388situations and for different purposes.
389Tuples are :term:`immutable`, and usually contain an heterogeneous sequence of
390elements that are accessed via unpacking (see later in this section) or indexing
391(or even by attribute in the case of :func:`namedtuples <collections.namedtuple>`).
392Lists are :term:`mutable`, and their elements are usually homogeneous and are
393accessed by iterating over the list.
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000394
395A special problem is the construction of tuples containing 0 or 1 items: the
396syntax has some extra quirks to accommodate these. Empty tuples are constructed
397by an empty pair of parentheses; a tuple with one item is constructed by
398following a value with a comma (it is not sufficient to enclose a single value
399in parentheses). Ugly, but effective. For example::
400
401 >>> empty = ()
402 >>> singleton = 'hello', # <-- note trailing comma
403 >>> len(empty)
404 0
405 >>> len(singleton)
406 1
407 >>> singleton
408 ('hello',)
409
410The statement ``t = 12345, 54321, 'hello!'`` is an example of *tuple packing*:
411the values ``12345``, ``54321`` and ``'hello!'`` are packed together in a tuple.
412The reverse operation is also possible::
413
414 >>> x, y, z = t
415
Benjamin Petersond23f8222009-04-05 19:13:16 +0000416This is called, appropriately enough, *sequence unpacking* and works for any
Georg Brandl7ae90dd2009-06-08 18:59:09 +0000417sequence on the right-hand side. Sequence unpacking requires that there are as
418many variables on the left side of the equals sign as there are elements in the
Benjamin Petersond23f8222009-04-05 19:13:16 +0000419sequence. Note that multiple assignment is really just a combination of tuple
420packing and sequence unpacking.
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000421
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000422
Georg Brandl116aa622007-08-15 14:28:22 +0000423.. _tut-sets:
424
425Sets
426====
427
428Python also includes a data type for *sets*. A set is an unordered collection
429with no duplicate elements. Basic uses include membership testing and
430eliminating duplicate entries. Set objects also support mathematical operations
431like union, intersection, difference, and symmetric difference.
432
Ezio Melotti89b03b02012-11-17 12:06:01 +0200433Curly braces or the :func:`set` function can be used to create sets. Note: to
Georg Brandl10e0e302009-06-08 20:25:55 +0000434create an empty set you have to use ``set()``, not ``{}``; the latter creates an
435empty dictionary, a data structure that we discuss in the next section.
Guido van Rossum0616b792007-08-31 03:25:11 +0000436
Georg Brandl116aa622007-08-15 14:28:22 +0000437Here is a brief demonstration::
438
Raymond Hettingerafdeca92010-08-08 01:30:45 +0000439 >>> basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
440 >>> print(basket) # show that duplicates have been removed
Georg Brandl1790ed22010-11-10 07:57:10 +0000441 {'orange', 'banana', 'pear', 'apple'}
Raymond Hettingerafdeca92010-08-08 01:30:45 +0000442 >>> 'orange' in basket # fast membership testing
Georg Brandl116aa622007-08-15 14:28:22 +0000443 True
Raymond Hettingerafdeca92010-08-08 01:30:45 +0000444 >>> 'crabgrass' in basket
Georg Brandl116aa622007-08-15 14:28:22 +0000445 False
446
447 >>> # Demonstrate set operations on unique letters from two words
448 ...
449 >>> a = set('abracadabra')
450 >>> b = set('alacazam')
451 >>> a # unique letters in a
Guido van Rossum0616b792007-08-31 03:25:11 +0000452 {'a', 'r', 'b', 'c', 'd'}
Georg Brandl116aa622007-08-15 14:28:22 +0000453 >>> a - b # letters in a but not in b
Guido van Rossum0616b792007-08-31 03:25:11 +0000454 {'r', 'd', 'b'}
Georg Brandl116aa622007-08-15 14:28:22 +0000455 >>> a | b # letters in either a or b
Guido van Rossum0616b792007-08-31 03:25:11 +0000456 {'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}
Georg Brandl116aa622007-08-15 14:28:22 +0000457 >>> a & b # letters in both a and b
Guido van Rossum0616b792007-08-31 03:25:11 +0000458 {'a', 'c'}
Georg Brandl116aa622007-08-15 14:28:22 +0000459 >>> a ^ b # letters in a or b but not both
Guido van Rossum0616b792007-08-31 03:25:11 +0000460 {'r', 'd', 'b', 'm', 'z', 'l'}
461
Ezio Melotti89b03b02012-11-17 12:06:01 +0200462Similarly to :ref:`list comprehensions <tut-listcomps>`, set comprehensions
463are also supported::
Georg Brandlf6945182008-02-01 11:56:49 +0000464
465 >>> a = {x for x in 'abracadabra' if x not in 'abc'}
466 >>> a
467 {'r', 'd'}
Guido van Rossum0616b792007-08-31 03:25:11 +0000468
Georg Brandl116aa622007-08-15 14:28:22 +0000469
Georg Brandl116aa622007-08-15 14:28:22 +0000470.. _tut-dictionaries:
471
472Dictionaries
473============
474
475Another useful data type built into Python is the *dictionary* (see
476:ref:`typesmapping`). Dictionaries are sometimes found in other languages as
477"associative memories" or "associative arrays". Unlike sequences, which are
478indexed by a range of numbers, dictionaries are indexed by *keys*, which can be
479any immutable type; strings and numbers can always be keys. Tuples can be used
480as keys if they contain only strings, numbers, or tuples; if a tuple contains
481any mutable object either directly or indirectly, it cannot be used as a key.
482You can't use lists as keys, since lists can be modified in place using index
483assignments, slice assignments, or methods like :meth:`append` and
484:meth:`extend`.
485
486It is best to think of a dictionary as an unordered set of *key: value* pairs,
487with the requirement that the keys are unique (within one dictionary). A pair of
488braces creates an empty dictionary: ``{}``. Placing a comma-separated list of
489key:value pairs within the braces adds initial key:value pairs to the
490dictionary; this is also the way dictionaries are written on output.
491
492The main operations on a dictionary are storing a value with some key and
493extracting the value given the key. It is also possible to delete a key:value
494pair with ``del``. If you store using a key that is already in use, the old
495value associated with that key is forgotten. It is an error to extract a value
496using a non-existent key.
497
Georg Brandlabffe712008-12-15 08:28:37 +0000498Performing ``list(d.keys())`` on a dictionary returns a list of all the keys
Georg Brandlfc11f272009-06-16 19:22:10 +0000499used in the dictionary, in arbitrary order (if you want it sorted, just use
Georg Brandl388349a2011-10-08 18:32:40 +0200500``sorted(d.keys())`` instead). [2]_ To check whether a single key is in the
Georg Brandlfc11f272009-06-16 19:22:10 +0000501dictionary, use the :keyword:`in` keyword.
Georg Brandl116aa622007-08-15 14:28:22 +0000502
503Here is a small example using a dictionary::
504
505 >>> tel = {'jack': 4098, 'sape': 4139}
506 >>> tel['guido'] = 4127
507 >>> tel
508 {'sape': 4139, 'guido': 4127, 'jack': 4098}
509 >>> tel['jack']
510 4098
511 >>> del tel['sape']
512 >>> tel['irv'] = 4127
513 >>> tel
514 {'guido': 4127, 'irv': 4127, 'jack': 4098}
Neal Norwitze0906d12007-08-31 03:46:28 +0000515 >>> list(tel.keys())
Georg Brandlabffe712008-12-15 08:28:37 +0000516 ['irv', 'guido', 'jack']
517 >>> sorted(tel.keys())
Georg Brandl116aa622007-08-15 14:28:22 +0000518 ['guido', 'irv', 'jack']
Georg Brandl116aa622007-08-15 14:28:22 +0000519 >>> 'guido' in tel
520 True
Neal Norwitze0906d12007-08-31 03:46:28 +0000521 >>> 'jack' not in tel
522 False
Georg Brandl116aa622007-08-15 14:28:22 +0000523
Georg Brandlfc11f272009-06-16 19:22:10 +0000524The :func:`dict` constructor builds dictionaries directly from sequences of
Raymond Hettinger8699aea2009-06-16 20:49:30 +0000525key-value pairs::
Georg Brandl116aa622007-08-15 14:28:22 +0000526
527 >>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
528 {'sape': 4139, 'jack': 4098, 'guido': 4127}
Georg Brandl116aa622007-08-15 14:28:22 +0000529
Georg Brandlf6945182008-02-01 11:56:49 +0000530In addition, dict comprehensions can be used to create dictionaries from
531arbitrary key and value expressions::
532
533 >>> {x: x**2 for x in (2, 4, 6)}
534 {2: 4, 4: 16, 6: 36}
Georg Brandl116aa622007-08-15 14:28:22 +0000535
536When the keys are simple strings, it is sometimes easier to specify pairs using
537keyword arguments::
538
539 >>> dict(sape=4139, guido=4127, jack=4098)
540 {'sape': 4139, 'jack': 4098, 'guido': 4127}
541
542
543.. _tut-loopidioms:
544
545Looping Techniques
546==================
547
548When looping through dictionaries, the key and corresponding value can be
Neal Norwitze0906d12007-08-31 03:46:28 +0000549retrieved at the same time using the :meth:`items` method. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000550
551 >>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
Neal Norwitze0906d12007-08-31 03:46:28 +0000552 >>> for k, v in knights.items():
Guido van Rossum0616b792007-08-31 03:25:11 +0000553 ... print(k, v)
Georg Brandl116aa622007-08-15 14:28:22 +0000554 ...
555 gallahad the pure
556 robin the brave
557
558When looping through a sequence, the position index and corresponding value can
559be retrieved at the same time using the :func:`enumerate` function. ::
560
561 >>> for i, v in enumerate(['tic', 'tac', 'toe']):
Guido van Rossum0616b792007-08-31 03:25:11 +0000562 ... print(i, v)
Georg Brandl116aa622007-08-15 14:28:22 +0000563 ...
564 0 tic
565 1 tac
566 2 toe
567
568To loop over two or more sequences at the same time, the entries can be paired
569with the :func:`zip` function. ::
570
571 >>> questions = ['name', 'quest', 'favorite color']
572 >>> answers = ['lancelot', 'the holy grail', 'blue']
573 >>> for q, a in zip(questions, answers):
Benjamin Petersone6f00632008-05-26 01:03:56 +0000574 ... print('What is your {0}? It is {1}.'.format(q, a))
Georg Brandl06788c92009-01-03 21:31:47 +0000575 ...
Georg Brandl116aa622007-08-15 14:28:22 +0000576 What is your name? It is lancelot.
577 What is your quest? It is the holy grail.
578 What is your favorite color? It is blue.
579
580To loop over a sequence in reverse, first specify the sequence in a forward
581direction and then call the :func:`reversed` function. ::
582
Georg Brandle4ac7502007-09-03 07:10:24 +0000583 >>> for i in reversed(range(1, 10, 2)):
Guido van Rossum0616b792007-08-31 03:25:11 +0000584 ... print(i)
Georg Brandl116aa622007-08-15 14:28:22 +0000585 ...
586 9
587 7
588 5
589 3
590 1
591
592To loop over a sequence in sorted order, use the :func:`sorted` function which
593returns a new sorted list while leaving the source unaltered. ::
594
595 >>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
596 >>> for f in sorted(set(basket)):
Guido van Rossum0616b792007-08-31 03:25:11 +0000597 ... print(f)
Georg Brandl06788c92009-01-03 21:31:47 +0000598 ...
Georg Brandl116aa622007-08-15 14:28:22 +0000599 apple
600 banana
601 orange
602 pear
603
Chris Jerdonek4fab8f02012-10-15 19:44:47 -0700604To change a sequence you are iterating over while inside the loop (for
605example to duplicate certain items), it is recommended that you first make
606a copy. Looping over a sequence does not implicitly make a copy. The slice
607notation makes this especially convenient::
608
609 >>> words = ['cat', 'window', 'defenestrate']
610 >>> for w in words[:]: # Loop over a slice copy of the entire list.
611 ... if len(w) > 6:
612 ... words.insert(0, w)
613 ...
614 >>> words
615 ['defenestrate', 'cat', 'window', 'defenestrate']
616
Georg Brandl116aa622007-08-15 14:28:22 +0000617
618.. _tut-conditions:
619
620More on Conditions
621==================
622
623The conditions used in ``while`` and ``if`` statements can contain any
624operators, not just comparisons.
625
626The comparison operators ``in`` and ``not in`` check whether a value occurs
627(does not occur) in a sequence. The operators ``is`` and ``is not`` compare
628whether two objects are really the same object; this only matters for mutable
629objects like lists. All comparison operators have the same priority, which is
630lower than that of all numerical operators.
631
632Comparisons can be chained. For example, ``a < b == c`` tests whether ``a`` is
633less than ``b`` and moreover ``b`` equals ``c``.
634
635Comparisons may be combined using the Boolean operators ``and`` and ``or``, and
636the outcome of a comparison (or of any other Boolean expression) may be negated
637with ``not``. These have lower priorities than comparison operators; between
638them, ``not`` has the highest priority and ``or`` the lowest, so that ``A and
639not B or C`` is equivalent to ``(A and (not B)) or C``. As always, parentheses
640can be used to express the desired composition.
641
642The Boolean operators ``and`` and ``or`` are so-called *short-circuit*
643operators: their arguments are evaluated from left to right, and evaluation
644stops as soon as the outcome is determined. For example, if ``A`` and ``C`` are
645true but ``B`` is false, ``A and B and C`` does not evaluate the expression
646``C``. When used as a general value and not as a Boolean, the return value of a
647short-circuit operator is the last evaluated argument.
648
649It is possible to assign the result of a comparison or other Boolean expression
650to a variable. For example, ::
651
652 >>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance'
653 >>> non_null = string1 or string2 or string3
654 >>> non_null
655 'Trondheim'
656
657Note that in Python, unlike C, assignment cannot occur inside expressions. C
658programmers may grumble about this, but it avoids a common class of problems
659encountered in C programs: typing ``=`` in an expression when ``==`` was
660intended.
661
662
663.. _tut-comparing:
664
665Comparing Sequences and Other Types
666===================================
667
668Sequence objects may be compared to other objects with the same sequence type.
669The comparison uses *lexicographical* ordering: first the first two items are
670compared, and if they differ this determines the outcome of the comparison; if
671they are equal, the next two items are compared, and so on, until either
672sequence is exhausted. If two items to be compared are themselves sequences of
673the same type, the lexicographical comparison is carried out recursively. If
674all items of two sequences compare equal, the sequences are considered equal.
675If one sequence is an initial sub-sequence of the other, the shorter sequence is
Georg Brandlfc11f272009-06-16 19:22:10 +0000676the smaller (lesser) one. Lexicographical ordering for strings uses the Unicode
677codepoint number to order individual characters. Some examples of comparisons
678between sequences of the same type::
Georg Brandl116aa622007-08-15 14:28:22 +0000679
680 (1, 2, 3) < (1, 2, 4)
681 [1, 2, 3] < [1, 2, 4]
682 'ABC' < 'C' < 'Pascal' < 'Python'
683 (1, 2, 3, 4) < (1, 2, 4)
684 (1, 2) < (1, 2, -1)
685 (1, 2, 3) == (1.0, 2.0, 3.0)
686 (1, 2, ('aa', 'ab')) < (1, 2, ('abc', 'a'), 4)
687
Georg Brandl9f2c39a2007-10-08 14:08:36 +0000688Note that comparing objects of different types with ``<`` or ``>`` is legal
689provided that the objects have appropriate comparison methods. For example,
690mixed numeric types are compared according to their numeric value, so 0 equals
6910.0, etc. Otherwise, rather than providing an arbitrary ordering, the
692interpreter will raise a :exc:`TypeError` exception.
Georg Brandlfc11f272009-06-16 19:22:10 +0000693
694
695.. rubric:: Footnotes
696
Georg Brandl388349a2011-10-08 18:32:40 +0200697.. [1] Other languages may return the mutated object, which allows method
698 chaining, such as ``d->insert("a")->remove("b")->sort();``.
699
700.. [2] Calling ``d.keys()`` will return a :dfn:`dictionary view` object. It
Georg Brandlfc11f272009-06-16 19:22:10 +0000701 supports operations like membership test and iteration, but its contents
702 are not independent of the original dictionary -- it is only a *view*.