blob: f2b66f70d830be1b118d039a535875475981c789 [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]
Terry Jan Reedye17de092014-05-23 00:34:12 -0400114 >>> a.pop()
115 1234.5
116 >>> a
117 [-1, 1, 66.25, 333, 333]
Georg Brandl116aa622007-08-15 14:28:22 +0000118
Georg Brandl388349a2011-10-08 18:32:40 +0200119You might have noticed that methods like ``insert``, ``remove`` or ``sort`` that
Terry Jan Reedye17de092014-05-23 00:34:12 -0400120only modify the list have no return value printed -- they return the default
121``None``. [1]_ This is a design principle for all mutable data structures in
122Python.
Georg Brandl388349a2011-10-08 18:32:40 +0200123
Georg Brandl116aa622007-08-15 14:28:22 +0000124
125.. _tut-lists-as-stacks:
126
127Using Lists as Stacks
128---------------------
129
130.. sectionauthor:: Ka-Ping Yee <ping@lfw.org>
131
132
133The list methods make it very easy to use a list as a stack, where the last
134element added is the first element retrieved ("last-in, first-out"). To add an
135item to the top of the stack, use :meth:`append`. To retrieve an item from the
136top of the stack, use :meth:`pop` without an explicit index. For example::
137
138 >>> stack = [3, 4, 5]
139 >>> stack.append(6)
140 >>> stack.append(7)
141 >>> stack
142 [3, 4, 5, 6, 7]
143 >>> stack.pop()
144 7
145 >>> stack
146 [3, 4, 5, 6]
147 >>> stack.pop()
148 6
149 >>> stack.pop()
150 5
151 >>> stack
152 [3, 4]
153
154
155.. _tut-lists-as-queues:
156
157Using Lists as Queues
158---------------------
159
160.. sectionauthor:: Ka-Ping Yee <ping@lfw.org>
161
Ezio Melotti8f8db142010-03-31 07:45:32 +0000162It is also possible to use a list as a queue, where the first element added is
163the first element retrieved ("first-in, first-out"); however, lists are not
164efficient for this purpose. While appends and pops from the end of list are
165fast, doing inserts or pops from the beginning of a list is slow (because all
166of the other elements have to be shifted by one).
Georg Brandl116aa622007-08-15 14:28:22 +0000167
Ezio Melotti8f8db142010-03-31 07:45:32 +0000168To implement a queue, use :class:`collections.deque` which was designed to
169have fast appends and pops from both ends. For example::
Georg Brandl116aa622007-08-15 14:28:22 +0000170
Ezio Melotti8f8db142010-03-31 07:45:32 +0000171 >>> from collections import deque
172 >>> queue = deque(["Eric", "John", "Michael"])
Georg Brandl116aa622007-08-15 14:28:22 +0000173 >>> queue.append("Terry") # Terry arrives
174 >>> queue.append("Graham") # Graham arrives
Ezio Melotti8f8db142010-03-31 07:45:32 +0000175 >>> queue.popleft() # The first to arrive now leaves
Georg Brandl116aa622007-08-15 14:28:22 +0000176 'Eric'
Ezio Melotti8f8db142010-03-31 07:45:32 +0000177 >>> queue.popleft() # The second to arrive now leaves
Georg Brandl116aa622007-08-15 14:28:22 +0000178 'John'
Ezio Melotti8f8db142010-03-31 07:45:32 +0000179 >>> queue # Remaining queue in order of arrival
180 deque(['Michael', 'Terry', 'Graham'])
Georg Brandl718ce2c2010-03-21 09:51:44 +0000181
Georg Brandl116aa622007-08-15 14:28:22 +0000182
Georg Brandlfc11f272009-06-16 19:22:10 +0000183.. _tut-listcomps:
184
Georg Brandl116aa622007-08-15 14:28:22 +0000185List Comprehensions
186-------------------
187
Ezio Melotti91621e22011-12-13 15:36:19 +0200188List comprehensions provide a concise way to create lists.
189Common applications are to make new lists where each element is the result of
190some operations applied to each member of another sequence or iterable, or to
191create a subsequence of those elements that satisfy a certain condition.
192
193For example, assume we want to create a list of squares, like::
194
195 >>> squares = []
196 >>> for x in range(10):
197 ... squares.append(x**2)
198 ...
199 >>> squares
200 [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
201
202We can obtain the same result with::
203
204 squares = [x**2 for x in range(10)]
205
Chris Jerdonekfd448da2012-09-28 07:07:12 -0700206This is also equivalent to ``squares = list(map(lambda x: x**2, range(10)))``,
Ezio Melotti91621e22011-12-13 15:36:19 +0200207but it's more concise and readable.
Guido van Rossum0616b792007-08-31 03:25:11 +0000208
Georg Brandl7ae90dd2009-06-08 18:59:09 +0000209A list comprehension consists of brackets containing an expression followed
210by a :keyword:`for` clause, then zero or more :keyword:`for` or :keyword:`if`
Ezio Melotti91621e22011-12-13 15:36:19 +0200211clauses. The result will be a new list resulting from evaluating the expression
212in the context of the :keyword:`for` and :keyword:`if` clauses which follow it.
213For example, this listcomp combines the elements of two lists if they are not
214equal::
Guido van Rossum0616b792007-08-31 03:25:11 +0000215
Ezio Melotti91621e22011-12-13 15:36:19 +0200216 >>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
217 [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
Guido van Rossum0616b792007-08-31 03:25:11 +0000218
Ezio Melotti91621e22011-12-13 15:36:19 +0200219and it's equivalent to::
Guido van Rossum0616b792007-08-31 03:25:11 +0000220
Ezio Melotti91621e22011-12-13 15:36:19 +0200221 >>> combs = []
222 >>> for x in [1,2,3]:
223 ... for y in [3,1,4]:
224 ... if x != y:
225 ... combs.append((x, y))
226 ...
227 >>> combs
228 [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
Guido van Rossum0616b792007-08-31 03:25:11 +0000229
Ezio Melotti91621e22011-12-13 15:36:19 +0200230Note how the order of the :keyword:`for` and :keyword:`if` statements is the
231same in both these snippets.
Guido van Rossum0616b792007-08-31 03:25:11 +0000232
Ezio Melotti91621e22011-12-13 15:36:19 +0200233If the expression is a tuple (e.g. the ``(x, y)`` in the previous example),
234it must be parenthesized. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000235
Ezio Melotti91621e22011-12-13 15:36:19 +0200236 >>> vec = [-4, -2, 0, 2, 4]
237 >>> # create a new list with the values doubled
238 >>> [x*2 for x in vec]
239 [-8, -4, 0, 4, 8]
240 >>> # filter the list to exclude negative numbers
241 >>> [x for x in vec if x >= 0]
242 [0, 2, 4]
243 >>> # apply a function to all the elements
244 >>> [abs(x) for x in vec]
245 [4, 2, 0, 2, 4]
246 >>> # call a method on each element
Georg Brandl116aa622007-08-15 14:28:22 +0000247 >>> freshfruit = [' banana', ' loganberry ', 'passion fruit ']
248 >>> [weapon.strip() for weapon in freshfruit]
249 ['banana', 'loganberry', 'passion fruit']
Ezio Melotti91621e22011-12-13 15:36:19 +0200250 >>> # create a list of 2-tuples like (number, square)
251 >>> [(x, x**2) for x in range(6)]
252 [(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]
253 >>> # the tuple must be parenthesized, otherwise an error is raised
254 >>> [x, x**2 for x in range(6)]
Georg Brandl116aa622007-08-15 14:28:22 +0000255 File "<stdin>", line 1, in ?
Ezio Melotti91621e22011-12-13 15:36:19 +0200256 [x, x**2 for x in range(6)]
Georg Brandl116aa622007-08-15 14:28:22 +0000257 ^
258 SyntaxError: invalid syntax
Ezio Melotti91621e22011-12-13 15:36:19 +0200259 >>> # flatten a list using a listcomp with two 'for'
260 >>> vec = [[1,2,3], [4,5,6], [7,8,9]]
261 >>> [num for elem in vec for num in elem]
262 [1, 2, 3, 4, 5, 6, 7, 8, 9]
Guido van Rossum0616b792007-08-31 03:25:11 +0000263
Ezio Melotti91621e22011-12-13 15:36:19 +0200264List comprehensions can contain complex expressions and nested functions::
Guido van Rossum0616b792007-08-31 03:25:11 +0000265
Ezio Melotti91621e22011-12-13 15:36:19 +0200266 >>> from math import pi
267 >>> [str(round(pi, i)) for i in range(1, 6)]
Georg Brandl116aa622007-08-15 14:28:22 +0000268 ['3.1', '3.14', '3.142', '3.1416', '3.14159']
269
Christian Heimes0449f632007-12-15 01:27:15 +0000270Nested List Comprehensions
271--------------------------
272
Ezio Melotti91621e22011-12-13 15:36:19 +0200273The initial expression in a list comprehension can be any arbitrary expression,
274including another list comprehension.
Christian Heimes0449f632007-12-15 01:27:15 +0000275
Ezio Melotti91621e22011-12-13 15:36:19 +0200276Consider the following example of a 3x4 matrix implemented as a list of
2773 lists of length 4::
Christian Heimes0449f632007-12-15 01:27:15 +0000278
Ezio Melotti91621e22011-12-13 15:36:19 +0200279 >>> matrix = [
280 ... [1, 2, 3, 4],
281 ... [5, 6, 7, 8],
282 ... [9, 10, 11, 12],
283 ... ]
Christian Heimes0449f632007-12-15 01:27:15 +0000284
Ezio Melotti91621e22011-12-13 15:36:19 +0200285The following list comprehension will transpose rows and columns::
Christian Heimes0449f632007-12-15 01:27:15 +0000286
Ezio Melotti91621e22011-12-13 15:36:19 +0200287 >>> [[row[i] for row in matrix] for i in range(4)]
288 [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
Christian Heimes0449f632007-12-15 01:27:15 +0000289
Ezio Melotti91621e22011-12-13 15:36:19 +0200290As we saw in the previous section, the nested listcomp is evaluated in
291the context of the :keyword:`for` that follows it, so this example is
292equivalent to::
Christian Heimes0449f632007-12-15 01:27:15 +0000293
Ezio Melotti91621e22011-12-13 15:36:19 +0200294 >>> transposed = []
295 >>> for i in range(4):
296 ... transposed.append([row[i] for row in matrix])
297 ...
298 >>> transposed
299 [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
Christian Heimes0449f632007-12-15 01:27:15 +0000300
Ezio Melotti91621e22011-12-13 15:36:19 +0200301which, in turn, is the same as::
Christian Heimes0449f632007-12-15 01:27:15 +0000302
Ezio Melotti91621e22011-12-13 15:36:19 +0200303 >>> transposed = []
304 >>> for i in range(4):
305 ... # the following 3 lines implement the nested listcomp
306 ... transposed_row = []
307 ... for row in matrix:
308 ... transposed_row.append(row[i])
309 ... transposed.append(transposed_row)
310 ...
311 >>> transposed
312 [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
Christian Heimes0449f632007-12-15 01:27:15 +0000313
Ezio Melotti91621e22011-12-13 15:36:19 +0200314In the real world, you should prefer built-in functions to complex flow statements.
Christian Heimes0449f632007-12-15 01:27:15 +0000315The :func:`zip` function would do a great job for this use case::
316
Sandro Tosi0a90a822012-08-12 10:24:50 +0200317 >>> list(zip(*matrix))
Ezio Melotti91621e22011-12-13 15:36:19 +0200318 [(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]
Christian Heimes0449f632007-12-15 01:27:15 +0000319
320See :ref:`tut-unpacking-arguments` for details on the asterisk in this line.
321
Georg Brandl116aa622007-08-15 14:28:22 +0000322.. _tut-del:
323
324The :keyword:`del` statement
325============================
326
327There is a way to remove an item from a list given its index instead of its
328value: the :keyword:`del` statement. This differs from the :meth:`pop` method
329which returns a value. The :keyword:`del` statement can also be used to remove
330slices from a list or clear the entire list (which we did earlier by assignment
331of an empty list to the slice). For example::
332
333 >>> a = [-1, 1, 66.25, 333, 333, 1234.5]
334 >>> del a[0]
335 >>> a
336 [1, 66.25, 333, 333, 1234.5]
337 >>> del a[2:4]
338 >>> a
339 [1, 66.25, 1234.5]
340 >>> del a[:]
341 >>> a
342 []
343
344:keyword:`del` can also be used to delete entire variables::
345
346 >>> del a
347
348Referencing the name ``a`` hereafter is an error (at least until another value
349is assigned to it). We'll find other uses for :keyword:`del` later.
350
351
Georg Brandl5d955ed2008-09-13 17:18:21 +0000352.. _tut-tuples:
Georg Brandl116aa622007-08-15 14:28:22 +0000353
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000354Tuples and Sequences
355====================
356
357We saw that lists and strings have many common properties, such as indexing and
358slicing operations. They are two examples of *sequence* data types (see
359:ref:`typesseq`). Since Python is an evolving language, other sequence data
360types may be added. There is also another standard sequence data type: the
361*tuple*.
362
363A tuple consists of a number of values separated by commas, for instance::
364
365 >>> t = 12345, 54321, 'hello!'
366 >>> t[0]
367 12345
368 >>> t
369 (12345, 54321, 'hello!')
370 >>> # Tuples may be nested:
371 ... u = t, (1, 2, 3, 4, 5)
372 >>> u
373 ((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))
Ezio Melottif90ea1f2012-06-17 14:10:59 +0200374 >>> # Tuples are immutable:
375 ... t[0] = 88888
376 Traceback (most recent call last):
377 File "<stdin>", line 1, in <module>
378 TypeError: 'tuple' object does not support item assignment
379 >>> # but they can contain mutable objects:
380 ... v = ([1, 2, 3], [3, 2, 1])
381 >>> v
382 ([1, 2, 3], [3, 2, 1])
383
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000384
385As you see, on output tuples are always enclosed in parentheses, so that nested
386tuples are interpreted correctly; they may be input with or without surrounding
387parentheses, although often parentheses are necessary anyway (if the tuple is
Ezio Melottif90ea1f2012-06-17 14:10:59 +0200388part of a larger expression). It is not possible to assign to the individual
389items of a tuple, however it is possible to create tuples which contain mutable
390objects, such as lists.
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000391
Ezio Melottif90ea1f2012-06-17 14:10:59 +0200392Though tuples may seem similar to lists, they are often used in different
393situations and for different purposes.
394Tuples are :term:`immutable`, and usually contain an heterogeneous sequence of
395elements that are accessed via unpacking (see later in this section) or indexing
396(or even by attribute in the case of :func:`namedtuples <collections.namedtuple>`).
397Lists are :term:`mutable`, and their elements are usually homogeneous and are
398accessed by iterating over the list.
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000399
400A special problem is the construction of tuples containing 0 or 1 items: the
401syntax has some extra quirks to accommodate these. Empty tuples are constructed
402by an empty pair of parentheses; a tuple with one item is constructed by
403following a value with a comma (it is not sufficient to enclose a single value
404in parentheses). Ugly, but effective. For example::
405
406 >>> empty = ()
407 >>> singleton = 'hello', # <-- note trailing comma
408 >>> len(empty)
409 0
410 >>> len(singleton)
411 1
412 >>> singleton
413 ('hello',)
414
415The statement ``t = 12345, 54321, 'hello!'`` is an example of *tuple packing*:
416the values ``12345``, ``54321`` and ``'hello!'`` are packed together in a tuple.
417The reverse operation is also possible::
418
419 >>> x, y, z = t
420
Benjamin Petersond23f8222009-04-05 19:13:16 +0000421This is called, appropriately enough, *sequence unpacking* and works for any
Georg Brandl7ae90dd2009-06-08 18:59:09 +0000422sequence on the right-hand side. Sequence unpacking requires that there are as
423many variables on the left side of the equals sign as there are elements in the
Benjamin Petersond23f8222009-04-05 19:13:16 +0000424sequence. Note that multiple assignment is really just a combination of tuple
425packing and sequence unpacking.
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000426
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000427
Georg Brandl116aa622007-08-15 14:28:22 +0000428.. _tut-sets:
429
430Sets
431====
432
433Python also includes a data type for *sets*. A set is an unordered collection
434with no duplicate elements. Basic uses include membership testing and
435eliminating duplicate entries. Set objects also support mathematical operations
436like union, intersection, difference, and symmetric difference.
437
Ezio Melotti89b03b02012-11-17 12:06:01 +0200438Curly braces or the :func:`set` function can be used to create sets. Note: to
Georg Brandl10e0e302009-06-08 20:25:55 +0000439create an empty set you have to use ``set()``, not ``{}``; the latter creates an
440empty dictionary, a data structure that we discuss in the next section.
Guido van Rossum0616b792007-08-31 03:25:11 +0000441
Georg Brandl116aa622007-08-15 14:28:22 +0000442Here is a brief demonstration::
443
Raymond Hettingerafdeca92010-08-08 01:30:45 +0000444 >>> basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
445 >>> print(basket) # show that duplicates have been removed
Georg Brandl1790ed22010-11-10 07:57:10 +0000446 {'orange', 'banana', 'pear', 'apple'}
Raymond Hettingerafdeca92010-08-08 01:30:45 +0000447 >>> 'orange' in basket # fast membership testing
Georg Brandl116aa622007-08-15 14:28:22 +0000448 True
Raymond Hettingerafdeca92010-08-08 01:30:45 +0000449 >>> 'crabgrass' in basket
Georg Brandl116aa622007-08-15 14:28:22 +0000450 False
451
452 >>> # Demonstrate set operations on unique letters from two words
453 ...
454 >>> a = set('abracadabra')
455 >>> b = set('alacazam')
456 >>> a # unique letters in a
Guido van Rossum0616b792007-08-31 03:25:11 +0000457 {'a', 'r', 'b', 'c', 'd'}
Georg Brandl116aa622007-08-15 14:28:22 +0000458 >>> a - b # letters in a but not in b
Guido van Rossum0616b792007-08-31 03:25:11 +0000459 {'r', 'd', 'b'}
Georg Brandl116aa622007-08-15 14:28:22 +0000460 >>> a | b # letters in either a or b
Guido van Rossum0616b792007-08-31 03:25:11 +0000461 {'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}
Georg Brandl116aa622007-08-15 14:28:22 +0000462 >>> a & b # letters in both a and b
Guido van Rossum0616b792007-08-31 03:25:11 +0000463 {'a', 'c'}
Georg Brandl116aa622007-08-15 14:28:22 +0000464 >>> a ^ b # letters in a or b but not both
Guido van Rossum0616b792007-08-31 03:25:11 +0000465 {'r', 'd', 'b', 'm', 'z', 'l'}
466
Ezio Melotti89b03b02012-11-17 12:06:01 +0200467Similarly to :ref:`list comprehensions <tut-listcomps>`, set comprehensions
468are also supported::
Georg Brandlf6945182008-02-01 11:56:49 +0000469
470 >>> a = {x for x in 'abracadabra' if x not in 'abc'}
471 >>> a
472 {'r', 'd'}
Guido van Rossum0616b792007-08-31 03:25:11 +0000473
Georg Brandl116aa622007-08-15 14:28:22 +0000474
Georg Brandl116aa622007-08-15 14:28:22 +0000475.. _tut-dictionaries:
476
477Dictionaries
478============
479
480Another useful data type built into Python is the *dictionary* (see
481:ref:`typesmapping`). Dictionaries are sometimes found in other languages as
482"associative memories" or "associative arrays". Unlike sequences, which are
483indexed by a range of numbers, dictionaries are indexed by *keys*, which can be
484any immutable type; strings and numbers can always be keys. Tuples can be used
485as keys if they contain only strings, numbers, or tuples; if a tuple contains
486any mutable object either directly or indirectly, it cannot be used as a key.
487You can't use lists as keys, since lists can be modified in place using index
488assignments, slice assignments, or methods like :meth:`append` and
489:meth:`extend`.
490
491It is best to think of a dictionary as an unordered set of *key: value* pairs,
492with the requirement that the keys are unique (within one dictionary). A pair of
493braces creates an empty dictionary: ``{}``. Placing a comma-separated list of
494key:value pairs within the braces adds initial key:value pairs to the
495dictionary; this is also the way dictionaries are written on output.
496
497The main operations on a dictionary are storing a value with some key and
498extracting the value given the key. It is also possible to delete a key:value
499pair with ``del``. If you store using a key that is already in use, the old
500value associated with that key is forgotten. It is an error to extract a value
501using a non-existent key.
502
Georg Brandlabffe712008-12-15 08:28:37 +0000503Performing ``list(d.keys())`` on a dictionary returns a list of all the keys
Georg Brandlfc11f272009-06-16 19:22:10 +0000504used in the dictionary, in arbitrary order (if you want it sorted, just use
Georg Brandl388349a2011-10-08 18:32:40 +0200505``sorted(d.keys())`` instead). [2]_ To check whether a single key is in the
Georg Brandlfc11f272009-06-16 19:22:10 +0000506dictionary, use the :keyword:`in` keyword.
Georg Brandl116aa622007-08-15 14:28:22 +0000507
508Here is a small example using a dictionary::
509
510 >>> tel = {'jack': 4098, 'sape': 4139}
511 >>> tel['guido'] = 4127
512 >>> tel
513 {'sape': 4139, 'guido': 4127, 'jack': 4098}
514 >>> tel['jack']
515 4098
516 >>> del tel['sape']
517 >>> tel['irv'] = 4127
518 >>> tel
519 {'guido': 4127, 'irv': 4127, 'jack': 4098}
Neal Norwitze0906d12007-08-31 03:46:28 +0000520 >>> list(tel.keys())
Georg Brandlabffe712008-12-15 08:28:37 +0000521 ['irv', 'guido', 'jack']
522 >>> sorted(tel.keys())
Georg Brandl116aa622007-08-15 14:28:22 +0000523 ['guido', 'irv', 'jack']
Georg Brandl116aa622007-08-15 14:28:22 +0000524 >>> 'guido' in tel
525 True
Neal Norwitze0906d12007-08-31 03:46:28 +0000526 >>> 'jack' not in tel
527 False
Georg Brandl116aa622007-08-15 14:28:22 +0000528
Georg Brandlfc11f272009-06-16 19:22:10 +0000529The :func:`dict` constructor builds dictionaries directly from sequences of
Raymond Hettinger8699aea2009-06-16 20:49:30 +0000530key-value pairs::
Georg Brandl116aa622007-08-15 14:28:22 +0000531
532 >>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
533 {'sape': 4139, 'jack': 4098, 'guido': 4127}
Georg Brandl116aa622007-08-15 14:28:22 +0000534
Georg Brandlf6945182008-02-01 11:56:49 +0000535In addition, dict comprehensions can be used to create dictionaries from
536arbitrary key and value expressions::
537
538 >>> {x: x**2 for x in (2, 4, 6)}
539 {2: 4, 4: 16, 6: 36}
Georg Brandl116aa622007-08-15 14:28:22 +0000540
541When the keys are simple strings, it is sometimes easier to specify pairs using
542keyword arguments::
543
544 >>> dict(sape=4139, guido=4127, jack=4098)
545 {'sape': 4139, 'jack': 4098, 'guido': 4127}
546
547
548.. _tut-loopidioms:
549
550Looping Techniques
551==================
552
553When looping through dictionaries, the key and corresponding value can be
Neal Norwitze0906d12007-08-31 03:46:28 +0000554retrieved at the same time using the :meth:`items` method. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000555
556 >>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
Neal Norwitze0906d12007-08-31 03:46:28 +0000557 >>> for k, v in knights.items():
Guido van Rossum0616b792007-08-31 03:25:11 +0000558 ... print(k, v)
Georg Brandl116aa622007-08-15 14:28:22 +0000559 ...
560 gallahad the pure
561 robin the brave
562
563When looping through a sequence, the position index and corresponding value can
564be retrieved at the same time using the :func:`enumerate` function. ::
565
566 >>> for i, v in enumerate(['tic', 'tac', 'toe']):
Guido van Rossum0616b792007-08-31 03:25:11 +0000567 ... print(i, v)
Georg Brandl116aa622007-08-15 14:28:22 +0000568 ...
569 0 tic
570 1 tac
571 2 toe
572
573To loop over two or more sequences at the same time, the entries can be paired
574with the :func:`zip` function. ::
575
576 >>> questions = ['name', 'quest', 'favorite color']
577 >>> answers = ['lancelot', 'the holy grail', 'blue']
578 >>> for q, a in zip(questions, answers):
Benjamin Petersone6f00632008-05-26 01:03:56 +0000579 ... print('What is your {0}? It is {1}.'.format(q, a))
Georg Brandl06788c92009-01-03 21:31:47 +0000580 ...
Georg Brandl116aa622007-08-15 14:28:22 +0000581 What is your name? It is lancelot.
582 What is your quest? It is the holy grail.
583 What is your favorite color? It is blue.
584
585To loop over a sequence in reverse, first specify the sequence in a forward
586direction and then call the :func:`reversed` function. ::
587
Georg Brandle4ac7502007-09-03 07:10:24 +0000588 >>> for i in reversed(range(1, 10, 2)):
Guido van Rossum0616b792007-08-31 03:25:11 +0000589 ... print(i)
Georg Brandl116aa622007-08-15 14:28:22 +0000590 ...
591 9
592 7
593 5
594 3
595 1
596
597To loop over a sequence in sorted order, use the :func:`sorted` function which
598returns a new sorted list while leaving the source unaltered. ::
599
600 >>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
601 >>> for f in sorted(set(basket)):
Guido van Rossum0616b792007-08-31 03:25:11 +0000602 ... print(f)
Georg Brandl06788c92009-01-03 21:31:47 +0000603 ...
Georg Brandl116aa622007-08-15 14:28:22 +0000604 apple
605 banana
606 orange
607 pear
608
Chris Jerdonek4fab8f02012-10-15 19:44:47 -0700609To change a sequence you are iterating over while inside the loop (for
610example to duplicate certain items), it is recommended that you first make
611a copy. Looping over a sequence does not implicitly make a copy. The slice
612notation makes this especially convenient::
613
614 >>> words = ['cat', 'window', 'defenestrate']
615 >>> for w in words[:]: # Loop over a slice copy of the entire list.
616 ... if len(w) > 6:
617 ... words.insert(0, w)
618 ...
619 >>> words
620 ['defenestrate', 'cat', 'window', 'defenestrate']
621
Georg Brandl116aa622007-08-15 14:28:22 +0000622
623.. _tut-conditions:
624
625More on Conditions
626==================
627
628The conditions used in ``while`` and ``if`` statements can contain any
629operators, not just comparisons.
630
631The comparison operators ``in`` and ``not in`` check whether a value occurs
632(does not occur) in a sequence. The operators ``is`` and ``is not`` compare
633whether two objects are really the same object; this only matters for mutable
634objects like lists. All comparison operators have the same priority, which is
635lower than that of all numerical operators.
636
637Comparisons can be chained. For example, ``a < b == c`` tests whether ``a`` is
638less than ``b`` and moreover ``b`` equals ``c``.
639
640Comparisons may be combined using the Boolean operators ``and`` and ``or``, and
641the outcome of a comparison (or of any other Boolean expression) may be negated
642with ``not``. These have lower priorities than comparison operators; between
643them, ``not`` has the highest priority and ``or`` the lowest, so that ``A and
644not B or C`` is equivalent to ``(A and (not B)) or C``. As always, parentheses
645can be used to express the desired composition.
646
647The Boolean operators ``and`` and ``or`` are so-called *short-circuit*
648operators: their arguments are evaluated from left to right, and evaluation
649stops as soon as the outcome is determined. For example, if ``A`` and ``C`` are
650true but ``B`` is false, ``A and B and C`` does not evaluate the expression
651``C``. When used as a general value and not as a Boolean, the return value of a
652short-circuit operator is the last evaluated argument.
653
654It is possible to assign the result of a comparison or other Boolean expression
655to a variable. For example, ::
656
657 >>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance'
658 >>> non_null = string1 or string2 or string3
659 >>> non_null
660 'Trondheim'
661
662Note that in Python, unlike C, assignment cannot occur inside expressions. C
663programmers may grumble about this, but it avoids a common class of problems
664encountered in C programs: typing ``=`` in an expression when ``==`` was
665intended.
666
667
668.. _tut-comparing:
669
670Comparing Sequences and Other Types
671===================================
672
673Sequence objects may be compared to other objects with the same sequence type.
674The comparison uses *lexicographical* ordering: first the first two items are
675compared, and if they differ this determines the outcome of the comparison; if
676they are equal, the next two items are compared, and so on, until either
677sequence is exhausted. If two items to be compared are themselves sequences of
678the same type, the lexicographical comparison is carried out recursively. If
679all items of two sequences compare equal, the sequences are considered equal.
680If one sequence is an initial sub-sequence of the other, the shorter sequence is
Georg Brandlfc11f272009-06-16 19:22:10 +0000681the smaller (lesser) one. Lexicographical ordering for strings uses the Unicode
682codepoint number to order individual characters. Some examples of comparisons
683between sequences of the same type::
Georg Brandl116aa622007-08-15 14:28:22 +0000684
685 (1, 2, 3) < (1, 2, 4)
686 [1, 2, 3] < [1, 2, 4]
687 'ABC' < 'C' < 'Pascal' < 'Python'
688 (1, 2, 3, 4) < (1, 2, 4)
689 (1, 2) < (1, 2, -1)
690 (1, 2, 3) == (1.0, 2.0, 3.0)
691 (1, 2, ('aa', 'ab')) < (1, 2, ('abc', 'a'), 4)
692
Georg Brandl9f2c39a2007-10-08 14:08:36 +0000693Note that comparing objects of different types with ``<`` or ``>`` is legal
694provided that the objects have appropriate comparison methods. For example,
695mixed numeric types are compared according to their numeric value, so 0 equals
6960.0, etc. Otherwise, rather than providing an arbitrary ordering, the
697interpreter will raise a :exc:`TypeError` exception.
Georg Brandlfc11f272009-06-16 19:22:10 +0000698
699
700.. rubric:: Footnotes
701
Georg Brandl388349a2011-10-08 18:32:40 +0200702.. [1] Other languages may return the mutated object, which allows method
703 chaining, such as ``d->insert("a")->remove("b")->sort();``.
704
705.. [2] Calling ``d.keys()`` will return a :dfn:`dictionary view` object. It
Georg Brandlfc11f272009-06-16 19:22:10 +0000706 supports operations like membership test and iteration, but its contents
707 are not independent of the original dictionary -- it is only a *view*.