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 |
| 174 | numbers not divisible by 2 and 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 | |
| 232 | .. versionadded:: 2.3 |
| 233 | |
| 234 | |
| 235 | List Comprehensions |
| 236 | ------------------- |
| 237 | |
Ezio Melotti | 4a72d1a | 2011-12-13 14:50:21 +0200 | [diff] [blame] | 238 | List comprehensions provide a concise way to create lists. |
| 239 | Common applications are to make new lists where each element is the result of |
| 240 | some operations applied to each member of another sequence or iterable, or to |
| 241 | create a subsequence of those elements that satisfy a certain condition. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 242 | |
Ezio Melotti | 4a72d1a | 2011-12-13 14:50:21 +0200 | [diff] [blame] | 243 | For example, assume we want to create a list of squares, like:: |
| 244 | |
| 245 | >>> squares = [] |
| 246 | >>> for x in range(10): |
| 247 | ... squares.append(x**2) |
| 248 | ... |
| 249 | >>> squares |
| 250 | [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] |
| 251 | |
| 252 | We can obtain the same result with:: |
| 253 | |
| 254 | squares = [x**2 for x in range(10)] |
| 255 | |
| 256 | This is also equivalent to ``squares = map(lambda x: x**2, range(10))``, |
| 257 | but it's more concise and readable. |
| 258 | |
| 259 | A list comprehension consists of brackets containing an expression followed |
| 260 | by a :keyword:`for` clause, then zero or more :keyword:`for` or :keyword:`if` |
| 261 | clauses. The result will be a new list resulting from evaluating the expression |
| 262 | in the context of the :keyword:`for` and :keyword:`if` clauses which follow it. |
| 263 | For example, this listcomp combines the elements of two lists if they are not |
| 264 | equal:: |
| 265 | |
| 266 | >>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y] |
| 267 | [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)] |
| 268 | |
| 269 | and it's equivalent to: |
| 270 | |
| 271 | >>> combs = [] |
| 272 | >>> for x in [1,2,3]: |
| 273 | ... for y in [3,1,4]: |
| 274 | ... if x != y: |
| 275 | ... combs.append((x, y)) |
| 276 | ... |
| 277 | >>> combs |
| 278 | [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)] |
| 279 | |
| 280 | Note how the order of the :keyword:`for` and :keyword:`if` statements is the |
| 281 | same in both these snippets. |
| 282 | |
| 283 | If the expression is a tuple (e.g. the ``(x, y)`` in the previous example), |
| 284 | it must be parenthesized. :: |
| 285 | |
| 286 | >>> vec = [-4, -2, 0, 2, 4] |
| 287 | >>> # create a new list with the values doubled |
| 288 | >>> [x*2 for x in vec] |
| 289 | [-8, -4, 0, 4, 8] |
| 290 | >>> # filter the list to exclude negative numbers |
| 291 | >>> [x for x in vec if x >= 0] |
| 292 | [0, 2, 4] |
| 293 | >>> # apply a function to all the elements |
| 294 | >>> [abs(x) for x in vec] |
| 295 | [4, 2, 0, 2, 4] |
| 296 | >>> # call a method on each element |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 297 | >>> freshfruit = [' banana', ' loganberry ', 'passion fruit '] |
| 298 | >>> [weapon.strip() for weapon in freshfruit] |
| 299 | ['banana', 'loganberry', 'passion fruit'] |
Ezio Melotti | 4a72d1a | 2011-12-13 14:50:21 +0200 | [diff] [blame] | 300 | >>> # create a list of 2-tuples like (number, square) |
| 301 | >>> [(x, x**2) for x in range(6)] |
| 302 | [(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)] |
| 303 | >>> # the tuple must be parenthesized, otherwise an error is raised |
| 304 | >>> [x, x**2 for x in range(6)] |
| 305 | File "<stdin>", line 1 |
| 306 | [x, x**2 for x in range(6)] |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 307 | ^ |
| 308 | SyntaxError: invalid syntax |
Ezio Melotti | 4a72d1a | 2011-12-13 14:50:21 +0200 | [diff] [blame] | 309 | >>> # flatten a list using a listcomp with two 'for' |
| 310 | >>> vec = [[1,2,3], [4,5,6], [7,8,9]] |
| 311 | >>> [num for elem in vec for num in elem] |
| 312 | [1, 2, 3, 4, 5, 6, 7, 8, 9] |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 313 | |
Ezio Melotti | 4a72d1a | 2011-12-13 14:50:21 +0200 | [diff] [blame] | 314 | List comprehensions can contain complex expressions and nested functions:: |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 315 | |
Ezio Melotti | 4a72d1a | 2011-12-13 14:50:21 +0200 | [diff] [blame] | 316 | >>> from math import pi |
| 317 | >>> [str(round(pi, i)) for i in range(1, 6)] |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 318 | ['3.1', '3.14', '3.142', '3.1416', '3.14159'] |
| 319 | |
| 320 | |
Georg Brandl | adbda84 | 2007-12-14 19:03:36 +0000 | [diff] [blame] | 321 | Nested List Comprehensions |
Ezio Melotti | 4a72d1a | 2011-12-13 14:50:21 +0200 | [diff] [blame] | 322 | '''''''''''''''''''''''''' |
Georg Brandl | adbda84 | 2007-12-14 19:03:36 +0000 | [diff] [blame] | 323 | |
Ezio Melotti | 4a72d1a | 2011-12-13 14:50:21 +0200 | [diff] [blame] | 324 | The initial expression in a list comprehension can be any arbitrary expression, |
| 325 | including another list comprehension. |
Georg Brandl | adbda84 | 2007-12-14 19:03:36 +0000 | [diff] [blame] | 326 | |
Ezio Melotti | 4a72d1a | 2011-12-13 14:50:21 +0200 | [diff] [blame] | 327 | Consider the following example of a 3x4 matrix implemented as a list of |
| 328 | 3 lists of length 4:: |
Georg Brandl | adbda84 | 2007-12-14 19:03:36 +0000 | [diff] [blame] | 329 | |
Ezio Melotti | 4a72d1a | 2011-12-13 14:50:21 +0200 | [diff] [blame] | 330 | >>> matrix = [ |
| 331 | ... [1, 2, 3, 4], |
| 332 | ... [5, 6, 7, 8], |
| 333 | ... [9, 10, 11, 12], |
| 334 | ... ] |
Georg Brandl | adbda84 | 2007-12-14 19:03:36 +0000 | [diff] [blame] | 335 | |
Ezio Melotti | 4a72d1a | 2011-12-13 14:50:21 +0200 | [diff] [blame] | 336 | The following list comprehension will transpose rows and columns:: |
Georg Brandl | adbda84 | 2007-12-14 19:03:36 +0000 | [diff] [blame] | 337 | |
Ezio Melotti | 4a72d1a | 2011-12-13 14:50:21 +0200 | [diff] [blame] | 338 | >>> [[row[i] for row in matrix] for i in range(4)] |
| 339 | [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]] |
Georg Brandl | adbda84 | 2007-12-14 19:03:36 +0000 | [diff] [blame] | 340 | |
Ezio Melotti | 4a72d1a | 2011-12-13 14:50:21 +0200 | [diff] [blame] | 341 | As we saw in the previous section, the nested listcomp is evaluated in |
| 342 | the context of the :keyword:`for` that follows it, so this example is |
| 343 | equivalent to:: |
Georg Brandl | adbda84 | 2007-12-14 19:03:36 +0000 | [diff] [blame] | 344 | |
Ezio Melotti | 4a72d1a | 2011-12-13 14:50:21 +0200 | [diff] [blame] | 345 | >>> transposed = [] |
| 346 | >>> for i in range(4): |
| 347 | ... transposed.append([row[i] for row in matrix]) |
| 348 | ... |
| 349 | >>> transposed |
| 350 | [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]] |
Georg Brandl | adbda84 | 2007-12-14 19:03:36 +0000 | [diff] [blame] | 351 | |
Ezio Melotti | 4a72d1a | 2011-12-13 14:50:21 +0200 | [diff] [blame] | 352 | which, in turn, is the same as:: |
Georg Brandl | adbda84 | 2007-12-14 19:03:36 +0000 | [diff] [blame] | 353 | |
Ezio Melotti | 4a72d1a | 2011-12-13 14:50:21 +0200 | [diff] [blame] | 354 | >>> transposed = [] |
| 355 | >>> for i in range(4): |
| 356 | ... # the following 3 lines implement the nested listcomp |
| 357 | ... transposed_row = [] |
| 358 | ... for row in matrix: |
| 359 | ... transposed_row.append(row[i]) |
| 360 | ... transposed.append(transposed_row) |
| 361 | ... |
| 362 | >>> transposed |
| 363 | [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]] |
Georg Brandl | adbda84 | 2007-12-14 19:03:36 +0000 | [diff] [blame] | 364 | |
Ezio Melotti | 4a72d1a | 2011-12-13 14:50:21 +0200 | [diff] [blame] | 365 | |
| 366 | 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] | 367 | The :func:`zip` function would do a great job for this use case:: |
| 368 | |
Ezio Melotti | 4a72d1a | 2011-12-13 14:50:21 +0200 | [diff] [blame] | 369 | >>> zip(*matrix) |
| 370 | [(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)] |
Georg Brandl | adbda84 | 2007-12-14 19:03:36 +0000 | [diff] [blame] | 371 | |
| 372 | See :ref:`tut-unpacking-arguments` for details on the asterisk in this line. |
| 373 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 374 | .. _tut-del: |
| 375 | |
| 376 | The :keyword:`del` statement |
| 377 | ============================ |
| 378 | |
| 379 | There is a way to remove an item from a list given its index instead of its |
| 380 | value: the :keyword:`del` statement. This differs from the :meth:`pop` method |
| 381 | which returns a value. The :keyword:`del` statement can also be used to remove |
| 382 | slices from a list or clear the entire list (which we did earlier by assignment |
| 383 | of an empty list to the slice). For example:: |
| 384 | |
| 385 | >>> a = [-1, 1, 66.25, 333, 333, 1234.5] |
| 386 | >>> del a[0] |
| 387 | >>> a |
| 388 | [1, 66.25, 333, 333, 1234.5] |
| 389 | >>> del a[2:4] |
| 390 | >>> a |
| 391 | [1, 66.25, 1234.5] |
| 392 | >>> del a[:] |
| 393 | >>> a |
| 394 | [] |
| 395 | |
| 396 | :keyword:`del` can also be used to delete entire variables:: |
| 397 | |
| 398 | >>> del a |
| 399 | |
| 400 | Referencing the name ``a`` hereafter is an error (at least until another value |
| 401 | is assigned to it). We'll find other uses for :keyword:`del` later. |
| 402 | |
| 403 | |
| 404 | .. _tut-tuples: |
| 405 | |
| 406 | Tuples and Sequences |
| 407 | ==================== |
| 408 | |
| 409 | We saw that lists and strings have many common properties, such as indexing and |
| 410 | slicing operations. They are two examples of *sequence* data types (see |
| 411 | :ref:`typesseq`). Since Python is an evolving language, other sequence data |
| 412 | types may be added. There is also another standard sequence data type: the |
| 413 | *tuple*. |
| 414 | |
| 415 | A tuple consists of a number of values separated by commas, for instance:: |
| 416 | |
| 417 | >>> t = 12345, 54321, 'hello!' |
| 418 | >>> t[0] |
| 419 | 12345 |
| 420 | >>> t |
| 421 | (12345, 54321, 'hello!') |
| 422 | >>> # Tuples may be nested: |
| 423 | ... u = t, (1, 2, 3, 4, 5) |
| 424 | >>> u |
| 425 | ((12345, 54321, 'hello!'), (1, 2, 3, 4, 5)) |
| 426 | |
| 427 | As you see, on output tuples are always enclosed in parentheses, so that nested |
| 428 | tuples are interpreted correctly; they may be input with or without surrounding |
| 429 | parentheses, although often parentheses are necessary anyway (if the tuple is |
| 430 | part of a larger expression). |
| 431 | |
| 432 | Tuples have many uses. For example: (x, y) coordinate pairs, employee records |
| 433 | from a database, etc. Tuples, like strings, are immutable: it is not possible |
| 434 | to assign to the individual items of a tuple (you can simulate much of the same |
| 435 | effect with slicing and concatenation, though). It is also possible to create |
| 436 | tuples which contain mutable objects, such as lists. |
| 437 | |
| 438 | A special problem is the construction of tuples containing 0 or 1 items: the |
| 439 | syntax has some extra quirks to accommodate these. Empty tuples are constructed |
| 440 | by an empty pair of parentheses; a tuple with one item is constructed by |
| 441 | following a value with a comma (it is not sufficient to enclose a single value |
| 442 | in parentheses). Ugly, but effective. For example:: |
| 443 | |
| 444 | >>> empty = () |
| 445 | >>> singleton = 'hello', # <-- note trailing comma |
| 446 | >>> len(empty) |
| 447 | 0 |
| 448 | >>> len(singleton) |
| 449 | 1 |
| 450 | >>> singleton |
| 451 | ('hello',) |
| 452 | |
| 453 | The statement ``t = 12345, 54321, 'hello!'`` is an example of *tuple packing*: |
| 454 | the values ``12345``, ``54321`` and ``'hello!'`` are packed together in a tuple. |
| 455 | The reverse operation is also possible:: |
| 456 | |
| 457 | >>> x, y, z = t |
| 458 | |
Georg Brandl | 354e4cb | 2009-03-31 22:40:16 +0000 | [diff] [blame] | 459 | This is called, appropriately enough, *sequence unpacking* and works for any |
| 460 | sequence on the right-hand side. Sequence unpacking requires the list of |
| 461 | variables on the left to have the same number of elements as the length of the |
| 462 | sequence. Note that multiple assignment is really just a combination of tuple |
Georg Brandl | a08867d | 2009-03-31 23:01:27 +0000 | [diff] [blame] | 463 | packing and sequence unpacking. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 464 | |
Georg Brandl | b19be57 | 2007-12-29 10:57:00 +0000 | [diff] [blame] | 465 | .. XXX Add a bit on the difference between tuples and lists. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 466 | |
| 467 | |
| 468 | .. _tut-sets: |
| 469 | |
| 470 | Sets |
| 471 | ==== |
| 472 | |
| 473 | Python also includes a data type for *sets*. A set is an unordered collection |
| 474 | with no duplicate elements. Basic uses include membership testing and |
| 475 | eliminating duplicate entries. Set objects also support mathematical operations |
| 476 | like union, intersection, difference, and symmetric difference. |
| 477 | |
| 478 | Here is a brief demonstration:: |
| 479 | |
| 480 | >>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana'] |
| 481 | >>> fruit = set(basket) # create a set without duplicates |
| 482 | >>> fruit |
| 483 | set(['orange', 'pear', 'apple', 'banana']) |
| 484 | >>> 'orange' in fruit # fast membership testing |
| 485 | True |
| 486 | >>> 'crabgrass' in fruit |
| 487 | False |
| 488 | |
| 489 | >>> # Demonstrate set operations on unique letters from two words |
| 490 | ... |
| 491 | >>> a = set('abracadabra') |
| 492 | >>> b = set('alacazam') |
| 493 | >>> a # unique letters in a |
| 494 | set(['a', 'r', 'b', 'c', 'd']) |
| 495 | >>> a - b # letters in a but not in b |
| 496 | set(['r', 'd', 'b']) |
| 497 | >>> a | b # letters in either a or b |
| 498 | set(['a', 'c', 'r', 'd', 'b', 'm', 'z', 'l']) |
| 499 | >>> a & b # letters in both a and b |
| 500 | set(['a', 'c']) |
| 501 | >>> a ^ b # letters in a or b but not both |
| 502 | set(['r', 'd', 'b', 'm', 'z', 'l']) |
| 503 | |
| 504 | |
| 505 | .. _tut-dictionaries: |
| 506 | |
| 507 | Dictionaries |
| 508 | ============ |
| 509 | |
| 510 | Another useful data type built into Python is the *dictionary* (see |
| 511 | :ref:`typesmapping`). Dictionaries are sometimes found in other languages as |
| 512 | "associative memories" or "associative arrays". Unlike sequences, which are |
| 513 | indexed by a range of numbers, dictionaries are indexed by *keys*, which can be |
| 514 | any immutable type; strings and numbers can always be keys. Tuples can be used |
| 515 | as keys if they contain only strings, numbers, or tuples; if a tuple contains |
| 516 | any mutable object either directly or indirectly, it cannot be used as a key. |
| 517 | You can't use lists as keys, since lists can be modified in place using index |
| 518 | assignments, slice assignments, or methods like :meth:`append` and |
| 519 | :meth:`extend`. |
| 520 | |
| 521 | It is best to think of a dictionary as an unordered set of *key: value* pairs, |
| 522 | with the requirement that the keys are unique (within one dictionary). A pair of |
| 523 | braces creates an empty dictionary: ``{}``. Placing a comma-separated list of |
| 524 | key:value pairs within the braces adds initial key:value pairs to the |
| 525 | dictionary; this is also the way dictionaries are written on output. |
| 526 | |
| 527 | The main operations on a dictionary are storing a value with some key and |
| 528 | extracting the value given the key. It is also possible to delete a key:value |
| 529 | pair with ``del``. If you store using a key that is already in use, the old |
| 530 | value associated with that key is forgotten. It is an error to extract a value |
| 531 | using a non-existent key. |
| 532 | |
| 533 | The :meth:`keys` method of a dictionary object returns a list of all the keys |
| 534 | 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] | 535 | the :func:`sorted` function to it). To check whether a single key is in the |
| 536 | dictionary, use the :keyword:`in` keyword. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 537 | |
| 538 | Here is a small example using a dictionary:: |
| 539 | |
| 540 | >>> tel = {'jack': 4098, 'sape': 4139} |
| 541 | >>> tel['guido'] = 4127 |
| 542 | >>> tel |
| 543 | {'sape': 4139, 'guido': 4127, 'jack': 4098} |
| 544 | >>> tel['jack'] |
| 545 | 4098 |
| 546 | >>> del tel['sape'] |
| 547 | >>> tel['irv'] = 4127 |
| 548 | >>> tel |
| 549 | {'guido': 4127, 'irv': 4127, 'jack': 4098} |
| 550 | >>> tel.keys() |
| 551 | ['guido', 'irv', 'jack'] |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 552 | >>> 'guido' in tel |
| 553 | True |
| 554 | |
| 555 | The :func:`dict` constructor builds dictionaries directly from lists of |
| 556 | key-value pairs stored as tuples. When the pairs form a pattern, list |
| 557 | comprehensions can compactly specify the key-value list. :: |
| 558 | |
| 559 | >>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)]) |
| 560 | {'sape': 4139, 'jack': 4098, 'guido': 4127} |
| 561 | >>> dict([(x, x**2) for x in (2, 4, 6)]) # use a list comprehension |
| 562 | {2: 4, 4: 16, 6: 36} |
| 563 | |
| 564 | Later in the tutorial, we will learn about Generator Expressions which are even |
| 565 | better suited for the task of supplying key-values pairs to the :func:`dict` |
| 566 | constructor. |
| 567 | |
| 568 | When the keys are simple strings, it is sometimes easier to specify pairs using |
| 569 | keyword arguments:: |
| 570 | |
| 571 | >>> dict(sape=4139, guido=4127, jack=4098) |
| 572 | {'sape': 4139, 'jack': 4098, 'guido': 4127} |
| 573 | |
| 574 | |
| 575 | .. _tut-loopidioms: |
| 576 | |
| 577 | Looping Techniques |
| 578 | ================== |
| 579 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 580 | When looping through a sequence, the position index and corresponding value can |
| 581 | be retrieved at the same time using the :func:`enumerate` function. :: |
| 582 | |
| 583 | >>> for i, v in enumerate(['tic', 'tac', 'toe']): |
| 584 | ... print i, v |
| 585 | ... |
| 586 | 0 tic |
| 587 | 1 tac |
| 588 | 2 toe |
| 589 | |
| 590 | To loop over two or more sequences at the same time, the entries can be paired |
| 591 | with the :func:`zip` function. :: |
| 592 | |
| 593 | >>> questions = ['name', 'quest', 'favorite color'] |
| 594 | >>> answers = ['lancelot', 'the holy grail', 'blue'] |
| 595 | >>> for q, a in zip(questions, answers): |
Benjamin Peterson | f9ef988 | 2008-05-26 00:54:22 +0000 | [diff] [blame] | 596 | ... print 'What is your {0}? It is {1}.'.format(q, a) |
Georg Brandl | c62ef8b | 2009-01-03 20:55:06 +0000 | [diff] [blame] | 597 | ... |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 598 | What is your name? It is lancelot. |
| 599 | What is your quest? It is the holy grail. |
| 600 | What is your favorite color? It is blue. |
| 601 | |
| 602 | To loop over a sequence in reverse, first specify the sequence in a forward |
| 603 | direction and then call the :func:`reversed` function. :: |
| 604 | |
| 605 | >>> for i in reversed(xrange(1,10,2)): |
| 606 | ... print i |
| 607 | ... |
| 608 | 9 |
| 609 | 7 |
| 610 | 5 |
| 611 | 3 |
| 612 | 1 |
| 613 | |
| 614 | To loop over a sequence in sorted order, use the :func:`sorted` function which |
| 615 | returns a new sorted list while leaving the source unaltered. :: |
| 616 | |
| 617 | >>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana'] |
| 618 | >>> for f in sorted(set(basket)): |
| 619 | ... print f |
Georg Brandl | c62ef8b | 2009-01-03 20:55:06 +0000 | [diff] [blame] | 620 | ... |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 621 | apple |
| 622 | banana |
| 623 | orange |
| 624 | pear |
| 625 | |
Raymond Hettinger | 4c8d392 | 2012-04-23 21:24:15 -0700 | [diff] [blame^] | 626 | When looping through dictionaries, the key and corresponding value can be |
| 627 | retrieved at the same time using the :meth:`iteritems` method. :: |
| 628 | |
| 629 | >>> knights = {'gallahad': 'the pure', 'robin': 'the brave'} |
| 630 | >>> for k, v in knights.iteritems(): |
| 631 | ... print k, v |
| 632 | ... |
| 633 | gallahad the pure |
| 634 | robin the brave |
| 635 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 636 | |
| 637 | .. _tut-conditions: |
| 638 | |
| 639 | More on Conditions |
| 640 | ================== |
| 641 | |
| 642 | The conditions used in ``while`` and ``if`` statements can contain any |
| 643 | operators, not just comparisons. |
| 644 | |
| 645 | The comparison operators ``in`` and ``not in`` check whether a value occurs |
| 646 | (does not occur) in a sequence. The operators ``is`` and ``is not`` compare |
| 647 | whether two objects are really the same object; this only matters for mutable |
| 648 | objects like lists. All comparison operators have the same priority, which is |
| 649 | lower than that of all numerical operators. |
| 650 | |
| 651 | Comparisons can be chained. For example, ``a < b == c`` tests whether ``a`` is |
| 652 | less than ``b`` and moreover ``b`` equals ``c``. |
| 653 | |
| 654 | Comparisons may be combined using the Boolean operators ``and`` and ``or``, and |
| 655 | the outcome of a comparison (or of any other Boolean expression) may be negated |
| 656 | with ``not``. These have lower priorities than comparison operators; between |
| 657 | them, ``not`` has the highest priority and ``or`` the lowest, so that ``A and |
| 658 | not B or C`` is equivalent to ``(A and (not B)) or C``. As always, parentheses |
| 659 | can be used to express the desired composition. |
| 660 | |
| 661 | The Boolean operators ``and`` and ``or`` are so-called *short-circuit* |
| 662 | operators: their arguments are evaluated from left to right, and evaluation |
| 663 | stops as soon as the outcome is determined. For example, if ``A`` and ``C`` are |
| 664 | true but ``B`` is false, ``A and B and C`` does not evaluate the expression |
| 665 | ``C``. When used as a general value and not as a Boolean, the return value of a |
| 666 | short-circuit operator is the last evaluated argument. |
| 667 | |
| 668 | It is possible to assign the result of a comparison or other Boolean expression |
| 669 | to a variable. For example, :: |
| 670 | |
| 671 | >>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance' |
| 672 | >>> non_null = string1 or string2 or string3 |
| 673 | >>> non_null |
| 674 | 'Trondheim' |
| 675 | |
| 676 | Note that in Python, unlike C, assignment cannot occur inside expressions. C |
| 677 | programmers may grumble about this, but it avoids a common class of problems |
| 678 | encountered in C programs: typing ``=`` in an expression when ``==`` was |
| 679 | intended. |
| 680 | |
| 681 | |
| 682 | .. _tut-comparing: |
| 683 | |
| 684 | Comparing Sequences and Other Types |
| 685 | =================================== |
| 686 | |
| 687 | Sequence objects may be compared to other objects with the same sequence type. |
| 688 | The comparison uses *lexicographical* ordering: first the first two items are |
| 689 | compared, and if they differ this determines the outcome of the comparison; if |
| 690 | they are equal, the next two items are compared, and so on, until either |
| 691 | sequence is exhausted. If two items to be compared are themselves sequences of |
| 692 | the same type, the lexicographical comparison is carried out recursively. If |
| 693 | all items of two sequences compare equal, the sequences are considered equal. |
| 694 | If one sequence is an initial sub-sequence of the other, the shorter sequence is |
| 695 | the smaller (lesser) one. Lexicographical ordering for strings uses the ASCII |
| 696 | ordering for individual characters. Some examples of comparisons between |
| 697 | sequences of the same type:: |
| 698 | |
| 699 | (1, 2, 3) < (1, 2, 4) |
| 700 | [1, 2, 3] < [1, 2, 4] |
| 701 | 'ABC' < 'C' < 'Pascal' < 'Python' |
| 702 | (1, 2, 3, 4) < (1, 2, 4) |
| 703 | (1, 2) < (1, 2, -1) |
| 704 | (1, 2, 3) == (1.0, 2.0, 3.0) |
| 705 | (1, 2, ('aa', 'ab')) < (1, 2, ('abc', 'a'), 4) |
| 706 | |
| 707 | Note that comparing objects of different types is legal. The outcome is |
| 708 | deterministic but arbitrary: the types are ordered by their name. Thus, a list |
| 709 | is always smaller than a string, a string is always smaller than a tuple, etc. |
| 710 | [#]_ Mixed numeric types are compared according to their numeric value, so 0 |
| 711 | equals 0.0, etc. |
| 712 | |
| 713 | |
| 714 | .. rubric:: Footnotes |
| 715 | |
| 716 | .. [#] The rules for comparing objects of different types should not be relied upon; |
| 717 | they may change in a future version of the language. |
| 718 | |