Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1 | .. _tut-structures: |
| 2 | |
| 3 | *************** |
| 4 | Data Structures |
| 5 | *************** |
| 6 | |
| 7 | This chapter describes some things you've learned about already in more detail, |
| 8 | and adds some new things as well. |
| 9 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 10 | .. _tut-morelists: |
| 11 | |
| 12 | More on Lists |
| 13 | ============= |
| 14 | |
| 15 | The list data type has some more methods. Here are all of the methods of list |
| 16 | objects: |
| 17 | |
| 18 | |
| 19 | .. method:: list.append(x) |
Christian Heimes | 4fbc72b | 2008-03-22 00:47:35 +0000 | [diff] [blame] | 20 | :noindex: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 21 | |
| 22 | Add an item to the end of the list; equivalent to ``a[len(a):] = [x]``. |
| 23 | |
| 24 | |
| 25 | .. method:: list.extend(L) |
Christian Heimes | 4fbc72b | 2008-03-22 00:47:35 +0000 | [diff] [blame] | 26 | :noindex: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 27 | |
| 28 | Extend the list by appending all the items in the given list; equivalent to |
| 29 | ``a[len(a):] = L``. |
| 30 | |
| 31 | |
| 32 | .. method:: list.insert(i, x) |
Christian Heimes | 4fbc72b | 2008-03-22 00:47:35 +0000 | [diff] [blame] | 33 | :noindex: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 34 | |
| 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 Heimes | 4fbc72b | 2008-03-22 00:47:35 +0000 | [diff] [blame] | 41 | :noindex: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 42 | |
| 43 | Remove the first item from the list whose value is *x*. It is an error if there |
| 44 | is no such item. |
| 45 | |
| 46 | |
| 47 | .. method:: list.pop([i]) |
Christian Heimes | 4fbc72b | 2008-03-22 00:47:35 +0000 | [diff] [blame] | 48 | :noindex: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 49 | |
| 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 Heimes | 4fbc72b | 2008-03-22 00:47:35 +0000 | [diff] [blame] | 58 | :noindex: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 59 | |
| 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 Heimes | 4fbc72b | 2008-03-22 00:47:35 +0000 | [diff] [blame] | 65 | :noindex: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 66 | |
| 67 | Return the number of times *x* appears in the list. |
| 68 | |
| 69 | |
| 70 | .. method:: list.sort() |
Christian Heimes | 4fbc72b | 2008-03-22 00:47:35 +0000 | [diff] [blame] | 71 | :noindex: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 72 | |
| 73 | Sort the items of the list, in place. |
| 74 | |
| 75 | |
| 76 | .. method:: list.reverse() |
Christian Heimes | 4fbc72b | 2008-03-22 00:47:35 +0000 | [diff] [blame] | 77 | :noindex: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 78 | |
| 79 | Reverse the elements of the list, in place. |
| 80 | |
| 81 | An example that uses most of the list methods:: |
| 82 | |
| 83 | >>> a = [66.25, 333, 333, 1, 1234.5] |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 84 | >>> print(a.count(333), a.count(66.25), a.count('x')) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 85 | 2 1 0 |
| 86 | >>> a.insert(2, -1) |
| 87 | >>> a.append(333) |
| 88 | >>> a |
| 89 | [66.25, 333, -1, 333, 1, 1234.5, 333] |
| 90 | >>> a.index(333) |
| 91 | 1 |
| 92 | >>> a.remove(333) |
| 93 | >>> a |
| 94 | [66.25, -1, 333, 1, 1234.5, 333] |
| 95 | >>> a.reverse() |
| 96 | >>> a |
| 97 | [333, 1234.5, 1, 333, -1, 66.25] |
| 98 | >>> a.sort() |
| 99 | >>> a |
| 100 | [-1, 1, 66.25, 333, 333, 1234.5] |
| 101 | |
| 102 | |
| 103 | .. _tut-lists-as-stacks: |
| 104 | |
| 105 | Using Lists as Stacks |
| 106 | --------------------- |
| 107 | |
| 108 | .. sectionauthor:: Ka-Ping Yee <ping@lfw.org> |
| 109 | |
| 110 | |
| 111 | The list methods make it very easy to use a list as a stack, where the last |
| 112 | element added is the first element retrieved ("last-in, first-out"). To add an |
| 113 | item to the top of the stack, use :meth:`append`. To retrieve an item from the |
| 114 | top of the stack, use :meth:`pop` without an explicit index. For example:: |
| 115 | |
| 116 | >>> stack = [3, 4, 5] |
| 117 | >>> stack.append(6) |
| 118 | >>> stack.append(7) |
| 119 | >>> stack |
| 120 | [3, 4, 5, 6, 7] |
| 121 | >>> stack.pop() |
| 122 | 7 |
| 123 | >>> stack |
| 124 | [3, 4, 5, 6] |
| 125 | >>> stack.pop() |
| 126 | 6 |
| 127 | >>> stack.pop() |
| 128 | 5 |
| 129 | >>> stack |
| 130 | [3, 4] |
| 131 | |
| 132 | |
| 133 | .. _tut-lists-as-queues: |
| 134 | |
| 135 | Using Lists as Queues |
| 136 | --------------------- |
| 137 | |
| 138 | .. sectionauthor:: Ka-Ping Yee <ping@lfw.org> |
| 139 | |
| 140 | |
| 141 | You can also use a list conveniently as a queue, where the first element added |
| 142 | is the first element retrieved ("first-in, first-out"). To add an item to the |
| 143 | back of the queue, use :meth:`append`. To retrieve an item from the front of |
| 144 | the queue, use :meth:`pop` with ``0`` as the index. For example:: |
| 145 | |
| 146 | >>> queue = ["Eric", "John", "Michael"] |
| 147 | >>> queue.append("Terry") # Terry arrives |
| 148 | >>> queue.append("Graham") # Graham arrives |
| 149 | >>> queue.pop(0) |
| 150 | 'Eric' |
| 151 | >>> queue.pop(0) |
| 152 | 'John' |
| 153 | >>> queue |
| 154 | ['Michael', 'Terry', 'Graham'] |
| 155 | |
| 156 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 157 | List Comprehensions |
| 158 | ------------------- |
| 159 | |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 160 | List comprehensions provide a concise way to create lists from sequences. |
| 161 | Common applications are to make lists where each element is the result of |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 162 | some operations applied to each member of the sequence, or to create a |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 163 | subsequence of those elements that satisfy a certain condition. |
| 164 | |
| 165 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 166 | Each list comprehension consists of an expression followed by a :keyword:`for` |
| 167 | clause, then zero or more :keyword:`for` or :keyword:`if` clauses. The result |
| 168 | will be a list resulting from evaluating the expression in the context of the |
| 169 | :keyword:`for` and :keyword:`if` clauses which follow it. If the expression |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 170 | would evaluate to a tuple, it must be parenthesized. |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 171 | |
| 172 | Here we take a list of numbers and return a list of three times each number:: |
| 173 | |
| 174 | >>> vec = [2, 4, 6] |
| 175 | >>> [3*x for x in vec] |
| 176 | [6, 12, 18] |
| 177 | |
| 178 | Now we get a little fancier:: |
| 179 | |
Georg Brandl | e4ac750 | 2007-09-03 07:10:24 +0000 | [diff] [blame] | 180 | >>> [[x, x**2] for x in vec] |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 181 | [[2, 4], [4, 16], [6, 36]] |
| 182 | |
| 183 | Here we apply a method call to each item in a sequence:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 184 | |
| 185 | >>> freshfruit = [' banana', ' loganberry ', 'passion fruit '] |
| 186 | >>> [weapon.strip() for weapon in freshfruit] |
| 187 | ['banana', 'loganberry', 'passion fruit'] |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 188 | |
Georg Brandl | e4ac750 | 2007-09-03 07:10:24 +0000 | [diff] [blame] | 189 | Using the :keyword:`if` clause we can filter the stream:: |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 190 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 191 | >>> [3*x for x in vec if x > 3] |
| 192 | [12, 18] |
| 193 | >>> [3*x for x in vec if x < 2] |
| 194 | [] |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 195 | |
| 196 | Tuples can often be created without their parentheses, but not here:: |
| 197 | |
Georg Brandl | a1c6a1c | 2009-01-03 21:26:05 +0000 | [diff] [blame] | 198 | >>> [x, x**2 for x in vec] # error - parens required for tuples |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 199 | File "<stdin>", line 1, in ? |
| 200 | [x, x**2 for x in vec] |
| 201 | ^ |
| 202 | SyntaxError: invalid syntax |
| 203 | >>> [(x, x**2) for x in vec] |
| 204 | [(2, 4), (4, 16), (6, 36)] |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 205 | |
Georg Brandl | e4ac750 | 2007-09-03 07:10:24 +0000 | [diff] [blame] | 206 | Here are some nested for loops and other fancy behavior:: |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 207 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 208 | >>> vec1 = [2, 4, 6] |
| 209 | >>> vec2 = [4, 3, -9] |
| 210 | >>> [x*y for x in vec1 for y in vec2] |
| 211 | [8, 6, -18, 16, 12, -36, 24, 18, -54] |
| 212 | >>> [x+y for x in vec1 for y in vec2] |
| 213 | [6, 5, -7, 8, 7, -5, 10, 9, -3] |
| 214 | >>> [vec1[i]*vec2[i] for i in range(len(vec1))] |
| 215 | [8, 12, -54] |
| 216 | |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 217 | List comprehensions can be applied to complex expressions and nested functions:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 218 | |
Georg Brandl | f694518 | 2008-02-01 11:56:49 +0000 | [diff] [blame] | 219 | >>> [str(round(355/113, i)) for i in range(1, 6)] |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 220 | ['3.1', '3.14', '3.142', '3.1416', '3.14159'] |
| 221 | |
| 222 | |
Christian Heimes | 0449f63 | 2007-12-15 01:27:15 +0000 | [diff] [blame] | 223 | Nested List Comprehensions |
| 224 | -------------------------- |
| 225 | |
| 226 | If you've got the stomach for it, list comprehensions can be nested. They are a |
| 227 | powerful tool but -- like all powerful tools -- they need to be used carefully, |
| 228 | if at all. |
| 229 | |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 230 | Consider the following example of a 3x3 matrix held as a list containing three |
Christian Heimes | 0449f63 | 2007-12-15 01:27:15 +0000 | [diff] [blame] | 231 | lists, one list per row:: |
| 232 | |
| 233 | >>> mat = [ |
| 234 | ... [1, 2, 3], |
| 235 | ... [4, 5, 6], |
| 236 | ... [7, 8, 9], |
| 237 | ... ] |
| 238 | |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 239 | Now, if you wanted to swap rows and columns, you could use a list |
Christian Heimes | 0449f63 | 2007-12-15 01:27:15 +0000 | [diff] [blame] | 240 | comprehension:: |
| 241 | |
Neal Norwitz | 752abd0 | 2008-05-13 04:55:24 +0000 | [diff] [blame] | 242 | >>> print([[row[i] for row in mat] for i in [0, 1, 2]]) |
Christian Heimes | 0449f63 | 2007-12-15 01:27:15 +0000 | [diff] [blame] | 243 | [[1, 4, 7], [2, 5, 8], [3, 6, 9]] |
| 244 | |
| 245 | Special care has to be taken for the *nested* list comprehension: |
| 246 | |
| 247 | To avoid apprehension when nesting list comprehensions, read from right to |
| 248 | left. |
| 249 | |
| 250 | A more verbose version of this snippet shows the flow explicitly:: |
| 251 | |
| 252 | for i in [0, 1, 2]: |
| 253 | for row in mat: |
Neal Norwitz | 752abd0 | 2008-05-13 04:55:24 +0000 | [diff] [blame] | 254 | print(row[i], end="") |
Benjamin Peterson | bfc644b | 2008-07-05 23:39:56 +0000 | [diff] [blame] | 255 | print() |
Christian Heimes | 0449f63 | 2007-12-15 01:27:15 +0000 | [diff] [blame] | 256 | |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 257 | In real world, you should prefer builtin functions to complex flow statements. |
Christian Heimes | 0449f63 | 2007-12-15 01:27:15 +0000 | [diff] [blame] | 258 | The :func:`zip` function would do a great job for this use case:: |
| 259 | |
Georg Brandl | 409c9d7 | 2008-08-08 06:44:14 +0000 | [diff] [blame] | 260 | >>> list(zip(*mat)) |
Christian Heimes | 0449f63 | 2007-12-15 01:27:15 +0000 | [diff] [blame] | 261 | [(1, 4, 7), (2, 5, 8), (3, 6, 9)] |
| 262 | |
| 263 | See :ref:`tut-unpacking-arguments` for details on the asterisk in this line. |
| 264 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 265 | .. _tut-del: |
| 266 | |
| 267 | The :keyword:`del` statement |
| 268 | ============================ |
| 269 | |
| 270 | There is a way to remove an item from a list given its index instead of its |
| 271 | value: the :keyword:`del` statement. This differs from the :meth:`pop` method |
| 272 | which returns a value. The :keyword:`del` statement can also be used to remove |
| 273 | slices from a list or clear the entire list (which we did earlier by assignment |
| 274 | of an empty list to the slice). For example:: |
| 275 | |
| 276 | >>> a = [-1, 1, 66.25, 333, 333, 1234.5] |
| 277 | >>> del a[0] |
| 278 | >>> a |
| 279 | [1, 66.25, 333, 333, 1234.5] |
| 280 | >>> del a[2:4] |
| 281 | >>> a |
| 282 | [1, 66.25, 1234.5] |
| 283 | >>> del a[:] |
| 284 | >>> a |
| 285 | [] |
| 286 | |
| 287 | :keyword:`del` can also be used to delete entire variables:: |
| 288 | |
| 289 | >>> del a |
| 290 | |
| 291 | Referencing the name ``a`` hereafter is an error (at least until another value |
| 292 | is assigned to it). We'll find other uses for :keyword:`del` later. |
| 293 | |
| 294 | |
Georg Brandl | 5d955ed | 2008-09-13 17:18:21 +0000 | [diff] [blame] | 295 | .. _tut-tuples: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 296 | |
Christian Heimes | 5b5e81c | 2007-12-31 16:14:33 +0000 | [diff] [blame] | 297 | Tuples and Sequences |
| 298 | ==================== |
| 299 | |
| 300 | We saw that lists and strings have many common properties, such as indexing and |
| 301 | slicing operations. They are two examples of *sequence* data types (see |
| 302 | :ref:`typesseq`). Since Python is an evolving language, other sequence data |
| 303 | types may be added. There is also another standard sequence data type: the |
| 304 | *tuple*. |
| 305 | |
| 306 | A tuple consists of a number of values separated by commas, for instance:: |
| 307 | |
| 308 | >>> t = 12345, 54321, 'hello!' |
| 309 | >>> t[0] |
| 310 | 12345 |
| 311 | >>> t |
| 312 | (12345, 54321, 'hello!') |
| 313 | >>> # Tuples may be nested: |
| 314 | ... u = t, (1, 2, 3, 4, 5) |
| 315 | >>> u |
| 316 | ((12345, 54321, 'hello!'), (1, 2, 3, 4, 5)) |
| 317 | |
| 318 | As you see, on output tuples are always enclosed in parentheses, so that nested |
| 319 | tuples are interpreted correctly; they may be input with or without surrounding |
| 320 | parentheses, although often parentheses are necessary anyway (if the tuple is |
| 321 | part of a larger expression). |
| 322 | |
| 323 | Tuples have many uses. For example: (x, y) coordinate pairs, employee records |
| 324 | from a database, etc. Tuples, like strings, are immutable: it is not possible |
| 325 | to assign to the individual items of a tuple (you can simulate much of the same |
| 326 | effect with slicing and concatenation, though). It is also possible to create |
| 327 | tuples which contain mutable objects, such as lists. |
| 328 | |
| 329 | A special problem is the construction of tuples containing 0 or 1 items: the |
| 330 | syntax has some extra quirks to accommodate these. Empty tuples are constructed |
| 331 | by an empty pair of parentheses; a tuple with one item is constructed by |
| 332 | following a value with a comma (it is not sufficient to enclose a single value |
| 333 | in parentheses). Ugly, but effective. For example:: |
| 334 | |
| 335 | >>> empty = () |
| 336 | >>> singleton = 'hello', # <-- note trailing comma |
| 337 | >>> len(empty) |
| 338 | 0 |
| 339 | >>> len(singleton) |
| 340 | 1 |
| 341 | >>> singleton |
| 342 | ('hello',) |
| 343 | |
| 344 | The statement ``t = 12345, 54321, 'hello!'`` is an example of *tuple packing*: |
| 345 | the values ``12345``, ``54321`` and ``'hello!'`` are packed together in a tuple. |
| 346 | The reverse operation is also possible:: |
| 347 | |
| 348 | >>> x, y, z = t |
| 349 | |
| 350 | This is called, appropriately enough, *sequence unpacking*. Sequence unpacking |
| 351 | requires the list of variables on the left to have the same number of elements |
| 352 | as the length of the sequence. Note that multiple assignment is really just a |
| 353 | combination of tuple packing and sequence unpacking! |
| 354 | |
| 355 | There is a small bit of asymmetry here: packing multiple values always creates |
| 356 | a tuple, and unpacking works for any sequence. |
| 357 | |
| 358 | .. XXX Add a bit on the difference between tuples and lists. |
| 359 | |
| 360 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 361 | .. _tut-sets: |
| 362 | |
| 363 | Sets |
| 364 | ==== |
| 365 | |
| 366 | Python also includes a data type for *sets*. A set is an unordered collection |
| 367 | with no duplicate elements. Basic uses include membership testing and |
| 368 | eliminating duplicate entries. Set objects also support mathematical operations |
| 369 | like union, intersection, difference, and symmetric difference. |
| 370 | |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 371 | Curly braces or the :func:`set` function can be use to create sets. Note: |
| 372 | To create an empty set you have to use set(), not {}; the latter creates |
| 373 | an empty dictionary, a data structure that we discuss in the next section. |
| 374 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 375 | Here is a brief demonstration:: |
| 376 | |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 377 | >>> basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'} |
| 378 | >>> print(basket) |
Georg Brandl | 2080ea5 | 2008-12-07 15:17:53 +0000 | [diff] [blame] | 379 | {'orange', 'banana', 'pear', 'apple'} |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 380 | >>> fruit = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana'] |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 381 | >>> fruit = set(basket) # create a set without duplicates |
| 382 | >>> fruit |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 383 | {'orange', 'pear', 'apple', 'banana'} |
Georg Brandl | f694518 | 2008-02-01 11:56:49 +0000 | [diff] [blame] | 384 | >>> fruit = {'orange', 'apple'} # {} syntax is equivalent to [] for lists |
| 385 | >>> fruit |
| 386 | {'orange', 'apple'} |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 387 | >>> 'orange' in fruit # fast membership testing |
| 388 | True |
| 389 | >>> 'crabgrass' in fruit |
| 390 | False |
| 391 | |
| 392 | >>> # Demonstrate set operations on unique letters from two words |
| 393 | ... |
| 394 | >>> a = set('abracadabra') |
| 395 | >>> b = set('alacazam') |
| 396 | >>> a # unique letters in a |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 397 | {'a', 'r', 'b', 'c', 'd'} |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 398 | >>> a - b # letters in a but not in b |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 399 | {'r', 'd', 'b'} |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 400 | >>> a | b # letters in either a or b |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 401 | {'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'} |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 402 | >>> a & b # letters in both a and b |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 403 | {'a', 'c'} |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 404 | >>> a ^ b # letters in a or b but not both |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 405 | {'r', 'd', 'b', 'm', 'z', 'l'} |
| 406 | |
Georg Brandl | f694518 | 2008-02-01 11:56:49 +0000 | [diff] [blame] | 407 | Like for lists, there is a set comprehension syntax:: |
| 408 | |
| 409 | >>> a = {x for x in 'abracadabra' if x not in 'abc'} |
| 410 | >>> a |
| 411 | {'r', 'd'} |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 412 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 413 | |
| 414 | |
| 415 | .. _tut-dictionaries: |
| 416 | |
| 417 | Dictionaries |
| 418 | ============ |
| 419 | |
| 420 | Another useful data type built into Python is the *dictionary* (see |
| 421 | :ref:`typesmapping`). Dictionaries are sometimes found in other languages as |
| 422 | "associative memories" or "associative arrays". Unlike sequences, which are |
| 423 | indexed by a range of numbers, dictionaries are indexed by *keys*, which can be |
| 424 | any immutable type; strings and numbers can always be keys. Tuples can be used |
| 425 | as keys if they contain only strings, numbers, or tuples; if a tuple contains |
| 426 | any mutable object either directly or indirectly, it cannot be used as a key. |
| 427 | You can't use lists as keys, since lists can be modified in place using index |
| 428 | assignments, slice assignments, or methods like :meth:`append` and |
| 429 | :meth:`extend`. |
| 430 | |
| 431 | It is best to think of a dictionary as an unordered set of *key: value* pairs, |
| 432 | with the requirement that the keys are unique (within one dictionary). A pair of |
| 433 | braces creates an empty dictionary: ``{}``. Placing a comma-separated list of |
| 434 | key:value pairs within the braces adds initial key:value pairs to the |
| 435 | dictionary; this is also the way dictionaries are written on output. |
| 436 | |
| 437 | The main operations on a dictionary are storing a value with some key and |
| 438 | extracting the value given the key. It is also possible to delete a key:value |
| 439 | pair with ``del``. If you store using a key that is already in use, the old |
| 440 | value associated with that key is forgotten. It is an error to extract a value |
| 441 | using a non-existent key. |
| 442 | |
Georg Brandl | abffe71 | 2008-12-15 08:28:37 +0000 | [diff] [blame] | 443 | Performing ``list(d.keys())`` on a dictionary returns a list of all the keys |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 444 | used in the dictionary, in arbitrary order (if you want it sorted, just apply |
Georg Brandl | abffe71 | 2008-12-15 08:28:37 +0000 | [diff] [blame] | 445 | the :meth:`sorted` function instead). To check whether a single key is |
Collin Winter | 19ab2bd | 2007-09-10 00:20:46 +0000 | [diff] [blame] | 446 | in the dictionary, use the :keyword:`in` keyword. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 447 | |
| 448 | Here is a small example using a dictionary:: |
| 449 | |
| 450 | >>> tel = {'jack': 4098, 'sape': 4139} |
| 451 | >>> tel['guido'] = 4127 |
| 452 | >>> tel |
| 453 | {'sape': 4139, 'guido': 4127, 'jack': 4098} |
| 454 | >>> tel['jack'] |
| 455 | 4098 |
| 456 | >>> del tel['sape'] |
| 457 | >>> tel['irv'] = 4127 |
| 458 | >>> tel |
| 459 | {'guido': 4127, 'irv': 4127, 'jack': 4098} |
Neal Norwitz | e0906d1 | 2007-08-31 03:46:28 +0000 | [diff] [blame] | 460 | >>> list(tel.keys()) |
Georg Brandl | abffe71 | 2008-12-15 08:28:37 +0000 | [diff] [blame] | 461 | ['irv', 'guido', 'jack'] |
| 462 | >>> sorted(tel.keys()) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 463 | ['guido', 'irv', 'jack'] |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 464 | >>> 'guido' in tel |
| 465 | True |
Neal Norwitz | e0906d1 | 2007-08-31 03:46:28 +0000 | [diff] [blame] | 466 | >>> 'jack' not in tel |
| 467 | False |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 468 | |
| 469 | The :func:`dict` constructor builds dictionaries directly from lists of |
| 470 | key-value pairs stored as tuples. When the pairs form a pattern, list |
| 471 | comprehensions can compactly specify the key-value list. :: |
| 472 | |
| 473 | >>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)]) |
| 474 | {'sape': 4139, 'jack': 4098, 'guido': 4127} |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 475 | |
Georg Brandl | f694518 | 2008-02-01 11:56:49 +0000 | [diff] [blame] | 476 | In addition, dict comprehensions can be used to create dictionaries from |
| 477 | arbitrary key and value expressions:: |
| 478 | |
| 479 | >>> {x: x**2 for x in (2, 4, 6)} |
| 480 | {2: 4, 4: 16, 6: 36} |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 481 | |
| 482 | When the keys are simple strings, it is sometimes easier to specify pairs using |
| 483 | keyword arguments:: |
| 484 | |
| 485 | >>> dict(sape=4139, guido=4127, jack=4098) |
| 486 | {'sape': 4139, 'jack': 4098, 'guido': 4127} |
| 487 | |
| 488 | |
Georg Brandl | f694518 | 2008-02-01 11:56:49 +0000 | [diff] [blame] | 489 | .. XXX Find out the right way to do these DUBOIS |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 490 | .. _tut-loopidioms: |
| 491 | |
| 492 | Looping Techniques |
| 493 | ================== |
| 494 | |
| 495 | When looping through dictionaries, the key and corresponding value can be |
Neal Norwitz | e0906d1 | 2007-08-31 03:46:28 +0000 | [diff] [blame] | 496 | retrieved at the same time using the :meth:`items` method. :: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 497 | |
| 498 | >>> knights = {'gallahad': 'the pure', 'robin': 'the brave'} |
Neal Norwitz | e0906d1 | 2007-08-31 03:46:28 +0000 | [diff] [blame] | 499 | >>> for k, v in knights.items(): |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 500 | ... print(k, v) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 501 | ... |
| 502 | gallahad the pure |
| 503 | robin the brave |
| 504 | |
| 505 | When looping through a sequence, the position index and corresponding value can |
| 506 | be retrieved at the same time using the :func:`enumerate` function. :: |
| 507 | |
| 508 | >>> for i, v in enumerate(['tic', 'tac', 'toe']): |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 509 | ... print(i, v) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 510 | ... |
| 511 | 0 tic |
| 512 | 1 tac |
| 513 | 2 toe |
| 514 | |
| 515 | To loop over two or more sequences at the same time, the entries can be paired |
| 516 | with the :func:`zip` function. :: |
| 517 | |
| 518 | >>> questions = ['name', 'quest', 'favorite color'] |
| 519 | >>> answers = ['lancelot', 'the holy grail', 'blue'] |
| 520 | >>> for q, a in zip(questions, answers): |
Benjamin Peterson | e6f0063 | 2008-05-26 01:03:56 +0000 | [diff] [blame] | 521 | ... print('What is your {0}? It is {1}.'.format(q, a)) |
Georg Brandl | 06788c9 | 2009-01-03 21:31:47 +0000 | [diff] [blame] | 522 | ... |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 523 | What is your name? It is lancelot. |
| 524 | What is your quest? It is the holy grail. |
| 525 | What is your favorite color? It is blue. |
| 526 | |
| 527 | To loop over a sequence in reverse, first specify the sequence in a forward |
| 528 | direction and then call the :func:`reversed` function. :: |
| 529 | |
Georg Brandl | e4ac750 | 2007-09-03 07:10:24 +0000 | [diff] [blame] | 530 | >>> for i in reversed(range(1, 10, 2)): |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 531 | ... print(i) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 532 | ... |
| 533 | 9 |
| 534 | 7 |
| 535 | 5 |
| 536 | 3 |
| 537 | 1 |
| 538 | |
| 539 | To loop over a sequence in sorted order, use the :func:`sorted` function which |
| 540 | returns a new sorted list while leaving the source unaltered. :: |
| 541 | |
| 542 | >>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana'] |
| 543 | >>> for f in sorted(set(basket)): |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 544 | ... print(f) |
Georg Brandl | 06788c9 | 2009-01-03 21:31:47 +0000 | [diff] [blame] | 545 | ... |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 546 | apple |
| 547 | banana |
| 548 | orange |
| 549 | pear |
| 550 | |
| 551 | |
| 552 | .. _tut-conditions: |
| 553 | |
| 554 | More on Conditions |
| 555 | ================== |
| 556 | |
| 557 | The conditions used in ``while`` and ``if`` statements can contain any |
| 558 | operators, not just comparisons. |
| 559 | |
| 560 | The comparison operators ``in`` and ``not in`` check whether a value occurs |
| 561 | (does not occur) in a sequence. The operators ``is`` and ``is not`` compare |
| 562 | whether two objects are really the same object; this only matters for mutable |
| 563 | objects like lists. All comparison operators have the same priority, which is |
| 564 | lower than that of all numerical operators. |
| 565 | |
| 566 | Comparisons can be chained. For example, ``a < b == c`` tests whether ``a`` is |
| 567 | less than ``b`` and moreover ``b`` equals ``c``. |
| 568 | |
| 569 | Comparisons may be combined using the Boolean operators ``and`` and ``or``, and |
| 570 | the outcome of a comparison (or of any other Boolean expression) may be negated |
| 571 | with ``not``. These have lower priorities than comparison operators; between |
| 572 | them, ``not`` has the highest priority and ``or`` the lowest, so that ``A and |
| 573 | not B or C`` is equivalent to ``(A and (not B)) or C``. As always, parentheses |
| 574 | can be used to express the desired composition. |
| 575 | |
| 576 | The Boolean operators ``and`` and ``or`` are so-called *short-circuit* |
| 577 | operators: their arguments are evaluated from left to right, and evaluation |
| 578 | stops as soon as the outcome is determined. For example, if ``A`` and ``C`` are |
| 579 | true but ``B`` is false, ``A and B and C`` does not evaluate the expression |
| 580 | ``C``. When used as a general value and not as a Boolean, the return value of a |
| 581 | short-circuit operator is the last evaluated argument. |
| 582 | |
| 583 | It is possible to assign the result of a comparison or other Boolean expression |
| 584 | to a variable. For example, :: |
| 585 | |
| 586 | >>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance' |
| 587 | >>> non_null = string1 or string2 or string3 |
| 588 | >>> non_null |
| 589 | 'Trondheim' |
| 590 | |
| 591 | Note that in Python, unlike C, assignment cannot occur inside expressions. C |
| 592 | programmers may grumble about this, but it avoids a common class of problems |
| 593 | encountered in C programs: typing ``=`` in an expression when ``==`` was |
| 594 | intended. |
| 595 | |
| 596 | |
| 597 | .. _tut-comparing: |
| 598 | |
| 599 | Comparing Sequences and Other Types |
| 600 | =================================== |
| 601 | |
| 602 | Sequence objects may be compared to other objects with the same sequence type. |
| 603 | The comparison uses *lexicographical* ordering: first the first two items are |
| 604 | compared, and if they differ this determines the outcome of the comparison; if |
| 605 | they are equal, the next two items are compared, and so on, until either |
| 606 | sequence is exhausted. If two items to be compared are themselves sequences of |
| 607 | the same type, the lexicographical comparison is carried out recursively. If |
| 608 | all items of two sequences compare equal, the sequences are considered equal. |
| 609 | If one sequence is an initial sub-sequence of the other, the shorter sequence is |
| 610 | the smaller (lesser) one. Lexicographical ordering for strings uses the ASCII |
| 611 | ordering for individual characters. Some examples of comparisons between |
| 612 | sequences of the same type:: |
| 613 | |
| 614 | (1, 2, 3) < (1, 2, 4) |
| 615 | [1, 2, 3] < [1, 2, 4] |
| 616 | 'ABC' < 'C' < 'Pascal' < 'Python' |
| 617 | (1, 2, 3, 4) < (1, 2, 4) |
| 618 | (1, 2) < (1, 2, -1) |
| 619 | (1, 2, 3) == (1.0, 2.0, 3.0) |
| 620 | (1, 2, ('aa', 'ab')) < (1, 2, ('abc', 'a'), 4) |
| 621 | |
Georg Brandl | 9f2c39a | 2007-10-08 14:08:36 +0000 | [diff] [blame] | 622 | Note that comparing objects of different types with ``<`` or ``>`` is legal |
| 623 | provided that the objects have appropriate comparison methods. For example, |
| 624 | mixed numeric types are compared according to their numeric value, so 0 equals |
| 625 | 0.0, etc. Otherwise, rather than providing an arbitrary ordering, the |
| 626 | interpreter will raise a :exc:`TypeError` exception. |