blob: 28e6ad71b9545e5a2ebca9cfab53e44819c8ec19 [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +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
10
11.. _tut-morelists:
12
13More on Lists
14=============
15
16The list data type has some more methods. Here are all of the methods of list
17objects:
18
19
20.. method:: list.append(x)
Georg Brandl9c6c47b2008-03-21 14:32:33 +000021 :noindex:
Georg Brandl8ec7f652007-08-15 14:28:01 +000022
23 Add an item to the end of the list; equivalent to ``a[len(a):] = [x]``.
24
25
26.. method:: list.extend(L)
Georg Brandl9c6c47b2008-03-21 14:32:33 +000027 :noindex:
Georg Brandl8ec7f652007-08-15 14:28:01 +000028
29 Extend the list by appending all the items in the given list; equivalent to
30 ``a[len(a):] = L``.
31
32
33.. method:: list.insert(i, x)
Georg Brandl9c6c47b2008-03-21 14:32:33 +000034 :noindex:
Georg Brandl8ec7f652007-08-15 14:28:01 +000035
36 Insert an item at a given position. The first argument is the index of the
37 element before which to insert, so ``a.insert(0, x)`` inserts at the front of
38 the list, and ``a.insert(len(a), x)`` is equivalent to ``a.append(x)``.
39
40
41.. method:: list.remove(x)
Georg Brandl9c6c47b2008-03-21 14:32:33 +000042 :noindex:
Georg Brandl8ec7f652007-08-15 14:28:01 +000043
44 Remove the first item from the list whose value is *x*. It is an error if there
45 is no such item.
46
47
48.. method:: list.pop([i])
Georg Brandl9c6c47b2008-03-21 14:32:33 +000049 :noindex:
Georg Brandl8ec7f652007-08-15 14:28:01 +000050
51 Remove the item at the given position in the list, and return it. If no index
52 is specified, ``a.pop()`` removes and returns the last item in the list. (The
53 square brackets around the *i* in the method signature denote that the parameter
54 is optional, not that you should type square brackets at that position. You
55 will see this notation frequently in the Python Library Reference.)
56
57
58.. method:: list.index(x)
Georg Brandl9c6c47b2008-03-21 14:32:33 +000059 :noindex:
Georg Brandl8ec7f652007-08-15 14:28:01 +000060
61 Return the index in the list of the first item whose value is *x*. It is an
62 error if there is no such item.
63
64
65.. method:: list.count(x)
Georg Brandl9c6c47b2008-03-21 14:32:33 +000066 :noindex:
Georg Brandl8ec7f652007-08-15 14:28:01 +000067
68 Return the number of times *x* appears in the list.
69
70
71.. method:: list.sort()
Georg Brandl9c6c47b2008-03-21 14:32:33 +000072 :noindex:
Georg Brandl8ec7f652007-08-15 14:28:01 +000073
74 Sort the items of the list, in place.
75
76
77.. method:: list.reverse()
Georg Brandl9c6c47b2008-03-21 14:32:33 +000078 :noindex:
Georg Brandl8ec7f652007-08-15 14:28:01 +000079
80 Reverse the elements of the list, in place.
81
82An example that uses most of the list methods::
83
84 >>> a = [66.25, 333, 333, 1, 1234.5]
85 >>> print a.count(333), a.count(66.25), a.count('x')
86 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
103
104.. _tut-lists-as-stacks:
105
106Using Lists as Stacks
107---------------------
108
109.. sectionauthor:: Ka-Ping Yee <ping@lfw.org>
110
111
112The list methods make it very easy to use a list as a stack, where the last
113element added is the first element retrieved ("last-in, first-out"). To add an
114item to the top of the stack, use :meth:`append`. To retrieve an item from the
115top of the stack, use :meth:`pop` without an explicit index. For example::
116
117 >>> stack = [3, 4, 5]
118 >>> stack.append(6)
119 >>> stack.append(7)
120 >>> stack
121 [3, 4, 5, 6, 7]
122 >>> stack.pop()
123 7
124 >>> stack
125 [3, 4, 5, 6]
126 >>> stack.pop()
127 6
128 >>> stack.pop()
129 5
130 >>> stack
131 [3, 4]
132
133
134.. _tut-lists-as-queues:
135
136Using Lists as Queues
137---------------------
138
139.. sectionauthor:: Ka-Ping Yee <ping@lfw.org>
140
Ezio Melottieb729912010-03-31 07:26:24 +0000141It is also possible to use a list as a queue, where the first element added is
142the first element retrieved ("first-in, first-out"); however, lists are not
143efficient for this purpose. While appends and pops from the end of list are
144fast, doing inserts or pops from the beginning of a list is slow (because all
145of the other elements have to be shifted by one).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000146
Ezio Melottieb729912010-03-31 07:26:24 +0000147To implement a queue, use :class:`collections.deque` which was designed to
148have fast appends and pops from both ends. For example::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000149
Ezio Melottieb729912010-03-31 07:26:24 +0000150 >>> from collections import deque
151 >>> queue = deque(["Eric", "John", "Michael"])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000152 >>> queue.append("Terry") # Terry arrives
153 >>> queue.append("Graham") # Graham arrives
Ezio Melottieb729912010-03-31 07:26:24 +0000154 >>> queue.popleft() # The first to arrive now leaves
Georg Brandl8ec7f652007-08-15 14:28:01 +0000155 'Eric'
Ezio Melottieb729912010-03-31 07:26:24 +0000156 >>> queue.popleft() # The second to arrive now leaves
Georg Brandl8ec7f652007-08-15 14:28:01 +0000157 'John'
Ezio Melottieb729912010-03-31 07:26:24 +0000158 >>> queue # Remaining queue in order of arrival
159 deque(['Michael', 'Terry', 'Graham'])
Georg Brandla39f2af2010-03-21 09:37:54 +0000160
Georg Brandl8ec7f652007-08-15 14:28:01 +0000161
162.. _tut-functional:
163
164Functional Programming Tools
165----------------------------
166
167There are three built-in functions that are very useful when used with lists:
168:func:`filter`, :func:`map`, and :func:`reduce`.
169
170``filter(function, sequence)`` returns a sequence consisting of those items from
171the sequence for which ``function(item)`` is true. If *sequence* is a
172:class:`string` or :class:`tuple`, the result will be of the same type;
Senthil Kumaran169fa932011-09-29 07:52:46 +0800173otherwise, it is always a :class:`list`. For example, to compute a sequence of
Georg Brandlb3d6fe32013-10-06 11:41:36 +0200174numbers not divisible by 2 or 3::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000175
176 >>> def f(x): return x % 2 != 0 and x % 3 != 0
177 ...
178 >>> filter(f, range(2, 25))
179 [5, 7, 11, 13, 17, 19, 23]
180
181``map(function, sequence)`` calls ``function(item)`` for each of the sequence's
182items and returns a list of the return values. For example, to compute some
183cubes::
184
185 >>> def cube(x): return x*x*x
186 ...
187 >>> map(cube, range(1, 11))
188 [1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
189
190More than one sequence may be passed; the function must then have as many
191arguments as there are sequences and is called with the corresponding item from
192each sequence (or ``None`` if some sequence is shorter than another). For
193example::
194
195 >>> seq = range(8)
196 >>> def add(x, y): return x+y
197 ...
198 >>> map(add, seq, seq)
199 [0, 2, 4, 6, 8, 10, 12, 14]
200
201``reduce(function, sequence)`` returns a single value constructed by calling the
202binary function *function* on the first two items of the sequence, then on the
203result and the next item, and so on. For example, to compute the sum of the
204numbers 1 through 10::
205
206 >>> def add(x,y): return x+y
207 ...
208 >>> reduce(add, range(1, 11))
209 55
210
211If there's only one item in the sequence, its value is returned; if the sequence
212is empty, an exception is raised.
213
214A third argument can be passed to indicate the starting value. In this case the
215starting value is returned for an empty sequence, and the function is first
216applied to the starting value and the first sequence item, then to the result
217and the next item, and so on. For example, ::
218
219 >>> def sum(seq):
220 ... def add(x,y): return x+y
221 ... return reduce(add, seq, 0)
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000222 ...
Georg Brandl8ec7f652007-08-15 14:28:01 +0000223 >>> sum(range(1, 11))
224 55
225 >>> sum([])
226 0
227
228Don't use this example's definition of :func:`sum`: since summing numbers is
229such a common need, a built-in function ``sum(sequence)`` is already provided,
230and works exactly like this.
231
Ezio Melotti9236a4e2012-11-17 12:02:30 +0200232.. _tut-listcomps:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000233
234List Comprehensions
235-------------------
236
Ezio Melotti4a72d1a2011-12-13 14:50:21 +0200237List comprehensions provide a concise way to create lists.
238Common applications are to make new lists where each element is the result of
239some operations applied to each member of another sequence or iterable, or to
240create a subsequence of those elements that satisfy a certain condition.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000241
Ezio Melotti4a72d1a2011-12-13 14:50:21 +0200242For example, assume we want to create a list of squares, like::
243
244 >>> squares = []
245 >>> for x in range(10):
246 ... squares.append(x**2)
247 ...
248 >>> squares
249 [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
250
251We can obtain the same result with::
252
253 squares = [x**2 for x in range(10)]
254
255This is also equivalent to ``squares = map(lambda x: x**2, range(10))``,
256but it's more concise and readable.
257
258A list comprehension consists of brackets containing an expression followed
259by a :keyword:`for` clause, then zero or more :keyword:`for` or :keyword:`if`
260clauses. The result will be a new list resulting from evaluating the expression
261in the context of the :keyword:`for` and :keyword:`if` clauses which follow it.
262For example, this listcomp combines the elements of two lists if they are not
263equal::
264
265 >>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
266 [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
267
268and it's equivalent to:
269
270 >>> combs = []
271 >>> for x in [1,2,3]:
272 ... for y in [3,1,4]:
273 ... if x != y:
274 ... combs.append((x, y))
275 ...
276 >>> combs
277 [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
278
279Note how the order of the :keyword:`for` and :keyword:`if` statements is the
280same in both these snippets.
281
282If the expression is a tuple (e.g. the ``(x, y)`` in the previous example),
283it must be parenthesized. ::
284
285 >>> vec = [-4, -2, 0, 2, 4]
286 >>> # create a new list with the values doubled
287 >>> [x*2 for x in vec]
288 [-8, -4, 0, 4, 8]
289 >>> # filter the list to exclude negative numbers
290 >>> [x for x in vec if x >= 0]
291 [0, 2, 4]
292 >>> # apply a function to all the elements
293 >>> [abs(x) for x in vec]
294 [4, 2, 0, 2, 4]
295 >>> # call a method on each element
Georg Brandl8ec7f652007-08-15 14:28:01 +0000296 >>> freshfruit = [' banana', ' loganberry ', 'passion fruit ']
297 >>> [weapon.strip() for weapon in freshfruit]
298 ['banana', 'loganberry', 'passion fruit']
Ezio Melotti4a72d1a2011-12-13 14:50:21 +0200299 >>> # create a list of 2-tuples like (number, square)
300 >>> [(x, x**2) for x in range(6)]
301 [(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]
302 >>> # the tuple must be parenthesized, otherwise an error is raised
303 >>> [x, x**2 for x in range(6)]
304 File "<stdin>", line 1
305 [x, x**2 for x in range(6)]
Georg Brandl8ec7f652007-08-15 14:28:01 +0000306 ^
307 SyntaxError: invalid syntax
Ezio Melotti4a72d1a2011-12-13 14:50:21 +0200308 >>> # flatten a list using a listcomp with two 'for'
309 >>> vec = [[1,2,3], [4,5,6], [7,8,9]]
310 >>> [num for elem in vec for num in elem]
311 [1, 2, 3, 4, 5, 6, 7, 8, 9]
Georg Brandl8ec7f652007-08-15 14:28:01 +0000312
Ezio Melotti4a72d1a2011-12-13 14:50:21 +0200313List comprehensions can contain complex expressions and nested functions::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000314
Ezio Melotti4a72d1a2011-12-13 14:50:21 +0200315 >>> from math import pi
316 >>> [str(round(pi, i)) for i in range(1, 6)]
Georg Brandl8ec7f652007-08-15 14:28:01 +0000317 ['3.1', '3.14', '3.142', '3.1416', '3.14159']
318
319
Georg Brandladbda842007-12-14 19:03:36 +0000320Nested List Comprehensions
Ezio Melotti4a72d1a2011-12-13 14:50:21 +0200321''''''''''''''''''''''''''
Georg Brandladbda842007-12-14 19:03:36 +0000322
Ezio Melotti4a72d1a2011-12-13 14:50:21 +0200323The initial expression in a list comprehension can be any arbitrary expression,
324including another list comprehension.
Georg Brandladbda842007-12-14 19:03:36 +0000325
Ezio Melotti4a72d1a2011-12-13 14:50:21 +0200326Consider the following example of a 3x4 matrix implemented as a list of
3273 lists of length 4::
Georg Brandladbda842007-12-14 19:03:36 +0000328
Ezio Melotti4a72d1a2011-12-13 14:50:21 +0200329 >>> matrix = [
330 ... [1, 2, 3, 4],
331 ... [5, 6, 7, 8],
332 ... [9, 10, 11, 12],
333 ... ]
Georg Brandladbda842007-12-14 19:03:36 +0000334
Ezio Melotti4a72d1a2011-12-13 14:50:21 +0200335The following list comprehension will transpose rows and columns::
Georg Brandladbda842007-12-14 19:03:36 +0000336
Ezio Melotti4a72d1a2011-12-13 14:50:21 +0200337 >>> [[row[i] for row in matrix] for i in range(4)]
338 [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
Georg Brandladbda842007-12-14 19:03:36 +0000339
Ezio Melotti4a72d1a2011-12-13 14:50:21 +0200340As we saw in the previous section, the nested listcomp is evaluated in
341the context of the :keyword:`for` that follows it, so this example is
342equivalent to::
Georg Brandladbda842007-12-14 19:03:36 +0000343
Ezio Melotti4a72d1a2011-12-13 14:50:21 +0200344 >>> transposed = []
345 >>> for i in range(4):
346 ... transposed.append([row[i] for row in matrix])
347 ...
348 >>> transposed
349 [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
Georg Brandladbda842007-12-14 19:03:36 +0000350
Ezio Melotti4a72d1a2011-12-13 14:50:21 +0200351which, in turn, is the same as::
Georg Brandladbda842007-12-14 19:03:36 +0000352
Ezio Melotti4a72d1a2011-12-13 14:50:21 +0200353 >>> transposed = []
354 >>> for i in range(4):
355 ... # the following 3 lines implement the nested listcomp
356 ... transposed_row = []
357 ... for row in matrix:
358 ... transposed_row.append(row[i])
359 ... transposed.append(transposed_row)
360 ...
361 >>> transposed
362 [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
Georg Brandladbda842007-12-14 19:03:36 +0000363
Ezio Melotti4a72d1a2011-12-13 14:50:21 +0200364
365In the real world, you should prefer built-in functions to complex flow statements.
Georg Brandladbda842007-12-14 19:03:36 +0000366The :func:`zip` function would do a great job for this use case::
367
Ezio Melotti4a72d1a2011-12-13 14:50:21 +0200368 >>> zip(*matrix)
369 [(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]
Georg Brandladbda842007-12-14 19:03:36 +0000370
371See :ref:`tut-unpacking-arguments` for details on the asterisk in this line.
372
Georg Brandl8ec7f652007-08-15 14:28:01 +0000373.. _tut-del:
374
375The :keyword:`del` statement
376============================
377
378There is a way to remove an item from a list given its index instead of its
379value: the :keyword:`del` statement. This differs from the :meth:`pop` method
380which returns a value. The :keyword:`del` statement can also be used to remove
381slices from a list or clear the entire list (which we did earlier by assignment
382of an empty list to the slice). For example::
383
384 >>> a = [-1, 1, 66.25, 333, 333, 1234.5]
385 >>> del a[0]
386 >>> a
387 [1, 66.25, 333, 333, 1234.5]
388 >>> del a[2:4]
389 >>> a
390 [1, 66.25, 1234.5]
391 >>> del a[:]
392 >>> a
393 []
394
395:keyword:`del` can also be used to delete entire variables::
396
397 >>> del a
398
399Referencing the name ``a`` hereafter is an error (at least until another value
400is assigned to it). We'll find other uses for :keyword:`del` later.
401
402
403.. _tut-tuples:
404
405Tuples and Sequences
406====================
407
408We saw that lists and strings have many common properties, such as indexing and
409slicing operations. They are two examples of *sequence* data types (see
410:ref:`typesseq`). Since Python is an evolving language, other sequence data
411types may be added. There is also another standard sequence data type: the
412*tuple*.
413
414A tuple consists of a number of values separated by commas, for instance::
415
416 >>> t = 12345, 54321, 'hello!'
417 >>> t[0]
418 12345
419 >>> t
420 (12345, 54321, 'hello!')
421 >>> # Tuples may be nested:
422 ... u = t, (1, 2, 3, 4, 5)
423 >>> u
424 ((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))
Ezio Melottif6379202012-06-17 14:10:59 +0200425 >>> # Tuples are immutable:
426 ... t[0] = 88888
427 Traceback (most recent call last):
428 File "<stdin>", line 1, in <module>
429 TypeError: 'tuple' object does not support item assignment
430 >>> # but they can contain mutable objects:
431 ... v = ([1, 2, 3], [3, 2, 1])
432 >>> v
433 ([1, 2, 3], [3, 2, 1])
434
Georg Brandl8ec7f652007-08-15 14:28:01 +0000435
436As you see, on output tuples are always enclosed in parentheses, so that nested
437tuples are interpreted correctly; they may be input with or without surrounding
438parentheses, although often parentheses are necessary anyway (if the tuple is
Ezio Melottif6379202012-06-17 14:10:59 +0200439part of a larger expression). It is not possible to assign to the individual
440items of a tuple, however it is possible to create tuples which contain mutable
441objects, such as lists.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000442
Ezio Melottif6379202012-06-17 14:10:59 +0200443Though tuples may seem similar to lists, they are often used in different
444situations and for different purposes.
445Tuples are :term:`immutable`, and usually contain an heterogeneous sequence of
446elements that are accessed via unpacking (see later in this section) or indexing
447(or even by attribute in the case of :func:`namedtuples <collections.namedtuple>`).
448Lists are :term:`mutable`, and their elements are usually homogeneous and are
449accessed by iterating over the list.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000450
451A special problem is the construction of tuples containing 0 or 1 items: the
452syntax has some extra quirks to accommodate these. Empty tuples are constructed
453by an empty pair of parentheses; a tuple with one item is constructed by
454following a value with a comma (it is not sufficient to enclose a single value
455in parentheses). Ugly, but effective. For example::
456
457 >>> empty = ()
458 >>> singleton = 'hello', # <-- note trailing comma
459 >>> len(empty)
460 0
461 >>> len(singleton)
462 1
463 >>> singleton
464 ('hello',)
465
466The statement ``t = 12345, 54321, 'hello!'`` is an example of *tuple packing*:
467the values ``12345``, ``54321`` and ``'hello!'`` are packed together in a tuple.
468The reverse operation is also possible::
469
470 >>> x, y, z = t
471
Georg Brandl354e4cb2009-03-31 22:40:16 +0000472This is called, appropriately enough, *sequence unpacking* and works for any
473sequence on the right-hand side. Sequence unpacking requires the list of
474variables on the left to have the same number of elements as the length of the
475sequence. Note that multiple assignment is really just a combination of tuple
Georg Brandla08867d2009-03-31 23:01:27 +0000476packing and sequence unpacking.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000477
Georg Brandl8ec7f652007-08-15 14:28:01 +0000478
479.. _tut-sets:
480
481Sets
482====
483
484Python also includes a data type for *sets*. A set is an unordered collection
485with no duplicate elements. Basic uses include membership testing and
486eliminating duplicate entries. Set objects also support mathematical operations
487like union, intersection, difference, and symmetric difference.
488
Ezio Melotti9236a4e2012-11-17 12:02:30 +0200489Curly braces or the :func:`set` function can be used to create sets. Note: to
490create an empty set you have to use ``set()``, not ``{}``; the latter creates an
491empty dictionary, a data structure that we discuss in the next section.
492
Georg Brandl8ec7f652007-08-15 14:28:01 +0000493Here is a brief demonstration::
494
495 >>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
496 >>> fruit = set(basket) # create a set without duplicates
497 >>> fruit
498 set(['orange', 'pear', 'apple', 'banana'])
499 >>> 'orange' in fruit # fast membership testing
500 True
501 >>> 'crabgrass' in fruit
502 False
503
504 >>> # Demonstrate set operations on unique letters from two words
505 ...
506 >>> a = set('abracadabra')
507 >>> b = set('alacazam')
508 >>> a # unique letters in a
509 set(['a', 'r', 'b', 'c', 'd'])
510 >>> a - b # letters in a but not in b
511 set(['r', 'd', 'b'])
512 >>> a | b # letters in either a or b
513 set(['a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'])
514 >>> a & b # letters in both a and b
515 set(['a', 'c'])
516 >>> a ^ b # letters in a or b but not both
517 set(['r', 'd', 'b', 'm', 'z', 'l'])
518
Ezio Melotti9236a4e2012-11-17 12:02:30 +0200519Similarly to :ref:`list comprehensions <tut-listcomps>`, set comprehensions
520are also supported::
521
522 >>> a = {x for x in 'abracadabra' if x not in 'abc'}
523 >>> a
524 set(['r', 'd'])
525
Georg Brandl8ec7f652007-08-15 14:28:01 +0000526
527.. _tut-dictionaries:
528
529Dictionaries
530============
531
532Another useful data type built into Python is the *dictionary* (see
533:ref:`typesmapping`). Dictionaries are sometimes found in other languages as
534"associative memories" or "associative arrays". Unlike sequences, which are
535indexed by a range of numbers, dictionaries are indexed by *keys*, which can be
536any immutable type; strings and numbers can always be keys. Tuples can be used
537as keys if they contain only strings, numbers, or tuples; if a tuple contains
538any mutable object either directly or indirectly, it cannot be used as a key.
539You can't use lists as keys, since lists can be modified in place using index
540assignments, slice assignments, or methods like :meth:`append` and
541:meth:`extend`.
542
543It is best to think of a dictionary as an unordered set of *key: value* pairs,
544with the requirement that the keys are unique (within one dictionary). A pair of
545braces creates an empty dictionary: ``{}``. Placing a comma-separated list of
546key:value pairs within the braces adds initial key:value pairs to the
547dictionary; this is also the way dictionaries are written on output.
548
549The main operations on a dictionary are storing a value with some key and
550extracting the value given the key. It is also possible to delete a key:value
551pair with ``del``. If you store using a key that is already in use, the old
552value associated with that key is forgotten. It is an error to extract a value
553using a non-existent key.
554
555The :meth:`keys` method of a dictionary object returns a list of all the keys
556used in the dictionary, in arbitrary order (if you want it sorted, just apply
Georg Brandl44c3ceb2010-10-15 15:31:09 +0000557the :func:`sorted` function to it). To check whether a single key is in the
558dictionary, use the :keyword:`in` keyword.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000559
560Here is a small example using a dictionary::
561
562 >>> tel = {'jack': 4098, 'sape': 4139}
563 >>> tel['guido'] = 4127
564 >>> tel
565 {'sape': 4139, 'guido': 4127, 'jack': 4098}
566 >>> tel['jack']
567 4098
568 >>> del tel['sape']
569 >>> tel['irv'] = 4127
570 >>> tel
571 {'guido': 4127, 'irv': 4127, 'jack': 4098}
572 >>> tel.keys()
573 ['guido', 'irv', 'jack']
Georg Brandl8ec7f652007-08-15 14:28:01 +0000574 >>> 'guido' in tel
575 True
576
Ezio Melotti9236a4e2012-11-17 12:02:30 +0200577The :func:`dict` constructor builds dictionaries directly from sequences of
578key-value pairs::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000579
580 >>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
581 {'sape': 4139, 'jack': 4098, 'guido': 4127}
Georg Brandl8ec7f652007-08-15 14:28:01 +0000582
Ezio Melotti9236a4e2012-11-17 12:02:30 +0200583In addition, dict comprehensions can be used to create dictionaries from
584arbitrary key and value expressions::
585
586 >>> {x: x**2 for x in (2, 4, 6)}
587 {2: 4, 4: 16, 6: 36}
Georg Brandl8ec7f652007-08-15 14:28:01 +0000588
589When the keys are simple strings, it is sometimes easier to specify pairs using
590keyword arguments::
591
592 >>> dict(sape=4139, guido=4127, jack=4098)
593 {'sape': 4139, 'jack': 4098, 'guido': 4127}
594
595
596.. _tut-loopidioms:
597
598Looping Techniques
599==================
600
Georg Brandl8ec7f652007-08-15 14:28:01 +0000601When looping through a sequence, the position index and corresponding value can
602be retrieved at the same time using the :func:`enumerate` function. ::
603
604 >>> for i, v in enumerate(['tic', 'tac', 'toe']):
605 ... print i, v
606 ...
607 0 tic
608 1 tac
609 2 toe
610
611To loop over two or more sequences at the same time, the entries can be paired
612with the :func:`zip` function. ::
613
614 >>> questions = ['name', 'quest', 'favorite color']
615 >>> answers = ['lancelot', 'the holy grail', 'blue']
616 >>> for q, a in zip(questions, answers):
Benjamin Petersonf9ef9882008-05-26 00:54:22 +0000617 ... print 'What is your {0}? It is {1}.'.format(q, a)
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000618 ...
Georg Brandl8ec7f652007-08-15 14:28:01 +0000619 What is your name? It is lancelot.
620 What is your quest? It is the holy grail.
621 What is your favorite color? It is blue.
622
623To loop over a sequence in reverse, first specify the sequence in a forward
624direction and then call the :func:`reversed` function. ::
625
626 >>> for i in reversed(xrange(1,10,2)):
627 ... print i
628 ...
629 9
630 7
631 5
632 3
633 1
634
635To loop over a sequence in sorted order, use the :func:`sorted` function which
636returns a new sorted list while leaving the source unaltered. ::
637
638 >>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
639 >>> for f in sorted(set(basket)):
640 ... print f
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000641 ...
Georg Brandl8ec7f652007-08-15 14:28:01 +0000642 apple
643 banana
644 orange
645 pear
646
Raymond Hettinger4c8d3922012-04-23 21:24:15 -0700647When looping through dictionaries, the key and corresponding value can be
648retrieved at the same time using the :meth:`iteritems` method. ::
649
650 >>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
651 >>> for k, v in knights.iteritems():
652 ... print k, v
653 ...
654 gallahad the pure
655 robin the brave
656
Chris Jerdonek0cffd6b2012-10-15 20:01:38 -0700657To change a sequence you are iterating over while inside the loop (for
658example to duplicate certain items), it is recommended that you first make
659a copy. Looping over a sequence does not implicitly make a copy. The slice
660notation makes this especially convenient::
661
662 >>> words = ['cat', 'window', 'defenestrate']
663 >>> for w in words[:]: # Loop over a slice copy of the entire list.
664 ... if len(w) > 6:
665 ... words.insert(0, w)
666 ...
667 >>> words
668 ['defenestrate', 'cat', 'window', 'defenestrate']
669
Georg Brandl8ec7f652007-08-15 14:28:01 +0000670
671.. _tut-conditions:
672
673More on Conditions
674==================
675
676The conditions used in ``while`` and ``if`` statements can contain any
677operators, not just comparisons.
678
679The comparison operators ``in`` and ``not in`` check whether a value occurs
680(does not occur) in a sequence. The operators ``is`` and ``is not`` compare
681whether two objects are really the same object; this only matters for mutable
682objects like lists. All comparison operators have the same priority, which is
683lower than that of all numerical operators.
684
685Comparisons can be chained. For example, ``a < b == c`` tests whether ``a`` is
686less than ``b`` and moreover ``b`` equals ``c``.
687
688Comparisons may be combined using the Boolean operators ``and`` and ``or``, and
689the outcome of a comparison (or of any other Boolean expression) may be negated
690with ``not``. These have lower priorities than comparison operators; between
691them, ``not`` has the highest priority and ``or`` the lowest, so that ``A and
692not B or C`` is equivalent to ``(A and (not B)) or C``. As always, parentheses
693can be used to express the desired composition.
694
695The Boolean operators ``and`` and ``or`` are so-called *short-circuit*
696operators: their arguments are evaluated from left to right, and evaluation
697stops as soon as the outcome is determined. For example, if ``A`` and ``C`` are
698true but ``B`` is false, ``A and B and C`` does not evaluate the expression
699``C``. When used as a general value and not as a Boolean, the return value of a
700short-circuit operator is the last evaluated argument.
701
702It is possible to assign the result of a comparison or other Boolean expression
703to a variable. For example, ::
704
705 >>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance'
706 >>> non_null = string1 or string2 or string3
707 >>> non_null
708 'Trondheim'
709
710Note that in Python, unlike C, assignment cannot occur inside expressions. C
711programmers may grumble about this, but it avoids a common class of problems
712encountered in C programs: typing ``=`` in an expression when ``==`` was
713intended.
714
715
716.. _tut-comparing:
717
718Comparing Sequences and Other Types
719===================================
720
721Sequence objects may be compared to other objects with the same sequence type.
722The comparison uses *lexicographical* ordering: first the first two items are
723compared, and if they differ this determines the outcome of the comparison; if
724they are equal, the next two items are compared, and so on, until either
725sequence is exhausted. If two items to be compared are themselves sequences of
726the same type, the lexicographical comparison is carried out recursively. If
727all items of two sequences compare equal, the sequences are considered equal.
728If one sequence is an initial sub-sequence of the other, the shorter sequence is
729the smaller (lesser) one. Lexicographical ordering for strings uses the ASCII
730ordering for individual characters. Some examples of comparisons between
731sequences of the same type::
732
733 (1, 2, 3) < (1, 2, 4)
734 [1, 2, 3] < [1, 2, 4]
735 'ABC' < 'C' < 'Pascal' < 'Python'
736 (1, 2, 3, 4) < (1, 2, 4)
737 (1, 2) < (1, 2, -1)
738 (1, 2, 3) == (1.0, 2.0, 3.0)
739 (1, 2, ('aa', 'ab')) < (1, 2, ('abc', 'a'), 4)
740
741Note that comparing objects of different types is legal. The outcome is
742deterministic but arbitrary: the types are ordered by their name. Thus, a list
743is always smaller than a string, a string is always smaller than a tuple, etc.
744[#]_ Mixed numeric types are compared according to their numeric value, so 0
745equals 0.0, etc.
746
747
748.. rubric:: Footnotes
749
750.. [#] The rules for comparing objects of different types should not be relied upon;
751 they may change in a future version of the language.
752