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