blob: 83b30120ff920f7b7eecab92e999bd58048b9fa0 [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
57.. method:: list.index(x)
Christian Heimes4fbc72b2008-03-22 00:47:35 +000058 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +000059
60 Return the index in the list of the first item whose value is *x*. It is an
61 error if there is no such item.
62
63
64.. method:: list.count(x)
Christian Heimes4fbc72b2008-03-22 00:47:35 +000065 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +000066
67 Return the number of times *x* appears in the list.
68
69
70.. method:: list.sort()
Christian Heimes4fbc72b2008-03-22 00:47:35 +000071 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +000072
Georg Brandl388349a2011-10-08 18:32:40 +020073 Sort the items of the list in place.
Georg Brandl116aa622007-08-15 14:28:22 +000074
75
76.. method:: list.reverse()
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 Reverse the elements of the list in place.
80
Georg Brandl116aa622007-08-15 14:28:22 +000081
82An example that uses most of the list methods::
83
84 >>> a = [66.25, 333, 333, 1, 1234.5]
Guido van Rossum0616b792007-08-31 03:25:11 +000085 >>> print(a.count(333), a.count(66.25), a.count('x'))
Georg Brandl116aa622007-08-15 14:28:22 +000086 2 1 0
87 >>> a.insert(2, -1)
88 >>> a.append(333)
89 >>> a
90 [66.25, 333, -1, 333, 1, 1234.5, 333]
91 >>> a.index(333)
92 1
93 >>> a.remove(333)
94 >>> a
95 [66.25, -1, 333, 1, 1234.5, 333]
96 >>> a.reverse()
97 >>> a
98 [333, 1234.5, 1, 333, -1, 66.25]
99 >>> a.sort()
100 >>> a
101 [-1, 1, 66.25, 333, 333, 1234.5]
102
Georg Brandl388349a2011-10-08 18:32:40 +0200103You might have noticed that methods like ``insert``, ``remove`` or ``sort`` that
104modify the list have no return value printed -- they return ``None``. [1]_ This
105is a design principle for all mutable data structures in Python.
106
Georg Brandl116aa622007-08-15 14:28:22 +0000107
108.. _tut-lists-as-stacks:
109
110Using Lists as Stacks
111---------------------
112
113.. sectionauthor:: Ka-Ping Yee <ping@lfw.org>
114
115
116The list methods make it very easy to use a list as a stack, where the last
117element added is the first element retrieved ("last-in, first-out"). To add an
118item to the top of the stack, use :meth:`append`. To retrieve an item from the
119top of the stack, use :meth:`pop` without an explicit index. For example::
120
121 >>> stack = [3, 4, 5]
122 >>> stack.append(6)
123 >>> stack.append(7)
124 >>> stack
125 [3, 4, 5, 6, 7]
126 >>> stack.pop()
127 7
128 >>> stack
129 [3, 4, 5, 6]
130 >>> stack.pop()
131 6
132 >>> stack.pop()
133 5
134 >>> stack
135 [3, 4]
136
137
138.. _tut-lists-as-queues:
139
140Using Lists as Queues
141---------------------
142
143.. sectionauthor:: Ka-Ping Yee <ping@lfw.org>
144
Ezio Melotti8f8db142010-03-31 07:45:32 +0000145It is also possible to use a list as a queue, where the first element added is
146the first element retrieved ("first-in, first-out"); however, lists are not
147efficient for this purpose. While appends and pops from the end of list are
148fast, doing inserts or pops from the beginning of a list is slow (because all
149of the other elements have to be shifted by one).
Georg Brandl116aa622007-08-15 14:28:22 +0000150
Ezio Melotti8f8db142010-03-31 07:45:32 +0000151To implement a queue, use :class:`collections.deque` which was designed to
152have fast appends and pops from both ends. For example::
Georg Brandl116aa622007-08-15 14:28:22 +0000153
Ezio Melotti8f8db142010-03-31 07:45:32 +0000154 >>> from collections import deque
155 >>> queue = deque(["Eric", "John", "Michael"])
Georg Brandl116aa622007-08-15 14:28:22 +0000156 >>> queue.append("Terry") # Terry arrives
157 >>> queue.append("Graham") # Graham arrives
Ezio Melotti8f8db142010-03-31 07:45:32 +0000158 >>> queue.popleft() # The first to arrive now leaves
Georg Brandl116aa622007-08-15 14:28:22 +0000159 'Eric'
Ezio Melotti8f8db142010-03-31 07:45:32 +0000160 >>> queue.popleft() # The second to arrive now leaves
Georg Brandl116aa622007-08-15 14:28:22 +0000161 'John'
Ezio Melotti8f8db142010-03-31 07:45:32 +0000162 >>> queue # Remaining queue in order of arrival
163 deque(['Michael', 'Terry', 'Graham'])
Georg Brandl718ce2c2010-03-21 09:51:44 +0000164
Georg Brandl116aa622007-08-15 14:28:22 +0000165
Georg Brandlfc11f272009-06-16 19:22:10 +0000166.. _tut-listcomps:
167
Georg Brandl116aa622007-08-15 14:28:22 +0000168List Comprehensions
169-------------------
170
Ezio Melotti91621e22011-12-13 15:36:19 +0200171List comprehensions provide a concise way to create lists.
172Common applications are to make new lists where each element is the result of
173some operations applied to each member of another sequence or iterable, or to
174create a subsequence of those elements that satisfy a certain condition.
175
176For example, assume we want to create a list of squares, like::
177
178 >>> squares = []
179 >>> for x in range(10):
180 ... squares.append(x**2)
181 ...
182 >>> squares
183 [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
184
185We can obtain the same result with::
186
187 squares = [x**2 for x in range(10)]
188
189This is also equivalent to ``squares = map(lambda x: x**2, range(10))``,
190but it's more concise and readable.
Guido van Rossum0616b792007-08-31 03:25:11 +0000191
Georg Brandl7ae90dd2009-06-08 18:59:09 +0000192A list comprehension consists of brackets containing an expression followed
193by a :keyword:`for` clause, then zero or more :keyword:`for` or :keyword:`if`
Ezio Melotti91621e22011-12-13 15:36:19 +0200194clauses. The result will be a new list resulting from evaluating the expression
195in the context of the :keyword:`for` and :keyword:`if` clauses which follow it.
196For example, this listcomp combines the elements of two lists if they are not
197equal::
Guido van Rossum0616b792007-08-31 03:25:11 +0000198
Ezio Melotti91621e22011-12-13 15:36:19 +0200199 >>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
200 [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
Guido van Rossum0616b792007-08-31 03:25:11 +0000201
Ezio Melotti91621e22011-12-13 15:36:19 +0200202and it's equivalent to::
Guido van Rossum0616b792007-08-31 03:25:11 +0000203
Ezio Melotti91621e22011-12-13 15:36:19 +0200204 >>> combs = []
205 >>> for x in [1,2,3]:
206 ... for y in [3,1,4]:
207 ... if x != y:
208 ... combs.append((x, y))
209 ...
210 >>> combs
211 [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
Guido van Rossum0616b792007-08-31 03:25:11 +0000212
Ezio Melotti91621e22011-12-13 15:36:19 +0200213Note how the order of the :keyword:`for` and :keyword:`if` statements is the
214same in both these snippets.
Guido van Rossum0616b792007-08-31 03:25:11 +0000215
Ezio Melotti91621e22011-12-13 15:36:19 +0200216If the expression is a tuple (e.g. the ``(x, y)`` in the previous example),
217it must be parenthesized. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000218
Ezio Melotti91621e22011-12-13 15:36:19 +0200219 >>> vec = [-4, -2, 0, 2, 4]
220 >>> # create a new list with the values doubled
221 >>> [x*2 for x in vec]
222 [-8, -4, 0, 4, 8]
223 >>> # filter the list to exclude negative numbers
224 >>> [x for x in vec if x >= 0]
225 [0, 2, 4]
226 >>> # apply a function to all the elements
227 >>> [abs(x) for x in vec]
228 [4, 2, 0, 2, 4]
229 >>> # call a method on each element
Georg Brandl116aa622007-08-15 14:28:22 +0000230 >>> freshfruit = [' banana', ' loganberry ', 'passion fruit ']
231 >>> [weapon.strip() for weapon in freshfruit]
232 ['banana', 'loganberry', 'passion fruit']
Ezio Melotti91621e22011-12-13 15:36:19 +0200233 >>> # create a list of 2-tuples like (number, square)
234 >>> [(x, x**2) for x in range(6)]
235 [(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]
236 >>> # the tuple must be parenthesized, otherwise an error is raised
237 >>> [x, x**2 for x in range(6)]
Georg Brandl116aa622007-08-15 14:28:22 +0000238 File "<stdin>", line 1, in ?
Ezio Melotti91621e22011-12-13 15:36:19 +0200239 [x, x**2 for x in range(6)]
Georg Brandl116aa622007-08-15 14:28:22 +0000240 ^
241 SyntaxError: invalid syntax
Ezio Melotti91621e22011-12-13 15:36:19 +0200242 >>> # flatten a list using a listcomp with two 'for'
243 >>> vec = [[1,2,3], [4,5,6], [7,8,9]]
244 >>> [num for elem in vec for num in elem]
245 [1, 2, 3, 4, 5, 6, 7, 8, 9]
Guido van Rossum0616b792007-08-31 03:25:11 +0000246
Ezio Melotti91621e22011-12-13 15:36:19 +0200247List comprehensions can contain complex expressions and nested functions::
Guido van Rossum0616b792007-08-31 03:25:11 +0000248
Ezio Melotti91621e22011-12-13 15:36:19 +0200249 >>> from math import pi
250 >>> [str(round(pi, i)) for i in range(1, 6)]
Georg Brandl116aa622007-08-15 14:28:22 +0000251 ['3.1', '3.14', '3.142', '3.1416', '3.14159']
252
Christian Heimes0449f632007-12-15 01:27:15 +0000253Nested List Comprehensions
254--------------------------
255
Ezio Melotti91621e22011-12-13 15:36:19 +0200256The initial expression in a list comprehension can be any arbitrary expression,
257including another list comprehension.
Christian Heimes0449f632007-12-15 01:27:15 +0000258
Ezio Melotti91621e22011-12-13 15:36:19 +0200259Consider the following example of a 3x4 matrix implemented as a list of
2603 lists of length 4::
Christian Heimes0449f632007-12-15 01:27:15 +0000261
Ezio Melotti91621e22011-12-13 15:36:19 +0200262 >>> matrix = [
263 ... [1, 2, 3, 4],
264 ... [5, 6, 7, 8],
265 ... [9, 10, 11, 12],
266 ... ]
Christian Heimes0449f632007-12-15 01:27:15 +0000267
Ezio Melotti91621e22011-12-13 15:36:19 +0200268The following list comprehension will transpose rows and columns::
Christian Heimes0449f632007-12-15 01:27:15 +0000269
Ezio Melotti91621e22011-12-13 15:36:19 +0200270 >>> [[row[i] for row in matrix] for i in range(4)]
271 [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
Christian Heimes0449f632007-12-15 01:27:15 +0000272
Ezio Melotti91621e22011-12-13 15:36:19 +0200273As we saw in the previous section, the nested listcomp is evaluated in
274the context of the :keyword:`for` that follows it, so this example is
275equivalent to::
Christian Heimes0449f632007-12-15 01:27:15 +0000276
Ezio Melotti91621e22011-12-13 15:36:19 +0200277 >>> transposed = []
278 >>> for i in range(4):
279 ... transposed.append([row[i] for row in matrix])
280 ...
281 >>> transposed
282 [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
Christian Heimes0449f632007-12-15 01:27:15 +0000283
Ezio Melotti91621e22011-12-13 15:36:19 +0200284which, in turn, is the same as::
Christian Heimes0449f632007-12-15 01:27:15 +0000285
Ezio Melotti91621e22011-12-13 15:36:19 +0200286 >>> transposed = []
287 >>> for i in range(4):
288 ... # the following 3 lines implement the nested listcomp
289 ... transposed_row = []
290 ... for row in matrix:
291 ... transposed_row.append(row[i])
292 ... transposed.append(transposed_row)
293 ...
294 >>> transposed
295 [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
Christian Heimes0449f632007-12-15 01:27:15 +0000296
Ezio Melotti91621e22011-12-13 15:36:19 +0200297In the real world, you should prefer built-in functions to complex flow statements.
Christian Heimes0449f632007-12-15 01:27:15 +0000298The :func:`zip` function would do a great job for this use case::
299
Ezio Melotti91621e22011-12-13 15:36:19 +0200300 >>> zip(*matrix)
301 [(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]
Christian Heimes0449f632007-12-15 01:27:15 +0000302
303See :ref:`tut-unpacking-arguments` for details on the asterisk in this line.
304
Georg Brandl116aa622007-08-15 14:28:22 +0000305.. _tut-del:
306
307The :keyword:`del` statement
308============================
309
310There is a way to remove an item from a list given its index instead of its
311value: the :keyword:`del` statement. This differs from the :meth:`pop` method
312which returns a value. The :keyword:`del` statement can also be used to remove
313slices from a list or clear the entire list (which we did earlier by assignment
314of an empty list to the slice). For example::
315
316 >>> a = [-1, 1, 66.25, 333, 333, 1234.5]
317 >>> del a[0]
318 >>> a
319 [1, 66.25, 333, 333, 1234.5]
320 >>> del a[2:4]
321 >>> a
322 [1, 66.25, 1234.5]
323 >>> del a[:]
324 >>> a
325 []
326
327:keyword:`del` can also be used to delete entire variables::
328
329 >>> del a
330
331Referencing the name ``a`` hereafter is an error (at least until another value
332is assigned to it). We'll find other uses for :keyword:`del` later.
333
334
Georg Brandl5d955ed2008-09-13 17:18:21 +0000335.. _tut-tuples:
Georg Brandl116aa622007-08-15 14:28:22 +0000336
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000337Tuples and Sequences
338====================
339
340We saw that lists and strings have many common properties, such as indexing and
341slicing operations. They are two examples of *sequence* data types (see
342:ref:`typesseq`). Since Python is an evolving language, other sequence data
343types may be added. There is also another standard sequence data type: the
344*tuple*.
345
346A tuple consists of a number of values separated by commas, for instance::
347
348 >>> t = 12345, 54321, 'hello!'
349 >>> t[0]
350 12345
351 >>> t
352 (12345, 54321, 'hello!')
353 >>> # Tuples may be nested:
354 ... u = t, (1, 2, 3, 4, 5)
355 >>> u
356 ((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))
357
358As you see, on output tuples are always enclosed in parentheses, so that nested
359tuples are interpreted correctly; they may be input with or without surrounding
360parentheses, although often parentheses are necessary anyway (if the tuple is
361part of a larger expression).
362
363Tuples have many uses. For example: (x, y) coordinate pairs, employee records
364from a database, etc. Tuples, like strings, are immutable: it is not possible
365to assign to the individual items of a tuple (you can simulate much of the same
366effect with slicing and concatenation, though). It is also possible to create
367tuples which contain mutable objects, such as lists.
368
369A special problem is the construction of tuples containing 0 or 1 items: the
370syntax has some extra quirks to accommodate these. Empty tuples are constructed
371by an empty pair of parentheses; a tuple with one item is constructed by
372following a value with a comma (it is not sufficient to enclose a single value
373in parentheses). Ugly, but effective. For example::
374
375 >>> empty = ()
376 >>> singleton = 'hello', # <-- note trailing comma
377 >>> len(empty)
378 0
379 >>> len(singleton)
380 1
381 >>> singleton
382 ('hello',)
383
384The statement ``t = 12345, 54321, 'hello!'`` is an example of *tuple packing*:
385the values ``12345``, ``54321`` and ``'hello!'`` are packed together in a tuple.
386The reverse operation is also possible::
387
388 >>> x, y, z = t
389
Benjamin Petersond23f8222009-04-05 19:13:16 +0000390This is called, appropriately enough, *sequence unpacking* and works for any
Georg Brandl7ae90dd2009-06-08 18:59:09 +0000391sequence on the right-hand side. Sequence unpacking requires that there are as
392many variables on the left side of the equals sign as there are elements in the
Benjamin Petersond23f8222009-04-05 19:13:16 +0000393sequence. Note that multiple assignment is really just a combination of tuple
394packing and sequence unpacking.
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000395
396.. XXX Add a bit on the difference between tuples and lists.
397
398
Georg Brandl116aa622007-08-15 14:28:22 +0000399.. _tut-sets:
400
401Sets
402====
403
404Python also includes a data type for *sets*. A set is an unordered collection
405with no duplicate elements. Basic uses include membership testing and
406eliminating duplicate entries. Set objects also support mathematical operations
407like union, intersection, difference, and symmetric difference.
408
Georg Brandl448f20b2010-09-20 06:27:02 +0000409Curly braces or the :func:`set` function can be used to create sets. Note: To
Georg Brandl10e0e302009-06-08 20:25:55 +0000410create an empty set you have to use ``set()``, not ``{}``; the latter creates an
411empty dictionary, a data structure that we discuss in the next section.
Guido van Rossum0616b792007-08-31 03:25:11 +0000412
Georg Brandl116aa622007-08-15 14:28:22 +0000413Here is a brief demonstration::
414
Raymond Hettingerafdeca92010-08-08 01:30:45 +0000415 >>> basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
416 >>> print(basket) # show that duplicates have been removed
Georg Brandl1790ed22010-11-10 07:57:10 +0000417 {'orange', 'banana', 'pear', 'apple'}
Raymond Hettingerafdeca92010-08-08 01:30:45 +0000418 >>> 'orange' in basket # fast membership testing
Georg Brandl116aa622007-08-15 14:28:22 +0000419 True
Raymond Hettingerafdeca92010-08-08 01:30:45 +0000420 >>> 'crabgrass' in basket
Georg Brandl116aa622007-08-15 14:28:22 +0000421 False
422
423 >>> # Demonstrate set operations on unique letters from two words
424 ...
425 >>> a = set('abracadabra')
426 >>> b = set('alacazam')
427 >>> a # unique letters in a
Guido van Rossum0616b792007-08-31 03:25:11 +0000428 {'a', 'r', 'b', 'c', 'd'}
Georg Brandl116aa622007-08-15 14:28:22 +0000429 >>> a - b # letters in a but not in b
Guido van Rossum0616b792007-08-31 03:25:11 +0000430 {'r', 'd', 'b'}
Georg Brandl116aa622007-08-15 14:28:22 +0000431 >>> a | b # letters in either a or b
Guido van Rossum0616b792007-08-31 03:25:11 +0000432 {'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}
Georg Brandl116aa622007-08-15 14:28:22 +0000433 >>> a & b # letters in both a and b
Guido van Rossum0616b792007-08-31 03:25:11 +0000434 {'a', 'c'}
Georg Brandl116aa622007-08-15 14:28:22 +0000435 >>> a ^ b # letters in a or b but not both
Guido van Rossum0616b792007-08-31 03:25:11 +0000436 {'r', 'd', 'b', 'm', 'z', 'l'}
437
Georg Brandlfc11f272009-06-16 19:22:10 +0000438Like :ref:`for lists <tut-listcomps>`, there is a set comprehension syntax::
Georg Brandlf6945182008-02-01 11:56:49 +0000439
440 >>> a = {x for x in 'abracadabra' if x not in 'abc'}
441 >>> a
442 {'r', 'd'}
Guido van Rossum0616b792007-08-31 03:25:11 +0000443
Georg Brandl116aa622007-08-15 14:28:22 +0000444
445
446.. _tut-dictionaries:
447
448Dictionaries
449============
450
451Another useful data type built into Python is the *dictionary* (see
452:ref:`typesmapping`). Dictionaries are sometimes found in other languages as
453"associative memories" or "associative arrays". Unlike sequences, which are
454indexed by a range of numbers, dictionaries are indexed by *keys*, which can be
455any immutable type; strings and numbers can always be keys. Tuples can be used
456as keys if they contain only strings, numbers, or tuples; if a tuple contains
457any mutable object either directly or indirectly, it cannot be used as a key.
458You can't use lists as keys, since lists can be modified in place using index
459assignments, slice assignments, or methods like :meth:`append` and
460:meth:`extend`.
461
462It is best to think of a dictionary as an unordered set of *key: value* pairs,
463with the requirement that the keys are unique (within one dictionary). A pair of
464braces creates an empty dictionary: ``{}``. Placing a comma-separated list of
465key:value pairs within the braces adds initial key:value pairs to the
466dictionary; this is also the way dictionaries are written on output.
467
468The main operations on a dictionary are storing a value with some key and
469extracting the value given the key. It is also possible to delete a key:value
470pair with ``del``. If you store using a key that is already in use, the old
471value associated with that key is forgotten. It is an error to extract a value
472using a non-existent key.
473
Georg Brandlabffe712008-12-15 08:28:37 +0000474Performing ``list(d.keys())`` on a dictionary returns a list of all the keys
Georg Brandlfc11f272009-06-16 19:22:10 +0000475used in the dictionary, in arbitrary order (if you want it sorted, just use
Georg Brandl388349a2011-10-08 18:32:40 +0200476``sorted(d.keys())`` instead). [2]_ To check whether a single key is in the
Georg Brandlfc11f272009-06-16 19:22:10 +0000477dictionary, use the :keyword:`in` keyword.
Georg Brandl116aa622007-08-15 14:28:22 +0000478
479Here is a small example using a dictionary::
480
481 >>> tel = {'jack': 4098, 'sape': 4139}
482 >>> tel['guido'] = 4127
483 >>> tel
484 {'sape': 4139, 'guido': 4127, 'jack': 4098}
485 >>> tel['jack']
486 4098
487 >>> del tel['sape']
488 >>> tel['irv'] = 4127
489 >>> tel
490 {'guido': 4127, 'irv': 4127, 'jack': 4098}
Neal Norwitze0906d12007-08-31 03:46:28 +0000491 >>> list(tel.keys())
Georg Brandlabffe712008-12-15 08:28:37 +0000492 ['irv', 'guido', 'jack']
493 >>> sorted(tel.keys())
Georg Brandl116aa622007-08-15 14:28:22 +0000494 ['guido', 'irv', 'jack']
Georg Brandl116aa622007-08-15 14:28:22 +0000495 >>> 'guido' in tel
496 True
Neal Norwitze0906d12007-08-31 03:46:28 +0000497 >>> 'jack' not in tel
498 False
Georg Brandl116aa622007-08-15 14:28:22 +0000499
Georg Brandlfc11f272009-06-16 19:22:10 +0000500The :func:`dict` constructor builds dictionaries directly from sequences of
Raymond Hettinger8699aea2009-06-16 20:49:30 +0000501key-value pairs::
Georg Brandl116aa622007-08-15 14:28:22 +0000502
503 >>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
504 {'sape': 4139, 'jack': 4098, 'guido': 4127}
Georg Brandl116aa622007-08-15 14:28:22 +0000505
Georg Brandlf6945182008-02-01 11:56:49 +0000506In addition, dict comprehensions can be used to create dictionaries from
507arbitrary key and value expressions::
508
509 >>> {x: x**2 for x in (2, 4, 6)}
510 {2: 4, 4: 16, 6: 36}
Georg Brandl116aa622007-08-15 14:28:22 +0000511
512When the keys are simple strings, it is sometimes easier to specify pairs using
513keyword arguments::
514
515 >>> dict(sape=4139, guido=4127, jack=4098)
516 {'sape': 4139, 'jack': 4098, 'guido': 4127}
517
518
519.. _tut-loopidioms:
520
521Looping Techniques
522==================
523
524When looping through dictionaries, the key and corresponding value can be
Neal Norwitze0906d12007-08-31 03:46:28 +0000525retrieved at the same time using the :meth:`items` method. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000526
527 >>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
Neal Norwitze0906d12007-08-31 03:46:28 +0000528 >>> for k, v in knights.items():
Guido van Rossum0616b792007-08-31 03:25:11 +0000529 ... print(k, v)
Georg Brandl116aa622007-08-15 14:28:22 +0000530 ...
531 gallahad the pure
532 robin the brave
533
534When looping through a sequence, the position index and corresponding value can
535be retrieved at the same time using the :func:`enumerate` function. ::
536
537 >>> for i, v in enumerate(['tic', 'tac', 'toe']):
Guido van Rossum0616b792007-08-31 03:25:11 +0000538 ... print(i, v)
Georg Brandl116aa622007-08-15 14:28:22 +0000539 ...
540 0 tic
541 1 tac
542 2 toe
543
544To loop over two or more sequences at the same time, the entries can be paired
545with the :func:`zip` function. ::
546
547 >>> questions = ['name', 'quest', 'favorite color']
548 >>> answers = ['lancelot', 'the holy grail', 'blue']
549 >>> for q, a in zip(questions, answers):
Benjamin Petersone6f00632008-05-26 01:03:56 +0000550 ... print('What is your {0}? It is {1}.'.format(q, a))
Georg Brandl06788c92009-01-03 21:31:47 +0000551 ...
Georg Brandl116aa622007-08-15 14:28:22 +0000552 What is your name? It is lancelot.
553 What is your quest? It is the holy grail.
554 What is your favorite color? It is blue.
555
556To loop over a sequence in reverse, first specify the sequence in a forward
557direction and then call the :func:`reversed` function. ::
558
Georg Brandle4ac7502007-09-03 07:10:24 +0000559 >>> for i in reversed(range(1, 10, 2)):
Guido van Rossum0616b792007-08-31 03:25:11 +0000560 ... print(i)
Georg Brandl116aa622007-08-15 14:28:22 +0000561 ...
562 9
563 7
564 5
565 3
566 1
567
568To loop over a sequence in sorted order, use the :func:`sorted` function which
569returns a new sorted list while leaving the source unaltered. ::
570
571 >>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
572 >>> for f in sorted(set(basket)):
Guido van Rossum0616b792007-08-31 03:25:11 +0000573 ... print(f)
Georg Brandl06788c92009-01-03 21:31:47 +0000574 ...
Georg Brandl116aa622007-08-15 14:28:22 +0000575 apple
576 banana
577 orange
578 pear
579
580
581.. _tut-conditions:
582
583More on Conditions
584==================
585
586The conditions used in ``while`` and ``if`` statements can contain any
587operators, not just comparisons.
588
589The comparison operators ``in`` and ``not in`` check whether a value occurs
590(does not occur) in a sequence. The operators ``is`` and ``is not`` compare
591whether two objects are really the same object; this only matters for mutable
592objects like lists. All comparison operators have the same priority, which is
593lower than that of all numerical operators.
594
595Comparisons can be chained. For example, ``a < b == c`` tests whether ``a`` is
596less than ``b`` and moreover ``b`` equals ``c``.
597
598Comparisons may be combined using the Boolean operators ``and`` and ``or``, and
599the outcome of a comparison (or of any other Boolean expression) may be negated
600with ``not``. These have lower priorities than comparison operators; between
601them, ``not`` has the highest priority and ``or`` the lowest, so that ``A and
602not B or C`` is equivalent to ``(A and (not B)) or C``. As always, parentheses
603can be used to express the desired composition.
604
605The Boolean operators ``and`` and ``or`` are so-called *short-circuit*
606operators: their arguments are evaluated from left to right, and evaluation
607stops as soon as the outcome is determined. For example, if ``A`` and ``C`` are
608true but ``B`` is false, ``A and B and C`` does not evaluate the expression
609``C``. When used as a general value and not as a Boolean, the return value of a
610short-circuit operator is the last evaluated argument.
611
612It is possible to assign the result of a comparison or other Boolean expression
613to a variable. For example, ::
614
615 >>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance'
616 >>> non_null = string1 or string2 or string3
617 >>> non_null
618 'Trondheim'
619
620Note that in Python, unlike C, assignment cannot occur inside expressions. C
621programmers may grumble about this, but it avoids a common class of problems
622encountered in C programs: typing ``=`` in an expression when ``==`` was
623intended.
624
625
626.. _tut-comparing:
627
628Comparing Sequences and Other Types
629===================================
630
631Sequence objects may be compared to other objects with the same sequence type.
632The comparison uses *lexicographical* ordering: first the first two items are
633compared, and if they differ this determines the outcome of the comparison; if
634they are equal, the next two items are compared, and so on, until either
635sequence is exhausted. If two items to be compared are themselves sequences of
636the same type, the lexicographical comparison is carried out recursively. If
637all items of two sequences compare equal, the sequences are considered equal.
638If one sequence is an initial sub-sequence of the other, the shorter sequence is
Georg Brandlfc11f272009-06-16 19:22:10 +0000639the smaller (lesser) one. Lexicographical ordering for strings uses the Unicode
640codepoint number to order individual characters. Some examples of comparisons
641between sequences of the same type::
Georg Brandl116aa622007-08-15 14:28:22 +0000642
643 (1, 2, 3) < (1, 2, 4)
644 [1, 2, 3] < [1, 2, 4]
645 'ABC' < 'C' < 'Pascal' < 'Python'
646 (1, 2, 3, 4) < (1, 2, 4)
647 (1, 2) < (1, 2, -1)
648 (1, 2, 3) == (1.0, 2.0, 3.0)
649 (1, 2, ('aa', 'ab')) < (1, 2, ('abc', 'a'), 4)
650
Georg Brandl9f2c39a2007-10-08 14:08:36 +0000651Note that comparing objects of different types with ``<`` or ``>`` is legal
652provided that the objects have appropriate comparison methods. For example,
653mixed numeric types are compared according to their numeric value, so 0 equals
6540.0, etc. Otherwise, rather than providing an arbitrary ordering, the
655interpreter will raise a :exc:`TypeError` exception.
Georg Brandlfc11f272009-06-16 19:22:10 +0000656
657
658.. rubric:: Footnotes
659
Georg Brandl388349a2011-10-08 18:32:40 +0200660.. [1] Other languages may return the mutated object, which allows method
661 chaining, such as ``d->insert("a")->remove("b")->sort();``.
662
663.. [2] Calling ``d.keys()`` will return a :dfn:`dictionary view` object. It
Georg Brandlfc11f272009-06-16 19:22:10 +0000664 supports operations like membership test and iteration, but its contents
665 are not independent of the original dictionary -- it is only a *view*.