blob: a2edca183db8e35d76d03175d741f74c4d5eab4a [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
174numbers not divisible by 2 and 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
Georg Brandl8ec7f652007-08-15 14:28:01 +0000232
233List Comprehensions
234-------------------
235
Ezio Melotti4a72d1a2011-12-13 14:50:21 +0200236List comprehensions provide a concise way to create lists.
237Common applications are to make new lists where each element is the result of
238some operations applied to each member of another sequence or iterable, or to
239create a subsequence of those elements that satisfy a certain condition.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000240
Ezio Melotti4a72d1a2011-12-13 14:50:21 +0200241For example, assume we want to create a list of squares, like::
242
243 >>> squares = []
244 >>> for x in range(10):
245 ... squares.append(x**2)
246 ...
247 >>> squares
248 [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
249
250We can obtain the same result with::
251
252 squares = [x**2 for x in range(10)]
253
254This is also equivalent to ``squares = map(lambda x: x**2, range(10))``,
255but it's more concise and readable.
256
257A list comprehension consists of brackets containing an expression followed
258by a :keyword:`for` clause, then zero or more :keyword:`for` or :keyword:`if`
259clauses. The result will be a new list resulting from evaluating the expression
260in the context of the :keyword:`for` and :keyword:`if` clauses which follow it.
261For example, this listcomp combines the elements of two lists if they are not
262equal::
263
264 >>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
265 [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
266
267and it's equivalent to:
268
269 >>> combs = []
270 >>> for x in [1,2,3]:
271 ... for y in [3,1,4]:
272 ... if x != y:
273 ... combs.append((x, y))
274 ...
275 >>> combs
276 [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
277
278Note how the order of the :keyword:`for` and :keyword:`if` statements is the
279same in both these snippets.
280
281If the expression is a tuple (e.g. the ``(x, y)`` in the previous example),
282it must be parenthesized. ::
283
284 >>> vec = [-4, -2, 0, 2, 4]
285 >>> # create a new list with the values doubled
286 >>> [x*2 for x in vec]
287 [-8, -4, 0, 4, 8]
288 >>> # filter the list to exclude negative numbers
289 >>> [x for x in vec if x >= 0]
290 [0, 2, 4]
291 >>> # apply a function to all the elements
292 >>> [abs(x) for x in vec]
293 [4, 2, 0, 2, 4]
294 >>> # call a method on each element
Georg Brandl8ec7f652007-08-15 14:28:01 +0000295 >>> freshfruit = [' banana', ' loganberry ', 'passion fruit ']
296 >>> [weapon.strip() for weapon in freshfruit]
297 ['banana', 'loganberry', 'passion fruit']
Ezio Melotti4a72d1a2011-12-13 14:50:21 +0200298 >>> # create a list of 2-tuples like (number, square)
299 >>> [(x, x**2) for x in range(6)]
300 [(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]
301 >>> # the tuple must be parenthesized, otherwise an error is raised
302 >>> [x, x**2 for x in range(6)]
303 File "<stdin>", line 1
304 [x, x**2 for x in range(6)]
Georg Brandl8ec7f652007-08-15 14:28:01 +0000305 ^
306 SyntaxError: invalid syntax
Ezio Melotti4a72d1a2011-12-13 14:50:21 +0200307 >>> # flatten a list using a listcomp with two 'for'
308 >>> vec = [[1,2,3], [4,5,6], [7,8,9]]
309 >>> [num for elem in vec for num in elem]
310 [1, 2, 3, 4, 5, 6, 7, 8, 9]
Georg Brandl8ec7f652007-08-15 14:28:01 +0000311
Ezio Melotti4a72d1a2011-12-13 14:50:21 +0200312List comprehensions can contain complex expressions and nested functions::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000313
Ezio Melotti4a72d1a2011-12-13 14:50:21 +0200314 >>> from math import pi
315 >>> [str(round(pi, i)) for i in range(1, 6)]
Georg Brandl8ec7f652007-08-15 14:28:01 +0000316 ['3.1', '3.14', '3.142', '3.1416', '3.14159']
317
318
Georg Brandladbda842007-12-14 19:03:36 +0000319Nested List Comprehensions
Ezio Melotti4a72d1a2011-12-13 14:50:21 +0200320''''''''''''''''''''''''''
Georg Brandladbda842007-12-14 19:03:36 +0000321
Ezio Melotti4a72d1a2011-12-13 14:50:21 +0200322The initial expression in a list comprehension can be any arbitrary expression,
323including another list comprehension.
Georg Brandladbda842007-12-14 19:03:36 +0000324
Ezio Melotti4a72d1a2011-12-13 14:50:21 +0200325Consider the following example of a 3x4 matrix implemented as a list of
3263 lists of length 4::
Georg Brandladbda842007-12-14 19:03:36 +0000327
Ezio Melotti4a72d1a2011-12-13 14:50:21 +0200328 >>> matrix = [
329 ... [1, 2, 3, 4],
330 ... [5, 6, 7, 8],
331 ... [9, 10, 11, 12],
332 ... ]
Georg Brandladbda842007-12-14 19:03:36 +0000333
Ezio Melotti4a72d1a2011-12-13 14:50:21 +0200334The following list comprehension will transpose rows and columns::
Georg Brandladbda842007-12-14 19:03:36 +0000335
Ezio Melotti4a72d1a2011-12-13 14:50:21 +0200336 >>> [[row[i] for row in matrix] for i in range(4)]
337 [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
Georg Brandladbda842007-12-14 19:03:36 +0000338
Ezio Melotti4a72d1a2011-12-13 14:50:21 +0200339As we saw in the previous section, the nested listcomp is evaluated in
340the context of the :keyword:`for` that follows it, so this example is
341equivalent to::
Georg Brandladbda842007-12-14 19:03:36 +0000342
Ezio Melotti4a72d1a2011-12-13 14:50:21 +0200343 >>> transposed = []
344 >>> for i in range(4):
345 ... transposed.append([row[i] for row in matrix])
346 ...
347 >>> transposed
348 [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
Georg Brandladbda842007-12-14 19:03:36 +0000349
Ezio Melotti4a72d1a2011-12-13 14:50:21 +0200350which, in turn, is the same as::
Georg Brandladbda842007-12-14 19:03:36 +0000351
Ezio Melotti4a72d1a2011-12-13 14:50:21 +0200352 >>> transposed = []
353 >>> for i in range(4):
354 ... # the following 3 lines implement the nested listcomp
355 ... transposed_row = []
356 ... for row in matrix:
357 ... transposed_row.append(row[i])
358 ... transposed.append(transposed_row)
359 ...
360 >>> transposed
361 [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
Georg Brandladbda842007-12-14 19:03:36 +0000362
Ezio Melotti4a72d1a2011-12-13 14:50:21 +0200363
364In the real world, you should prefer built-in functions to complex flow statements.
Georg Brandladbda842007-12-14 19:03:36 +0000365The :func:`zip` function would do a great job for this use case::
366
Ezio Melotti4a72d1a2011-12-13 14:50:21 +0200367 >>> zip(*matrix)
368 [(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]
Georg Brandladbda842007-12-14 19:03:36 +0000369
370See :ref:`tut-unpacking-arguments` for details on the asterisk in this line.
371
Georg Brandl8ec7f652007-08-15 14:28:01 +0000372.. _tut-del:
373
374The :keyword:`del` statement
375============================
376
377There is a way to remove an item from a list given its index instead of its
378value: the :keyword:`del` statement. This differs from the :meth:`pop` method
379which returns a value. The :keyword:`del` statement can also be used to remove
380slices from a list or clear the entire list (which we did earlier by assignment
381of an empty list to the slice). For example::
382
383 >>> a = [-1, 1, 66.25, 333, 333, 1234.5]
384 >>> del a[0]
385 >>> a
386 [1, 66.25, 333, 333, 1234.5]
387 >>> del a[2:4]
388 >>> a
389 [1, 66.25, 1234.5]
390 >>> del a[:]
391 >>> a
392 []
393
394:keyword:`del` can also be used to delete entire variables::
395
396 >>> del a
397
398Referencing the name ``a`` hereafter is an error (at least until another value
399is assigned to it). We'll find other uses for :keyword:`del` later.
400
401
402.. _tut-tuples:
403
404Tuples and Sequences
405====================
406
407We saw that lists and strings have many common properties, such as indexing and
408slicing operations. They are two examples of *sequence* data types (see
409:ref:`typesseq`). Since Python is an evolving language, other sequence data
410types may be added. There is also another standard sequence data type: the
411*tuple*.
412
413A tuple consists of a number of values separated by commas, for instance::
414
415 >>> t = 12345, 54321, 'hello!'
416 >>> t[0]
417 12345
418 >>> t
419 (12345, 54321, 'hello!')
420 >>> # Tuples may be nested:
421 ... u = t, (1, 2, 3, 4, 5)
422 >>> u
423 ((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))
Ezio Melottif6379202012-06-17 14:10:59 +0200424 >>> # Tuples are immutable:
425 ... t[0] = 88888
426 Traceback (most recent call last):
427 File "<stdin>", line 1, in <module>
428 TypeError: 'tuple' object does not support item assignment
429 >>> # but they can contain mutable objects:
430 ... v = ([1, 2, 3], [3, 2, 1])
431 >>> v
432 ([1, 2, 3], [3, 2, 1])
433
Georg Brandl8ec7f652007-08-15 14:28:01 +0000434
435As you see, on output tuples are always enclosed in parentheses, so that nested
436tuples are interpreted correctly; they may be input with or without surrounding
437parentheses, although often parentheses are necessary anyway (if the tuple is
Ezio Melottif6379202012-06-17 14:10:59 +0200438part of a larger expression). It is not possible to assign to the individual
439items of a tuple, however it is possible to create tuples which contain mutable
440objects, such as lists.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000441
Ezio Melottif6379202012-06-17 14:10:59 +0200442Though tuples may seem similar to lists, they are often used in different
443situations and for different purposes.
444Tuples are :term:`immutable`, and usually contain an heterogeneous sequence of
445elements that are accessed via unpacking (see later in this section) or indexing
446(or even by attribute in the case of :func:`namedtuples <collections.namedtuple>`).
447Lists are :term:`mutable`, and their elements are usually homogeneous and are
448accessed by iterating over the list.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000449
450A special problem is the construction of tuples containing 0 or 1 items: the
451syntax has some extra quirks to accommodate these. Empty tuples are constructed
452by an empty pair of parentheses; a tuple with one item is constructed by
453following a value with a comma (it is not sufficient to enclose a single value
454in parentheses). Ugly, but effective. For example::
455
456 >>> empty = ()
457 >>> singleton = 'hello', # <-- note trailing comma
458 >>> len(empty)
459 0
460 >>> len(singleton)
461 1
462 >>> singleton
463 ('hello',)
464
465The statement ``t = 12345, 54321, 'hello!'`` is an example of *tuple packing*:
466the values ``12345``, ``54321`` and ``'hello!'`` are packed together in a tuple.
467The reverse operation is also possible::
468
469 >>> x, y, z = t
470
Georg Brandl354e4cb2009-03-31 22:40:16 +0000471This is called, appropriately enough, *sequence unpacking* and works for any
472sequence on the right-hand side. Sequence unpacking requires the list of
473variables on the left to have the same number of elements as the length of the
474sequence. Note that multiple assignment is really just a combination of tuple
Georg Brandla08867d2009-03-31 23:01:27 +0000475packing and sequence unpacking.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000476
Georg Brandl8ec7f652007-08-15 14:28:01 +0000477
478.. _tut-sets:
479
480Sets
481====
482
483Python also includes a data type for *sets*. A set is an unordered collection
484with no duplicate elements. Basic uses include membership testing and
485eliminating duplicate entries. Set objects also support mathematical operations
486like union, intersection, difference, and symmetric difference.
487
488Here is a brief demonstration::
489
490 >>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
491 >>> fruit = set(basket) # create a set without duplicates
492 >>> fruit
493 set(['orange', 'pear', 'apple', 'banana'])
494 >>> 'orange' in fruit # fast membership testing
495 True
496 >>> 'crabgrass' in fruit
497 False
498
499 >>> # Demonstrate set operations on unique letters from two words
500 ...
501 >>> a = set('abracadabra')
502 >>> b = set('alacazam')
503 >>> a # unique letters in a
504 set(['a', 'r', 'b', 'c', 'd'])
505 >>> a - b # letters in a but not in b
506 set(['r', 'd', 'b'])
507 >>> a | b # letters in either a or b
508 set(['a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'])
509 >>> a & b # letters in both a and b
510 set(['a', 'c'])
511 >>> a ^ b # letters in a or b but not both
512 set(['r', 'd', 'b', 'm', 'z', 'l'])
513
514
515.. _tut-dictionaries:
516
517Dictionaries
518============
519
520Another useful data type built into Python is the *dictionary* (see
521:ref:`typesmapping`). Dictionaries are sometimes found in other languages as
522"associative memories" or "associative arrays". Unlike sequences, which are
523indexed by a range of numbers, dictionaries are indexed by *keys*, which can be
524any immutable type; strings and numbers can always be keys. Tuples can be used
525as keys if they contain only strings, numbers, or tuples; if a tuple contains
526any mutable object either directly or indirectly, it cannot be used as a key.
527You can't use lists as keys, since lists can be modified in place using index
528assignments, slice assignments, or methods like :meth:`append` and
529:meth:`extend`.
530
531It is best to think of a dictionary as an unordered set of *key: value* pairs,
532with the requirement that the keys are unique (within one dictionary). A pair of
533braces creates an empty dictionary: ``{}``. Placing a comma-separated list of
534key:value pairs within the braces adds initial key:value pairs to the
535dictionary; this is also the way dictionaries are written on output.
536
537The main operations on a dictionary are storing a value with some key and
538extracting the value given the key. It is also possible to delete a key:value
539pair with ``del``. If you store using a key that is already in use, the old
540value associated with that key is forgotten. It is an error to extract a value
541using a non-existent key.
542
543The :meth:`keys` method of a dictionary object returns a list of all the keys
544used in the dictionary, in arbitrary order (if you want it sorted, just apply
Georg Brandl44c3ceb2010-10-15 15:31:09 +0000545the :func:`sorted` function to it). To check whether a single key is in the
546dictionary, use the :keyword:`in` keyword.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000547
548Here is a small example using a dictionary::
549
550 >>> tel = {'jack': 4098, 'sape': 4139}
551 >>> tel['guido'] = 4127
552 >>> tel
553 {'sape': 4139, 'guido': 4127, 'jack': 4098}
554 >>> tel['jack']
555 4098
556 >>> del tel['sape']
557 >>> tel['irv'] = 4127
558 >>> tel
559 {'guido': 4127, 'irv': 4127, 'jack': 4098}
560 >>> tel.keys()
561 ['guido', 'irv', 'jack']
Georg Brandl8ec7f652007-08-15 14:28:01 +0000562 >>> 'guido' in tel
563 True
564
565The :func:`dict` constructor builds dictionaries directly from lists of
566key-value pairs stored as tuples. When the pairs form a pattern, list
567comprehensions can compactly specify the key-value list. ::
568
569 >>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
570 {'sape': 4139, 'jack': 4098, 'guido': 4127}
571 >>> dict([(x, x**2) for x in (2, 4, 6)]) # use a list comprehension
572 {2: 4, 4: 16, 6: 36}
573
574Later in the tutorial, we will learn about Generator Expressions which are even
575better suited for the task of supplying key-values pairs to the :func:`dict`
576constructor.
577
578When the keys are simple strings, it is sometimes easier to specify pairs using
579keyword arguments::
580
581 >>> dict(sape=4139, guido=4127, jack=4098)
582 {'sape': 4139, 'jack': 4098, 'guido': 4127}
583
584
585.. _tut-loopidioms:
586
587Looping Techniques
588==================
589
Georg Brandl8ec7f652007-08-15 14:28:01 +0000590When looping through a sequence, the position index and corresponding value can
591be retrieved at the same time using the :func:`enumerate` function. ::
592
593 >>> for i, v in enumerate(['tic', 'tac', 'toe']):
594 ... print i, v
595 ...
596 0 tic
597 1 tac
598 2 toe
599
600To loop over two or more sequences at the same time, the entries can be paired
601with the :func:`zip` function. ::
602
603 >>> questions = ['name', 'quest', 'favorite color']
604 >>> answers = ['lancelot', 'the holy grail', 'blue']
605 >>> for q, a in zip(questions, answers):
Benjamin Petersonf9ef9882008-05-26 00:54:22 +0000606 ... print 'What is your {0}? It is {1}.'.format(q, a)
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000607 ...
Georg Brandl8ec7f652007-08-15 14:28:01 +0000608 What is your name? It is lancelot.
609 What is your quest? It is the holy grail.
610 What is your favorite color? It is blue.
611
612To loop over a sequence in reverse, first specify the sequence in a forward
613direction and then call the :func:`reversed` function. ::
614
615 >>> for i in reversed(xrange(1,10,2)):
616 ... print i
617 ...
618 9
619 7
620 5
621 3
622 1
623
624To loop over a sequence in sorted order, use the :func:`sorted` function which
625returns a new sorted list while leaving the source unaltered. ::
626
627 >>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
628 >>> for f in sorted(set(basket)):
629 ... print f
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000630 ...
Georg Brandl8ec7f652007-08-15 14:28:01 +0000631 apple
632 banana
633 orange
634 pear
635
Raymond Hettinger4c8d3922012-04-23 21:24:15 -0700636When looping through dictionaries, the key and corresponding value can be
637retrieved at the same time using the :meth:`iteritems` method. ::
638
639 >>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
640 >>> for k, v in knights.iteritems():
641 ... print k, v
642 ...
643 gallahad the pure
644 robin the brave
645
Chris Jerdonek0cffd6b2012-10-15 20:01:38 -0700646To change a sequence you are iterating over while inside the loop (for
647example to duplicate certain items), it is recommended that you first make
648a copy. Looping over a sequence does not implicitly make a copy. The slice
649notation makes this especially convenient::
650
651 >>> words = ['cat', 'window', 'defenestrate']
652 >>> for w in words[:]: # Loop over a slice copy of the entire list.
653 ... if len(w) > 6:
654 ... words.insert(0, w)
655 ...
656 >>> words
657 ['defenestrate', 'cat', 'window', 'defenestrate']
658
Georg Brandl8ec7f652007-08-15 14:28:01 +0000659
660.. _tut-conditions:
661
662More on Conditions
663==================
664
665The conditions used in ``while`` and ``if`` statements can contain any
666operators, not just comparisons.
667
668The comparison operators ``in`` and ``not in`` check whether a value occurs
669(does not occur) in a sequence. The operators ``is`` and ``is not`` compare
670whether two objects are really the same object; this only matters for mutable
671objects like lists. All comparison operators have the same priority, which is
672lower than that of all numerical operators.
673
674Comparisons can be chained. For example, ``a < b == c`` tests whether ``a`` is
675less than ``b`` and moreover ``b`` equals ``c``.
676
677Comparisons may be combined using the Boolean operators ``and`` and ``or``, and
678the outcome of a comparison (or of any other Boolean expression) may be negated
679with ``not``. These have lower priorities than comparison operators; between
680them, ``not`` has the highest priority and ``or`` the lowest, so that ``A and
681not B or C`` is equivalent to ``(A and (not B)) or C``. As always, parentheses
682can be used to express the desired composition.
683
684The Boolean operators ``and`` and ``or`` are so-called *short-circuit*
685operators: their arguments are evaluated from left to right, and evaluation
686stops as soon as the outcome is determined. For example, if ``A`` and ``C`` are
687true but ``B`` is false, ``A and B and C`` does not evaluate the expression
688``C``. When used as a general value and not as a Boolean, the return value of a
689short-circuit operator is the last evaluated argument.
690
691It is possible to assign the result of a comparison or other Boolean expression
692to a variable. For example, ::
693
694 >>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance'
695 >>> non_null = string1 or string2 or string3
696 >>> non_null
697 'Trondheim'
698
699Note that in Python, unlike C, assignment cannot occur inside expressions. C
700programmers may grumble about this, but it avoids a common class of problems
701encountered in C programs: typing ``=`` in an expression when ``==`` was
702intended.
703
704
705.. _tut-comparing:
706
707Comparing Sequences and Other Types
708===================================
709
710Sequence objects may be compared to other objects with the same sequence type.
711The comparison uses *lexicographical* ordering: first the first two items are
712compared, and if they differ this determines the outcome of the comparison; if
713they are equal, the next two items are compared, and so on, until either
714sequence is exhausted. If two items to be compared are themselves sequences of
715the same type, the lexicographical comparison is carried out recursively. If
716all items of two sequences compare equal, the sequences are considered equal.
717If one sequence is an initial sub-sequence of the other, the shorter sequence is
718the smaller (lesser) one. Lexicographical ordering for strings uses the ASCII
719ordering for individual characters. Some examples of comparisons between
720sequences of the same type::
721
722 (1, 2, 3) < (1, 2, 4)
723 [1, 2, 3] < [1, 2, 4]
724 'ABC' < 'C' < 'Pascal' < 'Python'
725 (1, 2, 3, 4) < (1, 2, 4)
726 (1, 2) < (1, 2, -1)
727 (1, 2, 3) == (1.0, 2.0, 3.0)
728 (1, 2, ('aa', 'ab')) < (1, 2, ('abc', 'a'), 4)
729
730Note that comparing objects of different types is legal. The outcome is
731deterministic but arbitrary: the types are ordered by their name. Thus, a list
732is always smaller than a string, a string is always smaller than a tuple, etc.
733[#]_ Mixed numeric types are compared according to their numeric value, so 0
734equals 0.0, etc.
735
736
737.. rubric:: Footnotes
738
739.. [#] The rules for comparing objects of different types should not be relied upon;
740 they may change in a future version of the language.
741