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