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