blob: 5c3ae1698012f7c7c63e38a1ad611bcf992c1c20 [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
R David Murray6bd68602014-09-30 21:25:38 -0400202Note that this creates (or overwrites) a variable named ``x`` that still exists
203after the loop completes. We can calculate the list of squares without any
204side effects using::
205
206 squares = list(map(lambda x: x**2, range(10)))
207
208or, equivalently::
Ezio Melotti91621e22011-12-13 15:36:19 +0200209
210 squares = [x**2 for x in range(10)]
211
R David Murray6bd68602014-09-30 21:25:38 -0400212which is more concise and readable.
Guido van Rossum0616b792007-08-31 03:25:11 +0000213
Georg Brandl7ae90dd2009-06-08 18:59:09 +0000214A list comprehension consists of brackets containing an expression followed
215by a :keyword:`for` clause, then zero or more :keyword:`for` or :keyword:`if`
Ezio Melotti91621e22011-12-13 15:36:19 +0200216clauses. The result will be a new list resulting from evaluating the expression
217in the context of the :keyword:`for` and :keyword:`if` clauses which follow it.
218For example, this listcomp combines the elements of two lists if they are not
219equal::
Guido van Rossum0616b792007-08-31 03:25:11 +0000220
Ezio Melotti91621e22011-12-13 15:36:19 +0200221 >>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
222 [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
Guido van Rossum0616b792007-08-31 03:25:11 +0000223
Ezio Melotti91621e22011-12-13 15:36:19 +0200224and it's equivalent to::
Guido van Rossum0616b792007-08-31 03:25:11 +0000225
Ezio Melotti91621e22011-12-13 15:36:19 +0200226 >>> combs = []
227 >>> for x in [1,2,3]:
228 ... for y in [3,1,4]:
229 ... if x != y:
230 ... combs.append((x, y))
231 ...
232 >>> combs
233 [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
Guido van Rossum0616b792007-08-31 03:25:11 +0000234
Ezio Melotti91621e22011-12-13 15:36:19 +0200235Note how the order of the :keyword:`for` and :keyword:`if` statements is the
236same in both these snippets.
Guido van Rossum0616b792007-08-31 03:25:11 +0000237
Ezio Melotti91621e22011-12-13 15:36:19 +0200238If the expression is a tuple (e.g. the ``(x, y)`` in the previous example),
239it must be parenthesized. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000240
Ezio Melotti91621e22011-12-13 15:36:19 +0200241 >>> vec = [-4, -2, 0, 2, 4]
242 >>> # create a new list with the values doubled
243 >>> [x*2 for x in vec]
244 [-8, -4, 0, 4, 8]
245 >>> # filter the list to exclude negative numbers
246 >>> [x for x in vec if x >= 0]
247 [0, 2, 4]
248 >>> # apply a function to all the elements
249 >>> [abs(x) for x in vec]
250 [4, 2, 0, 2, 4]
251 >>> # call a method on each element
Georg Brandl116aa622007-08-15 14:28:22 +0000252 >>> freshfruit = [' banana', ' loganberry ', 'passion fruit ']
253 >>> [weapon.strip() for weapon in freshfruit]
254 ['banana', 'loganberry', 'passion fruit']
Ezio Melotti91621e22011-12-13 15:36:19 +0200255 >>> # create a list of 2-tuples like (number, square)
256 >>> [(x, x**2) for x in range(6)]
257 [(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]
258 >>> # the tuple must be parenthesized, otherwise an error is raised
259 >>> [x, x**2 for x in range(6)]
Georg Brandl116aa622007-08-15 14:28:22 +0000260 File "<stdin>", line 1, in ?
Ezio Melotti91621e22011-12-13 15:36:19 +0200261 [x, x**2 for x in range(6)]
Georg Brandl116aa622007-08-15 14:28:22 +0000262 ^
263 SyntaxError: invalid syntax
Ezio Melotti91621e22011-12-13 15:36:19 +0200264 >>> # flatten a list using a listcomp with two 'for'
265 >>> vec = [[1,2,3], [4,5,6], [7,8,9]]
266 >>> [num for elem in vec for num in elem]
267 [1, 2, 3, 4, 5, 6, 7, 8, 9]
Guido van Rossum0616b792007-08-31 03:25:11 +0000268
Ezio Melotti91621e22011-12-13 15:36:19 +0200269List comprehensions can contain complex expressions and nested functions::
Guido van Rossum0616b792007-08-31 03:25:11 +0000270
Ezio Melotti91621e22011-12-13 15:36:19 +0200271 >>> from math import pi
272 >>> [str(round(pi, i)) for i in range(1, 6)]
Georg Brandl116aa622007-08-15 14:28:22 +0000273 ['3.1', '3.14', '3.142', '3.1416', '3.14159']
274
Christian Heimes0449f632007-12-15 01:27:15 +0000275Nested List Comprehensions
276--------------------------
277
Ezio Melotti91621e22011-12-13 15:36:19 +0200278The initial expression in a list comprehension can be any arbitrary expression,
279including another list comprehension.
Christian Heimes0449f632007-12-15 01:27:15 +0000280
Ezio Melotti91621e22011-12-13 15:36:19 +0200281Consider the following example of a 3x4 matrix implemented as a list of
2823 lists of length 4::
Christian Heimes0449f632007-12-15 01:27:15 +0000283
Ezio Melotti91621e22011-12-13 15:36:19 +0200284 >>> matrix = [
285 ... [1, 2, 3, 4],
286 ... [5, 6, 7, 8],
287 ... [9, 10, 11, 12],
288 ... ]
Christian Heimes0449f632007-12-15 01:27:15 +0000289
Ezio Melotti91621e22011-12-13 15:36:19 +0200290The following list comprehension will transpose rows and columns::
Christian Heimes0449f632007-12-15 01:27:15 +0000291
Ezio Melotti91621e22011-12-13 15:36:19 +0200292 >>> [[row[i] for row in matrix] for i in range(4)]
293 [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
Christian Heimes0449f632007-12-15 01:27:15 +0000294
Ezio Melotti91621e22011-12-13 15:36:19 +0200295As we saw in the previous section, the nested listcomp is evaluated in
296the context of the :keyword:`for` that follows it, so this example is
297equivalent to::
Christian Heimes0449f632007-12-15 01:27:15 +0000298
Ezio Melotti91621e22011-12-13 15:36:19 +0200299 >>> transposed = []
300 >>> for i in range(4):
301 ... transposed.append([row[i] for row in matrix])
302 ...
303 >>> transposed
304 [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
Christian Heimes0449f632007-12-15 01:27:15 +0000305
Ezio Melotti91621e22011-12-13 15:36:19 +0200306which, in turn, is the same as::
Christian Heimes0449f632007-12-15 01:27:15 +0000307
Ezio Melotti91621e22011-12-13 15:36:19 +0200308 >>> transposed = []
309 >>> for i in range(4):
310 ... # the following 3 lines implement the nested listcomp
311 ... transposed_row = []
312 ... for row in matrix:
313 ... transposed_row.append(row[i])
314 ... transposed.append(transposed_row)
315 ...
316 >>> transposed
317 [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
Christian Heimes0449f632007-12-15 01:27:15 +0000318
Ezio Melotti91621e22011-12-13 15:36:19 +0200319In the real world, you should prefer built-in functions to complex flow statements.
Christian Heimes0449f632007-12-15 01:27:15 +0000320The :func:`zip` function would do a great job for this use case::
321
Sandro Tosi0a90a822012-08-12 10:24:50 +0200322 >>> list(zip(*matrix))
Ezio Melotti91621e22011-12-13 15:36:19 +0200323 [(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]
Christian Heimes0449f632007-12-15 01:27:15 +0000324
325See :ref:`tut-unpacking-arguments` for details on the asterisk in this line.
326
Georg Brandl116aa622007-08-15 14:28:22 +0000327.. _tut-del:
328
329The :keyword:`del` statement
330============================
331
332There is a way to remove an item from a list given its index instead of its
333value: the :keyword:`del` statement. This differs from the :meth:`pop` method
334which returns a value. The :keyword:`del` statement can also be used to remove
335slices from a list or clear the entire list (which we did earlier by assignment
336of an empty list to the slice). For example::
337
338 >>> a = [-1, 1, 66.25, 333, 333, 1234.5]
339 >>> del a[0]
340 >>> a
341 [1, 66.25, 333, 333, 1234.5]
342 >>> del a[2:4]
343 >>> a
344 [1, 66.25, 1234.5]
345 >>> del a[:]
346 >>> a
347 []
348
349:keyword:`del` can also be used to delete entire variables::
350
351 >>> del a
352
353Referencing the name ``a`` hereafter is an error (at least until another value
354is assigned to it). We'll find other uses for :keyword:`del` later.
355
356
Georg Brandl5d955ed2008-09-13 17:18:21 +0000357.. _tut-tuples:
Georg Brandl116aa622007-08-15 14:28:22 +0000358
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000359Tuples and Sequences
360====================
361
362We saw that lists and strings have many common properties, such as indexing and
363slicing operations. They are two examples of *sequence* data types (see
364:ref:`typesseq`). Since Python is an evolving language, other sequence data
365types may be added. There is also another standard sequence data type: the
366*tuple*.
367
368A tuple consists of a number of values separated by commas, for instance::
369
370 >>> t = 12345, 54321, 'hello!'
371 >>> t[0]
372 12345
373 >>> t
374 (12345, 54321, 'hello!')
375 >>> # Tuples may be nested:
376 ... u = t, (1, 2, 3, 4, 5)
377 >>> u
378 ((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))
Ezio Melottif90ea1f2012-06-17 14:10:59 +0200379 >>> # Tuples are immutable:
380 ... t[0] = 88888
381 Traceback (most recent call last):
382 File "<stdin>", line 1, in <module>
383 TypeError: 'tuple' object does not support item assignment
384 >>> # but they can contain mutable objects:
385 ... v = ([1, 2, 3], [3, 2, 1])
386 >>> v
387 ([1, 2, 3], [3, 2, 1])
388
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000389
390As you see, on output tuples are always enclosed in parentheses, so that nested
391tuples are interpreted correctly; they may be input with or without surrounding
392parentheses, although often parentheses are necessary anyway (if the tuple is
Ezio Melottif90ea1f2012-06-17 14:10:59 +0200393part of a larger expression). It is not possible to assign to the individual
394items of a tuple, however it is possible to create tuples which contain mutable
395objects, such as lists.
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000396
Ezio Melottif90ea1f2012-06-17 14:10:59 +0200397Though tuples may seem similar to lists, they are often used in different
398situations and for different purposes.
399Tuples are :term:`immutable`, and usually contain an heterogeneous sequence of
400elements that are accessed via unpacking (see later in this section) or indexing
401(or even by attribute in the case of :func:`namedtuples <collections.namedtuple>`).
402Lists are :term:`mutable`, and their elements are usually homogeneous and are
403accessed by iterating over the list.
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000404
405A special problem is the construction of tuples containing 0 or 1 items: the
406syntax has some extra quirks to accommodate these. Empty tuples are constructed
407by an empty pair of parentheses; a tuple with one item is constructed by
408following a value with a comma (it is not sufficient to enclose a single value
409in parentheses). Ugly, but effective. For example::
410
411 >>> empty = ()
412 >>> singleton = 'hello', # <-- note trailing comma
413 >>> len(empty)
414 0
415 >>> len(singleton)
416 1
417 >>> singleton
418 ('hello',)
419
420The statement ``t = 12345, 54321, 'hello!'`` is an example of *tuple packing*:
421the values ``12345``, ``54321`` and ``'hello!'`` are packed together in a tuple.
422The reverse operation is also possible::
423
424 >>> x, y, z = t
425
Benjamin Petersond23f8222009-04-05 19:13:16 +0000426This is called, appropriately enough, *sequence unpacking* and works for any
Georg Brandl7ae90dd2009-06-08 18:59:09 +0000427sequence on the right-hand side. Sequence unpacking requires that there are as
428many variables on the left side of the equals sign as there are elements in the
Benjamin Petersond23f8222009-04-05 19:13:16 +0000429sequence. Note that multiple assignment is really just a combination of tuple
430packing and sequence unpacking.
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000431
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000432
Georg Brandl116aa622007-08-15 14:28:22 +0000433.. _tut-sets:
434
435Sets
436====
437
438Python also includes a data type for *sets*. A set is an unordered collection
439with no duplicate elements. Basic uses include membership testing and
440eliminating duplicate entries. Set objects also support mathematical operations
441like union, intersection, difference, and symmetric difference.
442
Ezio Melotti89b03b02012-11-17 12:06:01 +0200443Curly braces or the :func:`set` function can be used to create sets. Note: to
Georg Brandl10e0e302009-06-08 20:25:55 +0000444create an empty set you have to use ``set()``, not ``{}``; the latter creates an
445empty dictionary, a data structure that we discuss in the next section.
Guido van Rossum0616b792007-08-31 03:25:11 +0000446
Georg Brandl116aa622007-08-15 14:28:22 +0000447Here is a brief demonstration::
448
Raymond Hettingerafdeca92010-08-08 01:30:45 +0000449 >>> basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
450 >>> print(basket) # show that duplicates have been removed
Georg Brandl1790ed22010-11-10 07:57:10 +0000451 {'orange', 'banana', 'pear', 'apple'}
Raymond Hettingerafdeca92010-08-08 01:30:45 +0000452 >>> 'orange' in basket # fast membership testing
Georg Brandl116aa622007-08-15 14:28:22 +0000453 True
Raymond Hettingerafdeca92010-08-08 01:30:45 +0000454 >>> 'crabgrass' in basket
Georg Brandl116aa622007-08-15 14:28:22 +0000455 False
456
457 >>> # Demonstrate set operations on unique letters from two words
458 ...
459 >>> a = set('abracadabra')
460 >>> b = set('alacazam')
461 >>> a # unique letters in a
Guido van Rossum0616b792007-08-31 03:25:11 +0000462 {'a', 'r', 'b', 'c', 'd'}
Georg Brandl116aa622007-08-15 14:28:22 +0000463 >>> a - b # letters in a but not in b
Guido van Rossum0616b792007-08-31 03:25:11 +0000464 {'r', 'd', 'b'}
Georg Brandl116aa622007-08-15 14:28:22 +0000465 >>> a | b # letters in either a or b
Guido van Rossum0616b792007-08-31 03:25:11 +0000466 {'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}
Georg Brandl116aa622007-08-15 14:28:22 +0000467 >>> a & b # letters in both a and b
Guido van Rossum0616b792007-08-31 03:25:11 +0000468 {'a', 'c'}
Georg Brandl116aa622007-08-15 14:28:22 +0000469 >>> a ^ b # letters in a or b but not both
Guido van Rossum0616b792007-08-31 03:25:11 +0000470 {'r', 'd', 'b', 'm', 'z', 'l'}
471
Ezio Melotti89b03b02012-11-17 12:06:01 +0200472Similarly to :ref:`list comprehensions <tut-listcomps>`, set comprehensions
473are also supported::
Georg Brandlf6945182008-02-01 11:56:49 +0000474
475 >>> a = {x for x in 'abracadabra' if x not in 'abc'}
476 >>> a
477 {'r', 'd'}
Guido van Rossum0616b792007-08-31 03:25:11 +0000478
Georg Brandl116aa622007-08-15 14:28:22 +0000479
Georg Brandl116aa622007-08-15 14:28:22 +0000480.. _tut-dictionaries:
481
482Dictionaries
483============
484
485Another useful data type built into Python is the *dictionary* (see
486:ref:`typesmapping`). Dictionaries are sometimes found in other languages as
487"associative memories" or "associative arrays". Unlike sequences, which are
488indexed by a range of numbers, dictionaries are indexed by *keys*, which can be
489any immutable type; strings and numbers can always be keys. Tuples can be used
490as keys if they contain only strings, numbers, or tuples; if a tuple contains
491any mutable object either directly or indirectly, it cannot be used as a key.
492You can't use lists as keys, since lists can be modified in place using index
493assignments, slice assignments, or methods like :meth:`append` and
494:meth:`extend`.
495
496It is best to think of a dictionary as an unordered set of *key: value* pairs,
497with the requirement that the keys are unique (within one dictionary). A pair of
498braces creates an empty dictionary: ``{}``. Placing a comma-separated list of
499key:value pairs within the braces adds initial key:value pairs to the
500dictionary; this is also the way dictionaries are written on output.
501
502The main operations on a dictionary are storing a value with some key and
503extracting the value given the key. It is also possible to delete a key:value
504pair with ``del``. If you store using a key that is already in use, the old
505value associated with that key is forgotten. It is an error to extract a value
506using a non-existent key.
507
Georg Brandlabffe712008-12-15 08:28:37 +0000508Performing ``list(d.keys())`` on a dictionary returns a list of all the keys
Georg Brandlfc11f272009-06-16 19:22:10 +0000509used in the dictionary, in arbitrary order (if you want it sorted, just use
Georg Brandl388349a2011-10-08 18:32:40 +0200510``sorted(d.keys())`` instead). [2]_ To check whether a single key is in the
Georg Brandlfc11f272009-06-16 19:22:10 +0000511dictionary, use the :keyword:`in` keyword.
Georg Brandl116aa622007-08-15 14:28:22 +0000512
513Here is a small example using a dictionary::
514
515 >>> tel = {'jack': 4098, 'sape': 4139}
516 >>> tel['guido'] = 4127
517 >>> tel
518 {'sape': 4139, 'guido': 4127, 'jack': 4098}
519 >>> tel['jack']
520 4098
521 >>> del tel['sape']
522 >>> tel['irv'] = 4127
523 >>> tel
524 {'guido': 4127, 'irv': 4127, 'jack': 4098}
Neal Norwitze0906d12007-08-31 03:46:28 +0000525 >>> list(tel.keys())
Georg Brandlabffe712008-12-15 08:28:37 +0000526 ['irv', 'guido', 'jack']
527 >>> sorted(tel.keys())
Georg Brandl116aa622007-08-15 14:28:22 +0000528 ['guido', 'irv', 'jack']
Georg Brandl116aa622007-08-15 14:28:22 +0000529 >>> 'guido' in tel
530 True
Neal Norwitze0906d12007-08-31 03:46:28 +0000531 >>> 'jack' not in tel
532 False
Georg Brandl116aa622007-08-15 14:28:22 +0000533
Georg Brandlfc11f272009-06-16 19:22:10 +0000534The :func:`dict` constructor builds dictionaries directly from sequences of
Raymond Hettinger8699aea2009-06-16 20:49:30 +0000535key-value pairs::
Georg Brandl116aa622007-08-15 14:28:22 +0000536
537 >>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
538 {'sape': 4139, 'jack': 4098, 'guido': 4127}
Georg Brandl116aa622007-08-15 14:28:22 +0000539
Georg Brandlf6945182008-02-01 11:56:49 +0000540In addition, dict comprehensions can be used to create dictionaries from
541arbitrary key and value expressions::
542
543 >>> {x: x**2 for x in (2, 4, 6)}
544 {2: 4, 4: 16, 6: 36}
Georg Brandl116aa622007-08-15 14:28:22 +0000545
546When the keys are simple strings, it is sometimes easier to specify pairs using
547keyword arguments::
548
549 >>> dict(sape=4139, guido=4127, jack=4098)
550 {'sape': 4139, 'jack': 4098, 'guido': 4127}
551
552
553.. _tut-loopidioms:
554
555Looping Techniques
556==================
557
558When looping through dictionaries, the key and corresponding value can be
Neal Norwitze0906d12007-08-31 03:46:28 +0000559retrieved at the same time using the :meth:`items` method. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000560
561 >>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
Neal Norwitze0906d12007-08-31 03:46:28 +0000562 >>> for k, v in knights.items():
Guido van Rossum0616b792007-08-31 03:25:11 +0000563 ... print(k, v)
Georg Brandl116aa622007-08-15 14:28:22 +0000564 ...
565 gallahad the pure
566 robin the brave
567
568When looping through a sequence, the position index and corresponding value can
569be retrieved at the same time using the :func:`enumerate` function. ::
570
571 >>> for i, v in enumerate(['tic', 'tac', 'toe']):
Guido van Rossum0616b792007-08-31 03:25:11 +0000572 ... print(i, v)
Georg Brandl116aa622007-08-15 14:28:22 +0000573 ...
574 0 tic
575 1 tac
576 2 toe
577
578To loop over two or more sequences at the same time, the entries can be paired
579with the :func:`zip` function. ::
580
581 >>> questions = ['name', 'quest', 'favorite color']
582 >>> answers = ['lancelot', 'the holy grail', 'blue']
583 >>> for q, a in zip(questions, answers):
Benjamin Petersone6f00632008-05-26 01:03:56 +0000584 ... print('What is your {0}? It is {1}.'.format(q, a))
Georg Brandl06788c92009-01-03 21:31:47 +0000585 ...
Georg Brandl116aa622007-08-15 14:28:22 +0000586 What is your name? It is lancelot.
587 What is your quest? It is the holy grail.
588 What is your favorite color? It is blue.
589
590To loop over a sequence in reverse, first specify the sequence in a forward
591direction and then call the :func:`reversed` function. ::
592
Georg Brandle4ac7502007-09-03 07:10:24 +0000593 >>> for i in reversed(range(1, 10, 2)):
Guido van Rossum0616b792007-08-31 03:25:11 +0000594 ... print(i)
Georg Brandl116aa622007-08-15 14:28:22 +0000595 ...
596 9
597 7
598 5
599 3
600 1
601
602To loop over a sequence in sorted order, use the :func:`sorted` function which
603returns a new sorted list while leaving the source unaltered. ::
604
605 >>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
606 >>> for f in sorted(set(basket)):
Guido van Rossum0616b792007-08-31 03:25:11 +0000607 ... print(f)
Georg Brandl06788c92009-01-03 21:31:47 +0000608 ...
Georg Brandl116aa622007-08-15 14:28:22 +0000609 apple
610 banana
611 orange
612 pear
613
Chris Jerdonek4fab8f02012-10-15 19:44:47 -0700614To change a sequence you are iterating over while inside the loop (for
615example to duplicate certain items), it is recommended that you first make
616a copy. Looping over a sequence does not implicitly make a copy. The slice
617notation makes this especially convenient::
618
619 >>> words = ['cat', 'window', 'defenestrate']
620 >>> for w in words[:]: # Loop over a slice copy of the entire list.
621 ... if len(w) > 6:
622 ... words.insert(0, w)
623 ...
624 >>> words
625 ['defenestrate', 'cat', 'window', 'defenestrate']
626
Georg Brandl116aa622007-08-15 14:28:22 +0000627
628.. _tut-conditions:
629
630More on Conditions
631==================
632
633The conditions used in ``while`` and ``if`` statements can contain any
634operators, not just comparisons.
635
636The comparison operators ``in`` and ``not in`` check whether a value occurs
637(does not occur) in a sequence. The operators ``is`` and ``is not`` compare
638whether two objects are really the same object; this only matters for mutable
639objects like lists. All comparison operators have the same priority, which is
640lower than that of all numerical operators.
641
642Comparisons can be chained. For example, ``a < b == c`` tests whether ``a`` is
643less than ``b`` and moreover ``b`` equals ``c``.
644
645Comparisons may be combined using the Boolean operators ``and`` and ``or``, and
646the outcome of a comparison (or of any other Boolean expression) may be negated
647with ``not``. These have lower priorities than comparison operators; between
648them, ``not`` has the highest priority and ``or`` the lowest, so that ``A and
649not B or C`` is equivalent to ``(A and (not B)) or C``. As always, parentheses
650can be used to express the desired composition.
651
652The Boolean operators ``and`` and ``or`` are so-called *short-circuit*
653operators: their arguments are evaluated from left to right, and evaluation
654stops as soon as the outcome is determined. For example, if ``A`` and ``C`` are
655true but ``B`` is false, ``A and B and C`` does not evaluate the expression
656``C``. When used as a general value and not as a Boolean, the return value of a
657short-circuit operator is the last evaluated argument.
658
659It is possible to assign the result of a comparison or other Boolean expression
660to a variable. For example, ::
661
662 >>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance'
663 >>> non_null = string1 or string2 or string3
664 >>> non_null
665 'Trondheim'
666
667Note that in Python, unlike C, assignment cannot occur inside expressions. C
668programmers may grumble about this, but it avoids a common class of problems
669encountered in C programs: typing ``=`` in an expression when ``==`` was
670intended.
671
672
673.. _tut-comparing:
674
675Comparing Sequences and Other Types
676===================================
677
678Sequence objects may be compared to other objects with the same sequence type.
679The comparison uses *lexicographical* ordering: first the first two items are
680compared, and if they differ this determines the outcome of the comparison; if
681they are equal, the next two items are compared, and so on, until either
682sequence is exhausted. If two items to be compared are themselves sequences of
683the same type, the lexicographical comparison is carried out recursively. If
684all items of two sequences compare equal, the sequences are considered equal.
685If one sequence is an initial sub-sequence of the other, the shorter sequence is
Georg Brandlfc11f272009-06-16 19:22:10 +0000686the smaller (lesser) one. Lexicographical ordering for strings uses the Unicode
687codepoint number to order individual characters. Some examples of comparisons
688between sequences of the same type::
Georg Brandl116aa622007-08-15 14:28:22 +0000689
690 (1, 2, 3) < (1, 2, 4)
691 [1, 2, 3] < [1, 2, 4]
692 'ABC' < 'C' < 'Pascal' < 'Python'
693 (1, 2, 3, 4) < (1, 2, 4)
694 (1, 2) < (1, 2, -1)
695 (1, 2, 3) == (1.0, 2.0, 3.0)
696 (1, 2, ('aa', 'ab')) < (1, 2, ('abc', 'a'), 4)
697
Georg Brandl9f2c39a2007-10-08 14:08:36 +0000698Note that comparing objects of different types with ``<`` or ``>`` is legal
699provided that the objects have appropriate comparison methods. For example,
700mixed numeric types are compared according to their numeric value, so 0 equals
7010.0, etc. Otherwise, rather than providing an arbitrary ordering, the
702interpreter will raise a :exc:`TypeError` exception.
Georg Brandlfc11f272009-06-16 19:22:10 +0000703
704
705.. rubric:: Footnotes
706
Georg Brandl388349a2011-10-08 18:32:40 +0200707.. [1] Other languages may return the mutated object, which allows method
708 chaining, such as ``d->insert("a")->remove("b")->sort();``.
709
710.. [2] Calling ``d.keys()`` will return a :dfn:`dictionary view` object. It
Georg Brandlfc11f272009-06-16 19:22:10 +0000711 supports operations like membership test and iteration, but its contents
712 are not independent of the original dictionary -- it is only a *view*.