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