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