blob: 5e95afa6fc48ad82715c5b1f0d5ba35f59cdd28a [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
Raymond Hettinger07e04852014-05-26 18:44:04 -070076.. method:: list.sort(key=None, reverse=False)
Christian Heimes4fbc72b2008-03-22 00:47:35 +000077 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +000078
Raymond Hettinger07e04852014-05-26 18:44:04 -070079 Sort the items of the list in place (the arguments can be used for sort
80 customization, see :func:`sorted` for their explanation).
Georg Brandl116aa622007-08-15 14:28:22 +000081
82
83.. method:: list.reverse()
Christian Heimes4fbc72b2008-03-22 00:47:35 +000084 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +000085
Georg Brandl388349a2011-10-08 18:32:40 +020086 Reverse the elements of the list in place.
87
Georg Brandl116aa622007-08-15 14:28:22 +000088
Georg Brandla12b6822013-10-06 13:01:19 +020089.. method:: list.copy()
90 :noindex:
91
92 Return a shallow copy of the list. Equivalent to ``a[:]``.
93
94
Georg Brandl116aa622007-08-15 14:28:22 +000095An example that uses most of the list methods::
96
97 >>> a = [66.25, 333, 333, 1, 1234.5]
Guido van Rossum0616b792007-08-31 03:25:11 +000098 >>> print(a.count(333), a.count(66.25), a.count('x'))
Georg Brandl116aa622007-08-15 14:28:22 +000099 2 1 0
100 >>> a.insert(2, -1)
101 >>> a.append(333)
102 >>> a
103 [66.25, 333, -1, 333, 1, 1234.5, 333]
104 >>> a.index(333)
105 1
106 >>> a.remove(333)
107 >>> a
108 [66.25, -1, 333, 1, 1234.5, 333]
109 >>> a.reverse()
110 >>> a
111 [333, 1234.5, 1, 333, -1, 66.25]
112 >>> a.sort()
113 >>> a
114 [-1, 1, 66.25, 333, 333, 1234.5]
Terry Jan Reedye17de092014-05-23 00:34:12 -0400115 >>> a.pop()
116 1234.5
117 >>> a
118 [-1, 1, 66.25, 333, 333]
Georg Brandl116aa622007-08-15 14:28:22 +0000119
Georg Brandl388349a2011-10-08 18:32:40 +0200120You might have noticed that methods like ``insert``, ``remove`` or ``sort`` that
Terry Jan Reedye17de092014-05-23 00:34:12 -0400121only modify the list have no return value printed -- they return the default
122``None``. [1]_ This is a design principle for all mutable data structures in
123Python.
Georg Brandl388349a2011-10-08 18:32:40 +0200124
Georg Brandl116aa622007-08-15 14:28:22 +0000125
126.. _tut-lists-as-stacks:
127
128Using Lists as Stacks
129---------------------
130
131.. sectionauthor:: Ka-Ping Yee <ping@lfw.org>
132
133
134The list methods make it very easy to use a list as a stack, where the last
135element added is the first element retrieved ("last-in, first-out"). To add an
136item to the top of the stack, use :meth:`append`. To retrieve an item from the
137top of the stack, use :meth:`pop` without an explicit index. For example::
138
139 >>> stack = [3, 4, 5]
140 >>> stack.append(6)
141 >>> stack.append(7)
142 >>> stack
143 [3, 4, 5, 6, 7]
144 >>> stack.pop()
145 7
146 >>> stack
147 [3, 4, 5, 6]
148 >>> stack.pop()
149 6
150 >>> stack.pop()
151 5
152 >>> stack
153 [3, 4]
154
155
156.. _tut-lists-as-queues:
157
158Using Lists as Queues
159---------------------
160
161.. sectionauthor:: Ka-Ping Yee <ping@lfw.org>
162
Ezio Melotti8f8db142010-03-31 07:45:32 +0000163It is also possible to use a list as a queue, where the first element added is
164the first element retrieved ("first-in, first-out"); however, lists are not
165efficient for this purpose. While appends and pops from the end of list are
166fast, doing inserts or pops from the beginning of a list is slow (because all
167of the other elements have to be shifted by one).
Georg Brandl116aa622007-08-15 14:28:22 +0000168
Ezio Melotti8f8db142010-03-31 07:45:32 +0000169To implement a queue, use :class:`collections.deque` which was designed to
170have fast appends and pops from both ends. For example::
Georg Brandl116aa622007-08-15 14:28:22 +0000171
Ezio Melotti8f8db142010-03-31 07:45:32 +0000172 >>> from collections import deque
173 >>> queue = deque(["Eric", "John", "Michael"])
Georg Brandl116aa622007-08-15 14:28:22 +0000174 >>> queue.append("Terry") # Terry arrives
175 >>> queue.append("Graham") # Graham arrives
Ezio Melotti8f8db142010-03-31 07:45:32 +0000176 >>> queue.popleft() # The first to arrive now leaves
Georg Brandl116aa622007-08-15 14:28:22 +0000177 'Eric'
Ezio Melotti8f8db142010-03-31 07:45:32 +0000178 >>> queue.popleft() # The second to arrive now leaves
Georg Brandl116aa622007-08-15 14:28:22 +0000179 'John'
Ezio Melotti8f8db142010-03-31 07:45:32 +0000180 >>> queue # Remaining queue in order of arrival
181 deque(['Michael', 'Terry', 'Graham'])
Georg Brandl718ce2c2010-03-21 09:51:44 +0000182
Georg Brandl116aa622007-08-15 14:28:22 +0000183
Georg Brandlfc11f272009-06-16 19:22:10 +0000184.. _tut-listcomps:
185
Georg Brandl116aa622007-08-15 14:28:22 +0000186List Comprehensions
187-------------------
188
Ezio Melotti91621e22011-12-13 15:36:19 +0200189List comprehensions provide a concise way to create lists.
190Common applications are to make new lists where each element is the result of
191some operations applied to each member of another sequence or iterable, or to
192create a subsequence of those elements that satisfy a certain condition.
193
194For example, assume we want to create a list of squares, like::
195
196 >>> squares = []
197 >>> for x in range(10):
198 ... squares.append(x**2)
199 ...
200 >>> squares
201 [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
202
203We can obtain the same result with::
204
205 squares = [x**2 for x in range(10)]
206
Chris Jerdonekfd448da2012-09-28 07:07:12 -0700207This is also equivalent to ``squares = list(map(lambda x: x**2, range(10)))``,
Ezio Melotti91621e22011-12-13 15:36:19 +0200208but it's more concise and readable.
Guido van Rossum0616b792007-08-31 03:25:11 +0000209
Georg Brandl7ae90dd2009-06-08 18:59:09 +0000210A list comprehension consists of brackets containing an expression followed
211by a :keyword:`for` clause, then zero or more :keyword:`for` or :keyword:`if`
Ezio Melotti91621e22011-12-13 15:36:19 +0200212clauses. The result will be a new list resulting from evaluating the expression
213in the context of the :keyword:`for` and :keyword:`if` clauses which follow it.
214For example, this listcomp combines the elements of two lists if they are not
215equal::
Guido van Rossum0616b792007-08-31 03:25:11 +0000216
Ezio Melotti91621e22011-12-13 15:36:19 +0200217 >>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
218 [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
Guido van Rossum0616b792007-08-31 03:25:11 +0000219
Ezio Melotti91621e22011-12-13 15:36:19 +0200220and it's equivalent to::
Guido van Rossum0616b792007-08-31 03:25:11 +0000221
Ezio Melotti91621e22011-12-13 15:36:19 +0200222 >>> combs = []
223 >>> for x in [1,2,3]:
224 ... for y in [3,1,4]:
225 ... if x != y:
226 ... combs.append((x, y))
227 ...
228 >>> combs
229 [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
Guido van Rossum0616b792007-08-31 03:25:11 +0000230
Ezio Melotti91621e22011-12-13 15:36:19 +0200231Note how the order of the :keyword:`for` and :keyword:`if` statements is the
232same in both these snippets.
Guido van Rossum0616b792007-08-31 03:25:11 +0000233
Ezio Melotti91621e22011-12-13 15:36:19 +0200234If the expression is a tuple (e.g. the ``(x, y)`` in the previous example),
235it must be parenthesized. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000236
Ezio Melotti91621e22011-12-13 15:36:19 +0200237 >>> vec = [-4, -2, 0, 2, 4]
238 >>> # create a new list with the values doubled
239 >>> [x*2 for x in vec]
240 [-8, -4, 0, 4, 8]
241 >>> # filter the list to exclude negative numbers
242 >>> [x for x in vec if x >= 0]
243 [0, 2, 4]
244 >>> # apply a function to all the elements
245 >>> [abs(x) for x in vec]
246 [4, 2, 0, 2, 4]
247 >>> # call a method on each element
Georg Brandl116aa622007-08-15 14:28:22 +0000248 >>> freshfruit = [' banana', ' loganberry ', 'passion fruit ']
249 >>> [weapon.strip() for weapon in freshfruit]
250 ['banana', 'loganberry', 'passion fruit']
Ezio Melotti91621e22011-12-13 15:36:19 +0200251 >>> # create a list of 2-tuples like (number, square)
252 >>> [(x, x**2) for x in range(6)]
253 [(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]
254 >>> # the tuple must be parenthesized, otherwise an error is raised
255 >>> [x, x**2 for x in range(6)]
Georg Brandl116aa622007-08-15 14:28:22 +0000256 File "<stdin>", line 1, in ?
Ezio Melotti91621e22011-12-13 15:36:19 +0200257 [x, x**2 for x in range(6)]
Georg Brandl116aa622007-08-15 14:28:22 +0000258 ^
259 SyntaxError: invalid syntax
Ezio Melotti91621e22011-12-13 15:36:19 +0200260 >>> # flatten a list using a listcomp with two 'for'
261 >>> vec = [[1,2,3], [4,5,6], [7,8,9]]
262 >>> [num for elem in vec for num in elem]
263 [1, 2, 3, 4, 5, 6, 7, 8, 9]
Guido van Rossum0616b792007-08-31 03:25:11 +0000264
Ezio Melotti91621e22011-12-13 15:36:19 +0200265List comprehensions can contain complex expressions and nested functions::
Guido van Rossum0616b792007-08-31 03:25:11 +0000266
Ezio Melotti91621e22011-12-13 15:36:19 +0200267 >>> from math import pi
268 >>> [str(round(pi, i)) for i in range(1, 6)]
Georg Brandl116aa622007-08-15 14:28:22 +0000269 ['3.1', '3.14', '3.142', '3.1416', '3.14159']
270
Christian Heimes0449f632007-12-15 01:27:15 +0000271Nested List Comprehensions
272--------------------------
273
Ezio Melotti91621e22011-12-13 15:36:19 +0200274The initial expression in a list comprehension can be any arbitrary expression,
275including another list comprehension.
Christian Heimes0449f632007-12-15 01:27:15 +0000276
Ezio Melotti91621e22011-12-13 15:36:19 +0200277Consider the following example of a 3x4 matrix implemented as a list of
2783 lists of length 4::
Christian Heimes0449f632007-12-15 01:27:15 +0000279
Ezio Melotti91621e22011-12-13 15:36:19 +0200280 >>> matrix = [
281 ... [1, 2, 3, 4],
282 ... [5, 6, 7, 8],
283 ... [9, 10, 11, 12],
284 ... ]
Christian Heimes0449f632007-12-15 01:27:15 +0000285
Ezio Melotti91621e22011-12-13 15:36:19 +0200286The following list comprehension will transpose rows and columns::
Christian Heimes0449f632007-12-15 01:27:15 +0000287
Ezio Melotti91621e22011-12-13 15:36:19 +0200288 >>> [[row[i] for row in matrix] for i in range(4)]
289 [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
Christian Heimes0449f632007-12-15 01:27:15 +0000290
Ezio Melotti91621e22011-12-13 15:36:19 +0200291As we saw in the previous section, the nested listcomp is evaluated in
292the context of the :keyword:`for` that follows it, so this example is
293equivalent to::
Christian Heimes0449f632007-12-15 01:27:15 +0000294
Ezio Melotti91621e22011-12-13 15:36:19 +0200295 >>> transposed = []
296 >>> for i in range(4):
297 ... transposed.append([row[i] for row in matrix])
298 ...
299 >>> transposed
300 [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
Christian Heimes0449f632007-12-15 01:27:15 +0000301
Ezio Melotti91621e22011-12-13 15:36:19 +0200302which, in turn, is the same as::
Christian Heimes0449f632007-12-15 01:27:15 +0000303
Ezio Melotti91621e22011-12-13 15:36:19 +0200304 >>> transposed = []
305 >>> for i in range(4):
306 ... # the following 3 lines implement the nested listcomp
307 ... transposed_row = []
308 ... for row in matrix:
309 ... transposed_row.append(row[i])
310 ... transposed.append(transposed_row)
311 ...
312 >>> transposed
313 [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
Christian Heimes0449f632007-12-15 01:27:15 +0000314
Ezio Melotti91621e22011-12-13 15:36:19 +0200315In the real world, you should prefer built-in functions to complex flow statements.
Christian Heimes0449f632007-12-15 01:27:15 +0000316The :func:`zip` function would do a great job for this use case::
317
Sandro Tosi0a90a822012-08-12 10:24:50 +0200318 >>> list(zip(*matrix))
Ezio Melotti91621e22011-12-13 15:36:19 +0200319 [(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]
Christian Heimes0449f632007-12-15 01:27:15 +0000320
321See :ref:`tut-unpacking-arguments` for details on the asterisk in this line.
322
Georg Brandl116aa622007-08-15 14:28:22 +0000323.. _tut-del:
324
325The :keyword:`del` statement
326============================
327
328There is a way to remove an item from a list given its index instead of its
329value: the :keyword:`del` statement. This differs from the :meth:`pop` method
330which returns a value. The :keyword:`del` statement can also be used to remove
331slices from a list or clear the entire list (which we did earlier by assignment
332of an empty list to the slice). For example::
333
334 >>> a = [-1, 1, 66.25, 333, 333, 1234.5]
335 >>> del a[0]
336 >>> a
337 [1, 66.25, 333, 333, 1234.5]
338 >>> del a[2:4]
339 >>> a
340 [1, 66.25, 1234.5]
341 >>> del a[:]
342 >>> a
343 []
344
345:keyword:`del` can also be used to delete entire variables::
346
347 >>> del a
348
349Referencing the name ``a`` hereafter is an error (at least until another value
350is assigned to it). We'll find other uses for :keyword:`del` later.
351
352
Georg Brandl5d955ed2008-09-13 17:18:21 +0000353.. _tut-tuples:
Georg Brandl116aa622007-08-15 14:28:22 +0000354
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000355Tuples and Sequences
356====================
357
358We saw that lists and strings have many common properties, such as indexing and
359slicing operations. They are two examples of *sequence* data types (see
360:ref:`typesseq`). Since Python is an evolving language, other sequence data
361types may be added. There is also another standard sequence data type: the
362*tuple*.
363
364A tuple consists of a number of values separated by commas, for instance::
365
366 >>> t = 12345, 54321, 'hello!'
367 >>> t[0]
368 12345
369 >>> t
370 (12345, 54321, 'hello!')
371 >>> # Tuples may be nested:
372 ... u = t, (1, 2, 3, 4, 5)
373 >>> u
374 ((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))
Ezio Melottif90ea1f2012-06-17 14:10:59 +0200375 >>> # Tuples are immutable:
376 ... t[0] = 88888
377 Traceback (most recent call last):
378 File "<stdin>", line 1, in <module>
379 TypeError: 'tuple' object does not support item assignment
380 >>> # but they can contain mutable objects:
381 ... v = ([1, 2, 3], [3, 2, 1])
382 >>> v
383 ([1, 2, 3], [3, 2, 1])
384
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000385
386As you see, on output tuples are always enclosed in parentheses, so that nested
387tuples are interpreted correctly; they may be input with or without surrounding
388parentheses, although often parentheses are necessary anyway (if the tuple is
Ezio Melottif90ea1f2012-06-17 14:10:59 +0200389part of a larger expression). It is not possible to assign to the individual
390items of a tuple, however it is possible to create tuples which contain mutable
391objects, such as lists.
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000392
Ezio Melottif90ea1f2012-06-17 14:10:59 +0200393Though tuples may seem similar to lists, they are often used in different
394situations and for different purposes.
395Tuples are :term:`immutable`, and usually contain an heterogeneous sequence of
396elements that are accessed via unpacking (see later in this section) or indexing
397(or even by attribute in the case of :func:`namedtuples <collections.namedtuple>`).
398Lists are :term:`mutable`, and their elements are usually homogeneous and are
399accessed by iterating over the list.
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000400
401A special problem is the construction of tuples containing 0 or 1 items: the
402syntax has some extra quirks to accommodate these. Empty tuples are constructed
403by an empty pair of parentheses; a tuple with one item is constructed by
404following a value with a comma (it is not sufficient to enclose a single value
405in parentheses). Ugly, but effective. For example::
406
407 >>> empty = ()
408 >>> singleton = 'hello', # <-- note trailing comma
409 >>> len(empty)
410 0
411 >>> len(singleton)
412 1
413 >>> singleton
414 ('hello',)
415
416The statement ``t = 12345, 54321, 'hello!'`` is an example of *tuple packing*:
417the values ``12345``, ``54321`` and ``'hello!'`` are packed together in a tuple.
418The reverse operation is also possible::
419
420 >>> x, y, z = t
421
Benjamin Petersond23f8222009-04-05 19:13:16 +0000422This is called, appropriately enough, *sequence unpacking* and works for any
Georg Brandl7ae90dd2009-06-08 18:59:09 +0000423sequence on the right-hand side. Sequence unpacking requires that there are as
424many variables on the left side of the equals sign as there are elements in the
Benjamin Petersond23f8222009-04-05 19:13:16 +0000425sequence. Note that multiple assignment is really just a combination of tuple
426packing and sequence unpacking.
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000427
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000428
Georg Brandl116aa622007-08-15 14:28:22 +0000429.. _tut-sets:
430
431Sets
432====
433
434Python also includes a data type for *sets*. A set is an unordered collection
435with no duplicate elements. Basic uses include membership testing and
436eliminating duplicate entries. Set objects also support mathematical operations
437like union, intersection, difference, and symmetric difference.
438
Ezio Melotti89b03b02012-11-17 12:06:01 +0200439Curly braces or the :func:`set` function can be used to create sets. Note: to
Georg Brandl10e0e302009-06-08 20:25:55 +0000440create an empty set you have to use ``set()``, not ``{}``; the latter creates an
441empty dictionary, a data structure that we discuss in the next section.
Guido van Rossum0616b792007-08-31 03:25:11 +0000442
Georg Brandl116aa622007-08-15 14:28:22 +0000443Here is a brief demonstration::
444
Raymond Hettingerafdeca92010-08-08 01:30:45 +0000445 >>> basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
446 >>> print(basket) # show that duplicates have been removed
Georg Brandl1790ed22010-11-10 07:57:10 +0000447 {'orange', 'banana', 'pear', 'apple'}
Raymond Hettingerafdeca92010-08-08 01:30:45 +0000448 >>> 'orange' in basket # fast membership testing
Georg Brandl116aa622007-08-15 14:28:22 +0000449 True
Raymond Hettingerafdeca92010-08-08 01:30:45 +0000450 >>> 'crabgrass' in basket
Georg Brandl116aa622007-08-15 14:28:22 +0000451 False
452
453 >>> # Demonstrate set operations on unique letters from two words
454 ...
455 >>> a = set('abracadabra')
456 >>> b = set('alacazam')
457 >>> a # unique letters in a
Guido van Rossum0616b792007-08-31 03:25:11 +0000458 {'a', 'r', 'b', 'c', 'd'}
Georg Brandl116aa622007-08-15 14:28:22 +0000459 >>> a - b # letters in a but not in b
Guido van Rossum0616b792007-08-31 03:25:11 +0000460 {'r', 'd', 'b'}
Georg Brandl116aa622007-08-15 14:28:22 +0000461 >>> a | b # letters in either a or b
Guido van Rossum0616b792007-08-31 03:25:11 +0000462 {'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}
Georg Brandl116aa622007-08-15 14:28:22 +0000463 >>> a & b # letters in both a and b
Guido van Rossum0616b792007-08-31 03:25:11 +0000464 {'a', 'c'}
Georg Brandl116aa622007-08-15 14:28:22 +0000465 >>> a ^ b # letters in a or b but not both
Guido van Rossum0616b792007-08-31 03:25:11 +0000466 {'r', 'd', 'b', 'm', 'z', 'l'}
467
Ezio Melotti89b03b02012-11-17 12:06:01 +0200468Similarly to :ref:`list comprehensions <tut-listcomps>`, set comprehensions
469are also supported::
Georg Brandlf6945182008-02-01 11:56:49 +0000470
471 >>> a = {x for x in 'abracadabra' if x not in 'abc'}
472 >>> a
473 {'r', 'd'}
Guido van Rossum0616b792007-08-31 03:25:11 +0000474
Georg Brandl116aa622007-08-15 14:28:22 +0000475
Georg Brandl116aa622007-08-15 14:28:22 +0000476.. _tut-dictionaries:
477
478Dictionaries
479============
480
481Another useful data type built into Python is the *dictionary* (see
482:ref:`typesmapping`). Dictionaries are sometimes found in other languages as
483"associative memories" or "associative arrays". Unlike sequences, which are
484indexed by a range of numbers, dictionaries are indexed by *keys*, which can be
485any immutable type; strings and numbers can always be keys. Tuples can be used
486as keys if they contain only strings, numbers, or tuples; if a tuple contains
487any mutable object either directly or indirectly, it cannot be used as a key.
488You can't use lists as keys, since lists can be modified in place using index
489assignments, slice assignments, or methods like :meth:`append` and
490:meth:`extend`.
491
492It is best to think of a dictionary as an unordered set of *key: value* pairs,
493with the requirement that the keys are unique (within one dictionary). A pair of
494braces creates an empty dictionary: ``{}``. Placing a comma-separated list of
495key:value pairs within the braces adds initial key:value pairs to the
496dictionary; this is also the way dictionaries are written on output.
497
498The main operations on a dictionary are storing a value with some key and
499extracting the value given the key. It is also possible to delete a key:value
500pair with ``del``. If you store using a key that is already in use, the old
501value associated with that key is forgotten. It is an error to extract a value
502using a non-existent key.
503
Georg Brandlabffe712008-12-15 08:28:37 +0000504Performing ``list(d.keys())`` on a dictionary returns a list of all the keys
Georg Brandlfc11f272009-06-16 19:22:10 +0000505used in the dictionary, in arbitrary order (if you want it sorted, just use
Georg Brandl388349a2011-10-08 18:32:40 +0200506``sorted(d.keys())`` instead). [2]_ To check whether a single key is in the
Georg Brandlfc11f272009-06-16 19:22:10 +0000507dictionary, use the :keyword:`in` keyword.
Georg Brandl116aa622007-08-15 14:28:22 +0000508
509Here is a small example using a dictionary::
510
511 >>> tel = {'jack': 4098, 'sape': 4139}
512 >>> tel['guido'] = 4127
513 >>> tel
514 {'sape': 4139, 'guido': 4127, 'jack': 4098}
515 >>> tel['jack']
516 4098
517 >>> del tel['sape']
518 >>> tel['irv'] = 4127
519 >>> tel
520 {'guido': 4127, 'irv': 4127, 'jack': 4098}
Neal Norwitze0906d12007-08-31 03:46:28 +0000521 >>> list(tel.keys())
Georg Brandlabffe712008-12-15 08:28:37 +0000522 ['irv', 'guido', 'jack']
523 >>> sorted(tel.keys())
Georg Brandl116aa622007-08-15 14:28:22 +0000524 ['guido', 'irv', 'jack']
Georg Brandl116aa622007-08-15 14:28:22 +0000525 >>> 'guido' in tel
526 True
Neal Norwitze0906d12007-08-31 03:46:28 +0000527 >>> 'jack' not in tel
528 False
Georg Brandl116aa622007-08-15 14:28:22 +0000529
Georg Brandlfc11f272009-06-16 19:22:10 +0000530The :func:`dict` constructor builds dictionaries directly from sequences of
Raymond Hettinger8699aea2009-06-16 20:49:30 +0000531key-value pairs::
Georg Brandl116aa622007-08-15 14:28:22 +0000532
533 >>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
534 {'sape': 4139, 'jack': 4098, 'guido': 4127}
Georg Brandl116aa622007-08-15 14:28:22 +0000535
Georg Brandlf6945182008-02-01 11:56:49 +0000536In addition, dict comprehensions can be used to create dictionaries from
537arbitrary key and value expressions::
538
539 >>> {x: x**2 for x in (2, 4, 6)}
540 {2: 4, 4: 16, 6: 36}
Georg Brandl116aa622007-08-15 14:28:22 +0000541
542When the keys are simple strings, it is sometimes easier to specify pairs using
543keyword arguments::
544
545 >>> dict(sape=4139, guido=4127, jack=4098)
546 {'sape': 4139, 'jack': 4098, 'guido': 4127}
547
548
549.. _tut-loopidioms:
550
551Looping Techniques
552==================
553
554When looping through dictionaries, the key and corresponding value can be
Neal Norwitze0906d12007-08-31 03:46:28 +0000555retrieved at the same time using the :meth:`items` method. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000556
557 >>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
Neal Norwitze0906d12007-08-31 03:46:28 +0000558 >>> for k, v in knights.items():
Guido van Rossum0616b792007-08-31 03:25:11 +0000559 ... print(k, v)
Georg Brandl116aa622007-08-15 14:28:22 +0000560 ...
561 gallahad the pure
562 robin the brave
563
564When looping through a sequence, the position index and corresponding value can
565be retrieved at the same time using the :func:`enumerate` function. ::
566
567 >>> for i, v in enumerate(['tic', 'tac', 'toe']):
Guido van Rossum0616b792007-08-31 03:25:11 +0000568 ... print(i, v)
Georg Brandl116aa622007-08-15 14:28:22 +0000569 ...
570 0 tic
571 1 tac
572 2 toe
573
574To loop over two or more sequences at the same time, the entries can be paired
575with the :func:`zip` function. ::
576
577 >>> questions = ['name', 'quest', 'favorite color']
578 >>> answers = ['lancelot', 'the holy grail', 'blue']
579 >>> for q, a in zip(questions, answers):
Benjamin Petersone6f00632008-05-26 01:03:56 +0000580 ... print('What is your {0}? It is {1}.'.format(q, a))
Georg Brandl06788c92009-01-03 21:31:47 +0000581 ...
Georg Brandl116aa622007-08-15 14:28:22 +0000582 What is your name? It is lancelot.
583 What is your quest? It is the holy grail.
584 What is your favorite color? It is blue.
585
586To loop over a sequence in reverse, first specify the sequence in a forward
587direction and then call the :func:`reversed` function. ::
588
Georg Brandle4ac7502007-09-03 07:10:24 +0000589 >>> for i in reversed(range(1, 10, 2)):
Guido van Rossum0616b792007-08-31 03:25:11 +0000590 ... print(i)
Georg Brandl116aa622007-08-15 14:28:22 +0000591 ...
592 9
593 7
594 5
595 3
596 1
597
598To loop over a sequence in sorted order, use the :func:`sorted` function which
599returns a new sorted list while leaving the source unaltered. ::
600
601 >>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
602 >>> for f in sorted(set(basket)):
Guido van Rossum0616b792007-08-31 03:25:11 +0000603 ... print(f)
Georg Brandl06788c92009-01-03 21:31:47 +0000604 ...
Georg Brandl116aa622007-08-15 14:28:22 +0000605 apple
606 banana
607 orange
608 pear
609
Chris Jerdonek4fab8f02012-10-15 19:44:47 -0700610To change a sequence you are iterating over while inside the loop (for
611example to duplicate certain items), it is recommended that you first make
612a copy. Looping over a sequence does not implicitly make a copy. The slice
613notation makes this especially convenient::
614
615 >>> words = ['cat', 'window', 'defenestrate']
616 >>> for w in words[:]: # Loop over a slice copy of the entire list.
617 ... if len(w) > 6:
618 ... words.insert(0, w)
619 ...
620 >>> words
621 ['defenestrate', 'cat', 'window', 'defenestrate']
622
Georg Brandl116aa622007-08-15 14:28:22 +0000623
624.. _tut-conditions:
625
626More on Conditions
627==================
628
629The conditions used in ``while`` and ``if`` statements can contain any
630operators, not just comparisons.
631
632The comparison operators ``in`` and ``not in`` check whether a value occurs
633(does not occur) in a sequence. The operators ``is`` and ``is not`` compare
634whether two objects are really the same object; this only matters for mutable
635objects like lists. All comparison operators have the same priority, which is
636lower than that of all numerical operators.
637
638Comparisons can be chained. For example, ``a < b == c`` tests whether ``a`` is
639less than ``b`` and moreover ``b`` equals ``c``.
640
641Comparisons may be combined using the Boolean operators ``and`` and ``or``, and
642the outcome of a comparison (or of any other Boolean expression) may be negated
643with ``not``. These have lower priorities than comparison operators; between
644them, ``not`` has the highest priority and ``or`` the lowest, so that ``A and
645not B or C`` is equivalent to ``(A and (not B)) or C``. As always, parentheses
646can be used to express the desired composition.
647
648The Boolean operators ``and`` and ``or`` are so-called *short-circuit*
649operators: their arguments are evaluated from left to right, and evaluation
650stops as soon as the outcome is determined. For example, if ``A`` and ``C`` are
651true but ``B`` is false, ``A and B and C`` does not evaluate the expression
652``C``. When used as a general value and not as a Boolean, the return value of a
653short-circuit operator is the last evaluated argument.
654
655It is possible to assign the result of a comparison or other Boolean expression
656to a variable. For example, ::
657
658 >>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance'
659 >>> non_null = string1 or string2 or string3
660 >>> non_null
661 'Trondheim'
662
663Note that in Python, unlike C, assignment cannot occur inside expressions. C
664programmers may grumble about this, but it avoids a common class of problems
665encountered in C programs: typing ``=`` in an expression when ``==`` was
666intended.
667
668
669.. _tut-comparing:
670
671Comparing Sequences and Other Types
672===================================
673
674Sequence objects may be compared to other objects with the same sequence type.
675The comparison uses *lexicographical* ordering: first the first two items are
676compared, and if they differ this determines the outcome of the comparison; if
677they are equal, the next two items are compared, and so on, until either
678sequence is exhausted. If two items to be compared are themselves sequences of
679the same type, the lexicographical comparison is carried out recursively. If
680all items of two sequences compare equal, the sequences are considered equal.
681If one sequence is an initial sub-sequence of the other, the shorter sequence is
Georg Brandlfc11f272009-06-16 19:22:10 +0000682the smaller (lesser) one. Lexicographical ordering for strings uses the Unicode
683codepoint number to order individual characters. Some examples of comparisons
684between sequences of the same type::
Georg Brandl116aa622007-08-15 14:28:22 +0000685
686 (1, 2, 3) < (1, 2, 4)
687 [1, 2, 3] < [1, 2, 4]
688 'ABC' < 'C' < 'Pascal' < 'Python'
689 (1, 2, 3, 4) < (1, 2, 4)
690 (1, 2) < (1, 2, -1)
691 (1, 2, 3) == (1.0, 2.0, 3.0)
692 (1, 2, ('aa', 'ab')) < (1, 2, ('abc', 'a'), 4)
693
Georg Brandl9f2c39a2007-10-08 14:08:36 +0000694Note that comparing objects of different types with ``<`` or ``>`` is legal
695provided that the objects have appropriate comparison methods. For example,
696mixed numeric types are compared according to their numeric value, so 0 equals
6970.0, etc. Otherwise, rather than providing an arbitrary ordering, the
698interpreter will raise a :exc:`TypeError` exception.
Georg Brandlfc11f272009-06-16 19:22:10 +0000699
700
701.. rubric:: Footnotes
702
Georg Brandl388349a2011-10-08 18:32:40 +0200703.. [1] Other languages may return the mutated object, which allows method
704 chaining, such as ``d->insert("a")->remove("b")->sort();``.
705
706.. [2] Calling ``d.keys()`` will return a :dfn:`dictionary view` object. It
Georg Brandlfc11f272009-06-16 19:22:10 +0000707 supports operations like membership test and iteration, but its contents
708 are not independent of the original dictionary -- it is only a *view*.