blob: 0d51480177d882f9519a0d578c324fdd72fe0921 [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
R David Murray6bd68602014-09-30 21:25:38 -0400203Note that this creates (or overwrites) a variable named ``x`` that still exists
204after the loop completes. We can calculate the list of squares without any
205side effects using::
206
207 squares = list(map(lambda x: x**2, range(10)))
208
209or, equivalently::
Ezio Melotti91621e22011-12-13 15:36:19 +0200210
211 squares = [x**2 for x in range(10)]
212
R David Murray6bd68602014-09-30 21:25:38 -0400213which is more concise and readable.
Guido van Rossum0616b792007-08-31 03:25:11 +0000214
Georg Brandl7ae90dd2009-06-08 18:59:09 +0000215A list comprehension consists of brackets containing an expression followed
216by a :keyword:`for` clause, then zero or more :keyword:`for` or :keyword:`if`
Ezio Melotti91621e22011-12-13 15:36:19 +0200217clauses. The result will be a new list resulting from evaluating the expression
218in the context of the :keyword:`for` and :keyword:`if` clauses which follow it.
219For example, this listcomp combines the elements of two lists if they are not
220equal::
Guido van Rossum0616b792007-08-31 03:25:11 +0000221
Ezio Melotti91621e22011-12-13 15:36:19 +0200222 >>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
223 [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
Guido van Rossum0616b792007-08-31 03:25:11 +0000224
Ezio Melotti91621e22011-12-13 15:36:19 +0200225and it's equivalent to::
Guido van Rossum0616b792007-08-31 03:25:11 +0000226
Ezio Melotti91621e22011-12-13 15:36:19 +0200227 >>> combs = []
228 >>> for x in [1,2,3]:
229 ... for y in [3,1,4]:
230 ... if x != y:
231 ... combs.append((x, y))
232 ...
233 >>> combs
234 [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
Guido van Rossum0616b792007-08-31 03:25:11 +0000235
Ezio Melotti91621e22011-12-13 15:36:19 +0200236Note how the order of the :keyword:`for` and :keyword:`if` statements is the
237same in both these snippets.
Guido van Rossum0616b792007-08-31 03:25:11 +0000238
Ezio Melotti91621e22011-12-13 15:36:19 +0200239If the expression is a tuple (e.g. the ``(x, y)`` in the previous example),
240it must be parenthesized. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000241
Ezio Melotti91621e22011-12-13 15:36:19 +0200242 >>> vec = [-4, -2, 0, 2, 4]
243 >>> # create a new list with the values doubled
244 >>> [x*2 for x in vec]
245 [-8, -4, 0, 4, 8]
246 >>> # filter the list to exclude negative numbers
247 >>> [x for x in vec if x >= 0]
248 [0, 2, 4]
249 >>> # apply a function to all the elements
250 >>> [abs(x) for x in vec]
251 [4, 2, 0, 2, 4]
252 >>> # call a method on each element
Georg Brandl116aa622007-08-15 14:28:22 +0000253 >>> freshfruit = [' banana', ' loganberry ', 'passion fruit ']
254 >>> [weapon.strip() for weapon in freshfruit]
255 ['banana', 'loganberry', 'passion fruit']
Ezio Melotti91621e22011-12-13 15:36:19 +0200256 >>> # create a list of 2-tuples like (number, square)
257 >>> [(x, x**2) for x in range(6)]
258 [(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]
259 >>> # the tuple must be parenthesized, otherwise an error is raised
260 >>> [x, x**2 for x in range(6)]
Georg Brandl116aa622007-08-15 14:28:22 +0000261 File "<stdin>", line 1, in ?
Ezio Melotti91621e22011-12-13 15:36:19 +0200262 [x, x**2 for x in range(6)]
Georg Brandl116aa622007-08-15 14:28:22 +0000263 ^
264 SyntaxError: invalid syntax
Ezio Melotti91621e22011-12-13 15:36:19 +0200265 >>> # flatten a list using a listcomp with two 'for'
266 >>> vec = [[1,2,3], [4,5,6], [7,8,9]]
267 >>> [num for elem in vec for num in elem]
268 [1, 2, 3, 4, 5, 6, 7, 8, 9]
Guido van Rossum0616b792007-08-31 03:25:11 +0000269
Ezio Melotti91621e22011-12-13 15:36:19 +0200270List comprehensions can contain complex expressions and nested functions::
Guido van Rossum0616b792007-08-31 03:25:11 +0000271
Ezio Melotti91621e22011-12-13 15:36:19 +0200272 >>> from math import pi
273 >>> [str(round(pi, i)) for i in range(1, 6)]
Georg Brandl116aa622007-08-15 14:28:22 +0000274 ['3.1', '3.14', '3.142', '3.1416', '3.14159']
275
Christian Heimes0449f632007-12-15 01:27:15 +0000276Nested List Comprehensions
277--------------------------
278
Ezio Melotti91621e22011-12-13 15:36:19 +0200279The initial expression in a list comprehension can be any arbitrary expression,
280including another list comprehension.
Christian Heimes0449f632007-12-15 01:27:15 +0000281
Ezio Melotti91621e22011-12-13 15:36:19 +0200282Consider the following example of a 3x4 matrix implemented as a list of
2833 lists of length 4::
Christian Heimes0449f632007-12-15 01:27:15 +0000284
Ezio Melotti91621e22011-12-13 15:36:19 +0200285 >>> matrix = [
286 ... [1, 2, 3, 4],
287 ... [5, 6, 7, 8],
288 ... [9, 10, 11, 12],
289 ... ]
Christian Heimes0449f632007-12-15 01:27:15 +0000290
Ezio Melotti91621e22011-12-13 15:36:19 +0200291The following list comprehension will transpose rows and columns::
Christian Heimes0449f632007-12-15 01:27:15 +0000292
Ezio Melotti91621e22011-12-13 15:36:19 +0200293 >>> [[row[i] for row in matrix] for i in range(4)]
294 [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
Christian Heimes0449f632007-12-15 01:27:15 +0000295
Ezio Melotti91621e22011-12-13 15:36:19 +0200296As we saw in the previous section, the nested listcomp is evaluated in
297the context of the :keyword:`for` that follows it, so this example is
298equivalent to::
Christian Heimes0449f632007-12-15 01:27:15 +0000299
Ezio Melotti91621e22011-12-13 15:36:19 +0200300 >>> transposed = []
301 >>> for i in range(4):
302 ... transposed.append([row[i] for row in matrix])
303 ...
304 >>> transposed
305 [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
Christian Heimes0449f632007-12-15 01:27:15 +0000306
Ezio Melotti91621e22011-12-13 15:36:19 +0200307which, in turn, is the same as::
Christian Heimes0449f632007-12-15 01:27:15 +0000308
Ezio Melotti91621e22011-12-13 15:36:19 +0200309 >>> transposed = []
310 >>> for i in range(4):
311 ... # the following 3 lines implement the nested listcomp
312 ... transposed_row = []
313 ... for row in matrix:
314 ... transposed_row.append(row[i])
315 ... transposed.append(transposed_row)
316 ...
317 >>> transposed
318 [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
Christian Heimes0449f632007-12-15 01:27:15 +0000319
Ezio Melotti91621e22011-12-13 15:36:19 +0200320In the real world, you should prefer built-in functions to complex flow statements.
Christian Heimes0449f632007-12-15 01:27:15 +0000321The :func:`zip` function would do a great job for this use case::
322
Sandro Tosi0a90a822012-08-12 10:24:50 +0200323 >>> list(zip(*matrix))
Ezio Melotti91621e22011-12-13 15:36:19 +0200324 [(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]
Christian Heimes0449f632007-12-15 01:27:15 +0000325
326See :ref:`tut-unpacking-arguments` for details on the asterisk in this line.
327
Georg Brandl116aa622007-08-15 14:28:22 +0000328.. _tut-del:
329
330The :keyword:`del` statement
331============================
332
333There is a way to remove an item from a list given its index instead of its
334value: the :keyword:`del` statement. This differs from the :meth:`pop` method
335which returns a value. The :keyword:`del` statement can also be used to remove
336slices from a list or clear the entire list (which we did earlier by assignment
337of an empty list to the slice). For example::
338
339 >>> a = [-1, 1, 66.25, 333, 333, 1234.5]
340 >>> del a[0]
341 >>> a
342 [1, 66.25, 333, 333, 1234.5]
343 >>> del a[2:4]
344 >>> a
345 [1, 66.25, 1234.5]
346 >>> del a[:]
347 >>> a
348 []
349
350:keyword:`del` can also be used to delete entire variables::
351
352 >>> del a
353
354Referencing the name ``a`` hereafter is an error (at least until another value
355is assigned to it). We'll find other uses for :keyword:`del` later.
356
357
Georg Brandl5d955ed2008-09-13 17:18:21 +0000358.. _tut-tuples:
Georg Brandl116aa622007-08-15 14:28:22 +0000359
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000360Tuples and Sequences
361====================
362
363We saw that lists and strings have many common properties, such as indexing and
364slicing operations. They are two examples of *sequence* data types (see
365:ref:`typesseq`). Since Python is an evolving language, other sequence data
366types may be added. There is also another standard sequence data type: the
367*tuple*.
368
369A tuple consists of a number of values separated by commas, for instance::
370
371 >>> t = 12345, 54321, 'hello!'
372 >>> t[0]
373 12345
374 >>> t
375 (12345, 54321, 'hello!')
376 >>> # Tuples may be nested:
377 ... u = t, (1, 2, 3, 4, 5)
378 >>> u
379 ((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))
Ezio Melottif90ea1f2012-06-17 14:10:59 +0200380 >>> # Tuples are immutable:
381 ... t[0] = 88888
382 Traceback (most recent call last):
383 File "<stdin>", line 1, in <module>
384 TypeError: 'tuple' object does not support item assignment
385 >>> # but they can contain mutable objects:
386 ... v = ([1, 2, 3], [3, 2, 1])
387 >>> v
388 ([1, 2, 3], [3, 2, 1])
389
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000390
391As you see, on output tuples are always enclosed in parentheses, so that nested
392tuples are interpreted correctly; they may be input with or without surrounding
393parentheses, although often parentheses are necessary anyway (if the tuple is
Ezio Melottif90ea1f2012-06-17 14:10:59 +0200394part of a larger expression). It is not possible to assign to the individual
395items of a tuple, however it is possible to create tuples which contain mutable
396objects, such as lists.
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000397
Ezio Melottif90ea1f2012-06-17 14:10:59 +0200398Though tuples may seem similar to lists, they are often used in different
399situations and for different purposes.
400Tuples are :term:`immutable`, and usually contain an heterogeneous sequence of
401elements that are accessed via unpacking (see later in this section) or indexing
402(or even by attribute in the case of :func:`namedtuples <collections.namedtuple>`).
403Lists are :term:`mutable`, and their elements are usually homogeneous and are
404accessed by iterating over the list.
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000405
406A special problem is the construction of tuples containing 0 or 1 items: the
407syntax has some extra quirks to accommodate these. Empty tuples are constructed
408by an empty pair of parentheses; a tuple with one item is constructed by
409following a value with a comma (it is not sufficient to enclose a single value
410in parentheses). Ugly, but effective. For example::
411
412 >>> empty = ()
413 >>> singleton = 'hello', # <-- note trailing comma
414 >>> len(empty)
415 0
416 >>> len(singleton)
417 1
418 >>> singleton
419 ('hello',)
420
421The statement ``t = 12345, 54321, 'hello!'`` is an example of *tuple packing*:
422the values ``12345``, ``54321`` and ``'hello!'`` are packed together in a tuple.
423The reverse operation is also possible::
424
425 >>> x, y, z = t
426
Benjamin Petersond23f8222009-04-05 19:13:16 +0000427This is called, appropriately enough, *sequence unpacking* and works for any
Georg Brandl7ae90dd2009-06-08 18:59:09 +0000428sequence on the right-hand side. Sequence unpacking requires that there are as
429many variables on the left side of the equals sign as there are elements in the
Benjamin Petersond23f8222009-04-05 19:13:16 +0000430sequence. Note that multiple assignment is really just a combination of tuple
431packing and sequence unpacking.
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000432
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000433
Georg Brandl116aa622007-08-15 14:28:22 +0000434.. _tut-sets:
435
436Sets
437====
438
439Python also includes a data type for *sets*. A set is an unordered collection
440with no duplicate elements. Basic uses include membership testing and
441eliminating duplicate entries. Set objects also support mathematical operations
442like union, intersection, difference, and symmetric difference.
443
Ezio Melotti89b03b02012-11-17 12:06:01 +0200444Curly braces or the :func:`set` function can be used to create sets. Note: to
Georg Brandl10e0e302009-06-08 20:25:55 +0000445create an empty set you have to use ``set()``, not ``{}``; the latter creates an
446empty dictionary, a data structure that we discuss in the next section.
Guido van Rossum0616b792007-08-31 03:25:11 +0000447
Georg Brandl116aa622007-08-15 14:28:22 +0000448Here is a brief demonstration::
449
Raymond Hettingerafdeca92010-08-08 01:30:45 +0000450 >>> basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
451 >>> print(basket) # show that duplicates have been removed
Georg Brandl1790ed22010-11-10 07:57:10 +0000452 {'orange', 'banana', 'pear', 'apple'}
Raymond Hettingerafdeca92010-08-08 01:30:45 +0000453 >>> 'orange' in basket # fast membership testing
Georg Brandl116aa622007-08-15 14:28:22 +0000454 True
Raymond Hettingerafdeca92010-08-08 01:30:45 +0000455 >>> 'crabgrass' in basket
Georg Brandl116aa622007-08-15 14:28:22 +0000456 False
457
458 >>> # Demonstrate set operations on unique letters from two words
459 ...
460 >>> a = set('abracadabra')
461 >>> b = set('alacazam')
462 >>> a # unique letters in a
Guido van Rossum0616b792007-08-31 03:25:11 +0000463 {'a', 'r', 'b', 'c', 'd'}
Georg Brandl116aa622007-08-15 14:28:22 +0000464 >>> a - b # letters in a but not in b
Guido van Rossum0616b792007-08-31 03:25:11 +0000465 {'r', 'd', 'b'}
Georg Brandl116aa622007-08-15 14:28:22 +0000466 >>> a | b # letters in either a or b
Guido van Rossum0616b792007-08-31 03:25:11 +0000467 {'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}
Georg Brandl116aa622007-08-15 14:28:22 +0000468 >>> a & b # letters in both a and b
Guido van Rossum0616b792007-08-31 03:25:11 +0000469 {'a', 'c'}
Georg Brandl116aa622007-08-15 14:28:22 +0000470 >>> a ^ b # letters in a or b but not both
Guido van Rossum0616b792007-08-31 03:25:11 +0000471 {'r', 'd', 'b', 'm', 'z', 'l'}
472
Ezio Melotti89b03b02012-11-17 12:06:01 +0200473Similarly to :ref:`list comprehensions <tut-listcomps>`, set comprehensions
474are also supported::
Georg Brandlf6945182008-02-01 11:56:49 +0000475
476 >>> a = {x for x in 'abracadabra' if x not in 'abc'}
477 >>> a
478 {'r', 'd'}
Guido van Rossum0616b792007-08-31 03:25:11 +0000479
Georg Brandl116aa622007-08-15 14:28:22 +0000480
Georg Brandl116aa622007-08-15 14:28:22 +0000481.. _tut-dictionaries:
482
483Dictionaries
484============
485
486Another useful data type built into Python is the *dictionary* (see
487:ref:`typesmapping`). Dictionaries are sometimes found in other languages as
488"associative memories" or "associative arrays". Unlike sequences, which are
489indexed by a range of numbers, dictionaries are indexed by *keys*, which can be
490any immutable type; strings and numbers can always be keys. Tuples can be used
491as keys if they contain only strings, numbers, or tuples; if a tuple contains
492any mutable object either directly or indirectly, it cannot be used as a key.
493You can't use lists as keys, since lists can be modified in place using index
494assignments, slice assignments, or methods like :meth:`append` and
495:meth:`extend`.
496
497It is best to think of a dictionary as an unordered set of *key: value* pairs,
498with the requirement that the keys are unique (within one dictionary). A pair of
499braces creates an empty dictionary: ``{}``. Placing a comma-separated list of
500key:value pairs within the braces adds initial key:value pairs to the
501dictionary; this is also the way dictionaries are written on output.
502
503The main operations on a dictionary are storing a value with some key and
504extracting the value given the key. It is also possible to delete a key:value
505pair with ``del``. If you store using a key that is already in use, the old
506value associated with that key is forgotten. It is an error to extract a value
507using a non-existent key.
508
Georg Brandlabffe712008-12-15 08:28:37 +0000509Performing ``list(d.keys())`` on a dictionary returns a list of all the keys
Georg Brandlfc11f272009-06-16 19:22:10 +0000510used in the dictionary, in arbitrary order (if you want it sorted, just use
Georg Brandl388349a2011-10-08 18:32:40 +0200511``sorted(d.keys())`` instead). [2]_ To check whether a single key is in the
Georg Brandlfc11f272009-06-16 19:22:10 +0000512dictionary, use the :keyword:`in` keyword.
Georg Brandl116aa622007-08-15 14:28:22 +0000513
514Here is a small example using a dictionary::
515
516 >>> tel = {'jack': 4098, 'sape': 4139}
517 >>> tel['guido'] = 4127
518 >>> tel
519 {'sape': 4139, 'guido': 4127, 'jack': 4098}
520 >>> tel['jack']
521 4098
522 >>> del tel['sape']
523 >>> tel['irv'] = 4127
524 >>> tel
525 {'guido': 4127, 'irv': 4127, 'jack': 4098}
Neal Norwitze0906d12007-08-31 03:46:28 +0000526 >>> list(tel.keys())
Georg Brandlabffe712008-12-15 08:28:37 +0000527 ['irv', 'guido', 'jack']
528 >>> sorted(tel.keys())
Georg Brandl116aa622007-08-15 14:28:22 +0000529 ['guido', 'irv', 'jack']
Georg Brandl116aa622007-08-15 14:28:22 +0000530 >>> 'guido' in tel
531 True
Neal Norwitze0906d12007-08-31 03:46:28 +0000532 >>> 'jack' not in tel
533 False
Georg Brandl116aa622007-08-15 14:28:22 +0000534
Georg Brandlfc11f272009-06-16 19:22:10 +0000535The :func:`dict` constructor builds dictionaries directly from sequences of
Raymond Hettinger8699aea2009-06-16 20:49:30 +0000536key-value pairs::
Georg Brandl116aa622007-08-15 14:28:22 +0000537
538 >>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
539 {'sape': 4139, 'jack': 4098, 'guido': 4127}
Georg Brandl116aa622007-08-15 14:28:22 +0000540
Georg Brandlf6945182008-02-01 11:56:49 +0000541In addition, dict comprehensions can be used to create dictionaries from
542arbitrary key and value expressions::
543
544 >>> {x: x**2 for x in (2, 4, 6)}
545 {2: 4, 4: 16, 6: 36}
Georg Brandl116aa622007-08-15 14:28:22 +0000546
547When the keys are simple strings, it is sometimes easier to specify pairs using
548keyword arguments::
549
550 >>> dict(sape=4139, guido=4127, jack=4098)
551 {'sape': 4139, 'jack': 4098, 'guido': 4127}
552
553
554.. _tut-loopidioms:
555
556Looping Techniques
557==================
558
559When looping through dictionaries, the key and corresponding value can be
Neal Norwitze0906d12007-08-31 03:46:28 +0000560retrieved at the same time using the :meth:`items` method. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000561
562 >>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
Neal Norwitze0906d12007-08-31 03:46:28 +0000563 >>> for k, v in knights.items():
Guido van Rossum0616b792007-08-31 03:25:11 +0000564 ... print(k, v)
Georg Brandl116aa622007-08-15 14:28:22 +0000565 ...
566 gallahad the pure
567 robin the brave
568
569When looping through a sequence, the position index and corresponding value can
570be retrieved at the same time using the :func:`enumerate` function. ::
571
572 >>> for i, v in enumerate(['tic', 'tac', 'toe']):
Guido van Rossum0616b792007-08-31 03:25:11 +0000573 ... print(i, v)
Georg Brandl116aa622007-08-15 14:28:22 +0000574 ...
575 0 tic
576 1 tac
577 2 toe
578
579To loop over two or more sequences at the same time, the entries can be paired
580with the :func:`zip` function. ::
581
582 >>> questions = ['name', 'quest', 'favorite color']
583 >>> answers = ['lancelot', 'the holy grail', 'blue']
584 >>> for q, a in zip(questions, answers):
Benjamin Petersone6f00632008-05-26 01:03:56 +0000585 ... print('What is your {0}? It is {1}.'.format(q, a))
Georg Brandl06788c92009-01-03 21:31:47 +0000586 ...
Georg Brandl116aa622007-08-15 14:28:22 +0000587 What is your name? It is lancelot.
588 What is your quest? It is the holy grail.
589 What is your favorite color? It is blue.
590
591To loop over a sequence in reverse, first specify the sequence in a forward
592direction and then call the :func:`reversed` function. ::
593
Georg Brandle4ac7502007-09-03 07:10:24 +0000594 >>> for i in reversed(range(1, 10, 2)):
Guido van Rossum0616b792007-08-31 03:25:11 +0000595 ... print(i)
Georg Brandl116aa622007-08-15 14:28:22 +0000596 ...
597 9
598 7
599 5
600 3
601 1
602
603To loop over a sequence in sorted order, use the :func:`sorted` function which
604returns a new sorted list while leaving the source unaltered. ::
605
606 >>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
607 >>> for f in sorted(set(basket)):
Guido van Rossum0616b792007-08-31 03:25:11 +0000608 ... print(f)
Georg Brandl06788c92009-01-03 21:31:47 +0000609 ...
Georg Brandl116aa622007-08-15 14:28:22 +0000610 apple
611 banana
612 orange
613 pear
614
Raymond Hettinger502bf512015-09-01 02:33:02 -0700615It is sometimes tempting to change a list while you are looping over it;
616however, it is often simpler and safer to create a new list instead. ::
Chris Jerdonek4fab8f02012-10-15 19:44:47 -0700617
Raymond Hettinger502bf512015-09-01 02:33:02 -0700618 >>> import math
619 >>> raw_data = [56.2, float('NaN'), 51.7, 55.3, 52.5, float('NaN'), 47.8]
620 >>> filtered_data = []
621 >>> for value in raw_data:
622 ... if not math.isnan(value):
623 ... filtered_data.append(value)
Chris Jerdonek4fab8f02012-10-15 19:44:47 -0700624 ...
Raymond Hettinger502bf512015-09-01 02:33:02 -0700625 >>> filtered_data
626 [56.2, 51.7, 55.3, 52.5, 47.8]
Chris Jerdonek4fab8f02012-10-15 19:44:47 -0700627
Georg Brandl116aa622007-08-15 14:28:22 +0000628
629.. _tut-conditions:
630
631More on Conditions
632==================
633
634The conditions used in ``while`` and ``if`` statements can contain any
635operators, not just comparisons.
636
637The comparison operators ``in`` and ``not in`` check whether a value occurs
638(does not occur) in a sequence. The operators ``is`` and ``is not`` compare
639whether two objects are really the same object; this only matters for mutable
640objects like lists. All comparison operators have the same priority, which is
641lower than that of all numerical operators.
642
643Comparisons can be chained. For example, ``a < b == c`` tests whether ``a`` is
644less than ``b`` and moreover ``b`` equals ``c``.
645
646Comparisons may be combined using the Boolean operators ``and`` and ``or``, and
647the outcome of a comparison (or of any other Boolean expression) may be negated
648with ``not``. These have lower priorities than comparison operators; between
649them, ``not`` has the highest priority and ``or`` the lowest, so that ``A and
650not B or C`` is equivalent to ``(A and (not B)) or C``. As always, parentheses
651can be used to express the desired composition.
652
653The Boolean operators ``and`` and ``or`` are so-called *short-circuit*
654operators: their arguments are evaluated from left to right, and evaluation
655stops as soon as the outcome is determined. For example, if ``A`` and ``C`` are
656true but ``B`` is false, ``A and B and C`` does not evaluate the expression
657``C``. When used as a general value and not as a Boolean, the return value of a
658short-circuit operator is the last evaluated argument.
659
660It is possible to assign the result of a comparison or other Boolean expression
661to a variable. For example, ::
662
663 >>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance'
664 >>> non_null = string1 or string2 or string3
665 >>> non_null
666 'Trondheim'
667
668Note that in Python, unlike C, assignment cannot occur inside expressions. C
669programmers may grumble about this, but it avoids a common class of problems
670encountered in C programs: typing ``=`` in an expression when ``==`` was
671intended.
672
673
674.. _tut-comparing:
675
676Comparing Sequences and Other Types
677===================================
678
679Sequence objects may be compared to other objects with the same sequence type.
680The comparison uses *lexicographical* ordering: first the first two items are
681compared, and if they differ this determines the outcome of the comparison; if
682they are equal, the next two items are compared, and so on, until either
683sequence is exhausted. If two items to be compared are themselves sequences of
684the same type, the lexicographical comparison is carried out recursively. If
685all items of two sequences compare equal, the sequences are considered equal.
686If one sequence is an initial sub-sequence of the other, the shorter sequence is
Georg Brandlfc11f272009-06-16 19:22:10 +0000687the smaller (lesser) one. Lexicographical ordering for strings uses the Unicode
Georg Brandl3be472b2015-01-14 08:26:30 +0100688code point number to order individual characters. Some examples of comparisons
Georg Brandlfc11f272009-06-16 19:22:10 +0000689between sequences of the same type::
Georg Brandl116aa622007-08-15 14:28:22 +0000690
691 (1, 2, 3) < (1, 2, 4)
692 [1, 2, 3] < [1, 2, 4]
693 'ABC' < 'C' < 'Pascal' < 'Python'
694 (1, 2, 3, 4) < (1, 2, 4)
695 (1, 2) < (1, 2, -1)
696 (1, 2, 3) == (1.0, 2.0, 3.0)
697 (1, 2, ('aa', 'ab')) < (1, 2, ('abc', 'a'), 4)
698
Georg Brandl9f2c39a2007-10-08 14:08:36 +0000699Note that comparing objects of different types with ``<`` or ``>`` is legal
700provided that the objects have appropriate comparison methods. For example,
701mixed numeric types are compared according to their numeric value, so 0 equals
7020.0, etc. Otherwise, rather than providing an arbitrary ordering, the
703interpreter will raise a :exc:`TypeError` exception.
Georg Brandlfc11f272009-06-16 19:22:10 +0000704
705
706.. rubric:: Footnotes
707
Georg Brandl388349a2011-10-08 18:32:40 +0200708.. [1] Other languages may return the mutated object, which allows method
709 chaining, such as ``d->insert("a")->remove("b")->sort();``.
710
711.. [2] Calling ``d.keys()`` will return a :dfn:`dictionary view` object. It
Georg Brandlfc11f272009-06-16 19:22:10 +0000712 supports operations like membership test and iteration, but its contents
713 are not independent of the original dictionary -- it is only a *view*.