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