Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1 | .. XXX: reference/datamodel and this have quite a few overlaps! |
| 2 | |
| 3 | |
| 4 | .. _bltin-types: |
| 5 | |
| 6 | ************** |
| 7 | Built-in Types |
| 8 | ************** |
| 9 | |
| 10 | The following sections describe the standard types that are built into the |
| 11 | interpreter. |
| 12 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 13 | .. index:: pair: built-in; types |
| 14 | |
Antoine Pitrou | b1a1810 | 2009-12-19 18:23:15 +0000 | [diff] [blame] | 15 | The principal built-in types are numerics, sequences, mappings, classes, |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 16 | instances and exceptions. |
| 17 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 18 | Some operations are supported by several object types; in particular, |
| 19 | practically all objects can be compared, tested for truth value, and converted |
| 20 | to a string (with the :func:`repr` function or the slightly different |
| 21 | :func:`str` function). The latter function is implicitly used when an object is |
| 22 | written by the :func:`print` function. |
| 23 | |
| 24 | |
| 25 | .. _truth: |
| 26 | |
| 27 | Truth Value Testing |
| 28 | =================== |
| 29 | |
| 30 | .. index:: |
| 31 | statement: if |
| 32 | statement: while |
| 33 | pair: truth; value |
| 34 | pair: Boolean; operations |
| 35 | single: false |
| 36 | |
| 37 | Any object can be tested for truth value, for use in an :keyword:`if` or |
| 38 | :keyword:`while` condition or as operand of the Boolean operations below. The |
| 39 | following values are considered false: |
| 40 | |
| 41 | .. index:: single: None (Built-in object) |
| 42 | |
| 43 | * ``None`` |
| 44 | |
| 45 | .. index:: single: False (Built-in object) |
| 46 | |
| 47 | * ``False`` |
| 48 | |
Mark Summerfield | bbfd71d | 2008-07-01 15:50:04 +0000 | [diff] [blame] | 49 | * zero of any numeric type, for example, ``0``, ``0.0``, ``0j``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 50 | |
| 51 | * any empty sequence, for example, ``''``, ``()``, ``[]``. |
| 52 | |
| 53 | * any empty mapping, for example, ``{}``. |
| 54 | |
| 55 | * instances of user-defined classes, if the class defines a :meth:`__bool__` or |
| 56 | :meth:`__len__` method, when that method returns the integer zero or |
| 57 | :class:`bool` value ``False``. [#]_ |
| 58 | |
| 59 | .. index:: single: true |
| 60 | |
| 61 | All other values are considered true --- so objects of many types are always |
| 62 | true. |
| 63 | |
| 64 | .. index:: |
| 65 | operator: or |
| 66 | operator: and |
| 67 | single: False |
| 68 | single: True |
| 69 | |
| 70 | Operations and built-in functions that have a Boolean result always return ``0`` |
| 71 | or ``False`` for false and ``1`` or ``True`` for true, unless otherwise stated. |
| 72 | (Important exception: the Boolean operations ``or`` and ``and`` always return |
| 73 | one of their operands.) |
| 74 | |
| 75 | |
| 76 | .. _boolean: |
| 77 | |
| 78 | Boolean Operations --- :keyword:`and`, :keyword:`or`, :keyword:`not` |
| 79 | ==================================================================== |
| 80 | |
| 81 | .. index:: pair: Boolean; operations |
| 82 | |
| 83 | These are the Boolean operations, ordered by ascending priority: |
| 84 | |
| 85 | +-------------+---------------------------------+-------+ |
| 86 | | Operation | Result | Notes | |
| 87 | +=============+=================================+=======+ |
| 88 | | ``x or y`` | if *x* is false, then *y*, else | \(1) | |
| 89 | | | *x* | | |
| 90 | +-------------+---------------------------------+-------+ |
| 91 | | ``x and y`` | if *x* is false, then *x*, else | \(2) | |
| 92 | | | *y* | | |
| 93 | +-------------+---------------------------------+-------+ |
| 94 | | ``not x`` | if *x* is false, then ``True``, | \(3) | |
| 95 | | | else ``False`` | | |
| 96 | +-------------+---------------------------------+-------+ |
| 97 | |
| 98 | .. index:: |
| 99 | operator: and |
| 100 | operator: or |
| 101 | operator: not |
| 102 | |
| 103 | Notes: |
| 104 | |
| 105 | (1) |
| 106 | This is a short-circuit operator, so it only evaluates the second |
| 107 | argument if the first one is :const:`False`. |
| 108 | |
| 109 | (2) |
| 110 | This is a short-circuit operator, so it only evaluates the second |
| 111 | argument if the first one is :const:`True`. |
| 112 | |
| 113 | (3) |
| 114 | ``not`` has a lower priority than non-Boolean operators, so ``not a == b`` is |
| 115 | interpreted as ``not (a == b)``, and ``a == not b`` is a syntax error. |
| 116 | |
| 117 | |
| 118 | .. _stdcomparisons: |
| 119 | |
| 120 | Comparisons |
| 121 | =========== |
| 122 | |
Georg Brandl | c5605df | 2009-08-13 08:26:44 +0000 | [diff] [blame] | 123 | .. index:: |
| 124 | pair: chaining; comparisons |
| 125 | pair: operator; comparison |
| 126 | operator: == |
| 127 | operator: < |
| 128 | operator: <= |
| 129 | operator: > |
| 130 | operator: >= |
| 131 | operator: != |
| 132 | operator: is |
| 133 | operator: is not |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 134 | |
Georg Brandl | 905ec32 | 2007-09-28 13:39:25 +0000 | [diff] [blame] | 135 | There are eight comparison operations in Python. They all have the same |
| 136 | priority (which is higher than that of the Boolean operations). Comparisons can |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 137 | be chained arbitrarily; for example, ``x < y <= z`` is equivalent to ``x < y and |
| 138 | y <= z``, except that *y* is evaluated only once (but in both cases *z* is not |
| 139 | evaluated at all when ``x < y`` is found to be false). |
| 140 | |
| 141 | This table summarizes the comparison operations: |
| 142 | |
Georg Brandl | fd85516 | 2008-01-07 09:13:03 +0000 | [diff] [blame] | 143 | +------------+-------------------------+ |
| 144 | | Operation | Meaning | |
| 145 | +============+=========================+ |
| 146 | | ``<`` | strictly less than | |
| 147 | +------------+-------------------------+ |
| 148 | | ``<=`` | less than or equal | |
| 149 | +------------+-------------------------+ |
| 150 | | ``>`` | strictly greater than | |
| 151 | +------------+-------------------------+ |
| 152 | | ``>=`` | greater than or equal | |
| 153 | +------------+-------------------------+ |
| 154 | | ``==`` | equal | |
| 155 | +------------+-------------------------+ |
| 156 | | ``!=`` | not equal | |
| 157 | +------------+-------------------------+ |
| 158 | | ``is`` | object identity | |
| 159 | +------------+-------------------------+ |
| 160 | | ``is not`` | negated object identity | |
| 161 | +------------+-------------------------+ |
Christian Heimes | 5b5e81c | 2007-12-31 16:14:33 +0000 | [diff] [blame] | 162 | |
| 163 | .. index:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 164 | pair: object; numeric |
| 165 | pair: objects; comparing |
| 166 | |
Georg Brandl | 905ec32 | 2007-09-28 13:39:25 +0000 | [diff] [blame] | 167 | Objects of different types, except different numeric types, never compare equal. |
Antoine Pitrou | b1a1810 | 2009-12-19 18:23:15 +0000 | [diff] [blame] | 168 | Furthermore, some types (for example, function objects) support only a degenerate |
Georg Brandl | 905ec32 | 2007-09-28 13:39:25 +0000 | [diff] [blame] | 169 | notion of comparison where any two objects of that type are unequal. The ``<``, |
| 170 | ``<=``, ``>`` and ``>=`` operators will raise a :exc:`TypeError` exception when |
| 171 | any operand is a complex number, the objects are of different types that cannot |
| 172 | be compared, or other cases where there is no defined ordering. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 173 | |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 174 | .. index:: |
Georg Brandl | 905ec32 | 2007-09-28 13:39:25 +0000 | [diff] [blame] | 175 | single: __eq__() (instance method) |
| 176 | single: __ne__() (instance method) |
| 177 | single: __lt__() (instance method) |
| 178 | single: __le__() (instance method) |
| 179 | single: __gt__() (instance method) |
| 180 | single: __ge__() (instance method) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 181 | |
Georg Brandl | 05f5ab7 | 2008-09-24 09:11:47 +0000 | [diff] [blame] | 182 | Non-identical instances of a class normally compare as non-equal unless the |
| 183 | class defines the :meth:`__eq__` method. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 184 | |
Georg Brandl | 905ec32 | 2007-09-28 13:39:25 +0000 | [diff] [blame] | 185 | Instances of a class cannot be ordered with respect to other instances of the |
| 186 | same class, or other types of object, unless the class defines enough of the |
Georg Brandl | 05f5ab7 | 2008-09-24 09:11:47 +0000 | [diff] [blame] | 187 | methods :meth:`__lt__`, :meth:`__le__`, :meth:`__gt__`, and :meth:`__ge__` (in |
| 188 | general, :meth:`__lt__` and :meth:`__eq__` are sufficient, if you want the |
| 189 | conventional meanings of the comparison operators). |
Georg Brandl | 905ec32 | 2007-09-28 13:39:25 +0000 | [diff] [blame] | 190 | |
| 191 | The behavior of the :keyword:`is` and :keyword:`is not` operators cannot be |
| 192 | customized; also they can be applied to any two objects and never raise an |
| 193 | exception. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 194 | |
| 195 | .. index:: |
| 196 | operator: in |
| 197 | operator: not in |
| 198 | |
| 199 | Two more operations with the same syntactic priority, ``in`` and ``not in``, are |
| 200 | supported only by sequence types (below). |
| 201 | |
| 202 | |
| 203 | .. _typesnumeric: |
| 204 | |
Georg Brandl | 905ec32 | 2007-09-28 13:39:25 +0000 | [diff] [blame] | 205 | Numeric Types --- :class:`int`, :class:`float`, :class:`complex` |
| 206 | ================================================================ |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 207 | |
| 208 | .. index:: |
| 209 | object: numeric |
| 210 | object: Boolean |
| 211 | object: integer |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 212 | object: floating point |
| 213 | object: complex number |
| 214 | pair: C; language |
| 215 | |
Mark Summerfield | bbfd71d | 2008-07-01 15:50:04 +0000 | [diff] [blame] | 216 | There are three distinct numeric types: :dfn:`integers`, :dfn:`floating |
| 217 | point numbers`, and :dfn:`complex numbers`. In addition, Booleans are a |
| 218 | subtype of integers. Integers have unlimited precision. Floating point |
Mark Dickinson | e56a386 | 2010-08-04 18:43:36 +0000 | [diff] [blame] | 219 | numbers are usually implemented using :ctype:`double` in C; information |
| 220 | about the precision and internal representation of floating point |
| 221 | numbers for the machine on which your program is running is available |
| 222 | in :data:`sys.float_info`. Complex numbers have a real and imaginary |
| 223 | part, which are each a floating point number. To extract these parts |
| 224 | from a complex number *z*, use ``z.real`` and ``z.imag``. (The standard |
| 225 | library includes additional numeric types, :mod:`fractions` that hold |
| 226 | rationals, and :mod:`decimal` that hold floating-point numbers with |
| 227 | user-definable precision.) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 228 | |
| 229 | .. index:: |
| 230 | pair: numeric; literals |
| 231 | pair: integer; literals |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 232 | pair: floating point; literals |
| 233 | pair: complex number; literals |
| 234 | pair: hexadecimal; literals |
| 235 | pair: octal; literals |
Neal Norwitz | 1d2aef5 | 2007-10-02 07:26:14 +0000 | [diff] [blame] | 236 | pair: binary; literals |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 237 | |
| 238 | Numbers are created by numeric literals or as the result of built-in functions |
Georg Brandl | 905ec32 | 2007-09-28 13:39:25 +0000 | [diff] [blame] | 239 | and operators. Unadorned integer literals (including hex, octal and binary |
| 240 | numbers) yield integers. Numeric literals containing a decimal point or an |
| 241 | exponent sign yield floating point numbers. Appending ``'j'`` or ``'J'`` to a |
| 242 | numeric literal yields an imaginary number (a complex number with a zero real |
| 243 | part) which you can add to an integer or float to get a complex number with real |
| 244 | and imaginary parts. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 245 | |
| 246 | .. index:: |
| 247 | single: arithmetic |
| 248 | builtin: int |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 249 | builtin: float |
| 250 | builtin: complex |
Georg Brandl | c5605df | 2009-08-13 08:26:44 +0000 | [diff] [blame] | 251 | operator: + |
| 252 | operator: - |
| 253 | operator: * |
| 254 | operator: / |
| 255 | operator: // |
| 256 | operator: % |
| 257 | operator: ** |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 258 | |
| 259 | Python fully supports mixed arithmetic: when a binary arithmetic operator has |
| 260 | operands of different numeric types, the operand with the "narrower" type is |
Georg Brandl | 905ec32 | 2007-09-28 13:39:25 +0000 | [diff] [blame] | 261 | widened to that of the other, where integer is narrower than floating point, |
| 262 | which is narrower than complex. Comparisons between numbers of mixed type use |
| 263 | the same rule. [#]_ The constructors :func:`int`, :func:`float`, and |
| 264 | :func:`complex` can be used to produce numbers of a specific type. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 265 | |
| 266 | All numeric types (except complex) support the following operations, sorted by |
| 267 | ascending priority (operations in the same box have the same priority; all |
| 268 | numeric operations have a higher priority than comparison operations): |
| 269 | |
Georg Brandl | 905ec32 | 2007-09-28 13:39:25 +0000 | [diff] [blame] | 270 | +---------------------+---------------------------------+-------+--------------------+ |
| 271 | | Operation | Result | Notes | Full documentation | |
Neal Norwitz | 1d2aef5 | 2007-10-02 07:26:14 +0000 | [diff] [blame] | 272 | +=====================+=================================+=======+====================+ |
Georg Brandl | 905ec32 | 2007-09-28 13:39:25 +0000 | [diff] [blame] | 273 | | ``x + y`` | sum of *x* and *y* | | | |
| 274 | +---------------------+---------------------------------+-------+--------------------+ |
| 275 | | ``x - y`` | difference of *x* and *y* | | | |
| 276 | +---------------------+---------------------------------+-------+--------------------+ |
| 277 | | ``x * y`` | product of *x* and *y* | | | |
| 278 | +---------------------+---------------------------------+-------+--------------------+ |
| 279 | | ``x / y`` | quotient of *x* and *y* | | | |
| 280 | +---------------------+---------------------------------+-------+--------------------+ |
| 281 | | ``x // y`` | floored quotient of *x* and | \(1) | | |
| 282 | | | *y* | | | |
| 283 | +---------------------+---------------------------------+-------+--------------------+ |
| 284 | | ``x % y`` | remainder of ``x / y`` | \(2) | | |
| 285 | +---------------------+---------------------------------+-------+--------------------+ |
| 286 | | ``-x`` | *x* negated | | | |
| 287 | +---------------------+---------------------------------+-------+--------------------+ |
| 288 | | ``+x`` | *x* unchanged | | | |
| 289 | +---------------------+---------------------------------+-------+--------------------+ |
| 290 | | ``abs(x)`` | absolute value or magnitude of | | :func:`abs` | |
| 291 | | | *x* | | | |
| 292 | +---------------------+---------------------------------+-------+--------------------+ |
| 293 | | ``int(x)`` | *x* converted to integer | \(3) | :func:`int` | |
| 294 | +---------------------+---------------------------------+-------+--------------------+ |
Georg Brandl | 74f3669 | 2008-01-06 17:39:49 +0000 | [diff] [blame] | 295 | | ``float(x)`` | *x* converted to floating point | \(4) | :func:`float` | |
Georg Brandl | 905ec32 | 2007-09-28 13:39:25 +0000 | [diff] [blame] | 296 | +---------------------+---------------------------------+-------+--------------------+ |
| 297 | | ``complex(re, im)`` | a complex number with real part | | :func:`complex` | |
| 298 | | | *re*, imaginary part *im*. | | | |
| 299 | | | *im* defaults to zero. | | | |
| 300 | +---------------------+---------------------------------+-------+--------------------+ |
| 301 | | ``c.conjugate()`` | conjugate of the complex number | | | |
| 302 | | | *c* | | | |
| 303 | +---------------------+---------------------------------+-------+--------------------+ |
| 304 | | ``divmod(x, y)`` | the pair ``(x // y, x % y)`` | \(2) | :func:`divmod` | |
| 305 | +---------------------+---------------------------------+-------+--------------------+ |
Georg Brandl | 60fe2f1 | 2008-01-07 09:16:46 +0000 | [diff] [blame] | 306 | | ``pow(x, y)`` | *x* to the power *y* | \(5) | :func:`pow` | |
Georg Brandl | 905ec32 | 2007-09-28 13:39:25 +0000 | [diff] [blame] | 307 | +---------------------+---------------------------------+-------+--------------------+ |
Georg Brandl | 60fe2f1 | 2008-01-07 09:16:46 +0000 | [diff] [blame] | 308 | | ``x ** y`` | *x* to the power *y* | \(5) | | |
Georg Brandl | 905ec32 | 2007-09-28 13:39:25 +0000 | [diff] [blame] | 309 | +---------------------+---------------------------------+-------+--------------------+ |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 310 | |
| 311 | .. index:: |
| 312 | triple: operations on; numeric; types |
| 313 | single: conjugate() (complex number method) |
| 314 | |
| 315 | Notes: |
| 316 | |
| 317 | (1) |
Georg Brandl | 905ec32 | 2007-09-28 13:39:25 +0000 | [diff] [blame] | 318 | Also referred to as integer division. The resultant value is a whole |
| 319 | integer, though the result's type is not necessarily int. The result is |
| 320 | always rounded towards minus infinity: ``1//2`` is ``0``, ``(-1)//2`` is |
| 321 | ``-1``, ``1//(-2)`` is ``-1``, and ``(-1)//(-2)`` is ``0``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 322 | |
| 323 | (2) |
Georg Brandl | 905ec32 | 2007-09-28 13:39:25 +0000 | [diff] [blame] | 324 | Not for complex numbers. Instead convert to floats using :func:`abs` if |
| 325 | appropriate. |
| 326 | |
| 327 | (3) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 328 | .. index:: |
| 329 | module: math |
| 330 | single: floor() (in module math) |
| 331 | single: ceil() (in module math) |
Benjamin Peterson | 28d88b4 | 2009-01-09 03:03:23 +0000 | [diff] [blame] | 332 | single: trunc() (in module math) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 333 | pair: numeric; conversions |
| 334 | pair: C; language |
| 335 | |
Georg Brandl | ba956ae | 2007-11-29 17:24:34 +0000 | [diff] [blame] | 336 | Conversion from floating point to integer may round or truncate |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 337 | as in C; see functions :func:`floor` and :func:`ceil` in the :mod:`math` module |
| 338 | for well-defined conversions. |
| 339 | |
Georg Brandl | 74f3669 | 2008-01-06 17:39:49 +0000 | [diff] [blame] | 340 | (4) |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 341 | float also accepts the strings "nan" and "inf" with an optional prefix "+" |
Christian Heimes | 99170a5 | 2007-12-19 02:07:34 +0000 | [diff] [blame] | 342 | or "-" for Not a Number (NaN) and positive or negative infinity. |
Christian Heimes | 7f04431 | 2008-01-06 17:05:40 +0000 | [diff] [blame] | 343 | |
Georg Brandl | 74f3669 | 2008-01-06 17:39:49 +0000 | [diff] [blame] | 344 | (5) |
Christian Heimes | 7f04431 | 2008-01-06 17:05:40 +0000 | [diff] [blame] | 345 | Python defines ``pow(0, 0)`` and ``0 ** 0`` to be ``1``, as is common for |
| 346 | programming languages. |
| 347 | |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 348 | |
Christian Heimes | 5b5e81c | 2007-12-31 16:14:33 +0000 | [diff] [blame] | 349 | |
Christian Heimes | faf2f63 | 2008-01-06 16:59:19 +0000 | [diff] [blame] | 350 | All :class:`numbers.Real` types (:class:`int` and |
| 351 | :class:`float`) also include the following operations: |
| 352 | |
Benjamin Peterson | b58dda7 | 2009-01-18 22:27:04 +0000 | [diff] [blame] | 353 | +--------------------+------------------------------------+--------+ |
| 354 | | Operation | Result | Notes | |
| 355 | +====================+====================================+========+ |
| 356 | | ``math.trunc(x)`` | *x* truncated to Integral | | |
| 357 | +--------------------+------------------------------------+--------+ |
| 358 | | ``round(x[, n])`` | *x* rounded to n digits, | | |
| 359 | | | rounding half to even. If n is | | |
| 360 | | | omitted, it defaults to 0. | | |
| 361 | +--------------------+------------------------------------+--------+ |
| 362 | | ``math.floor(x)`` | the greatest integral float <= *x* | | |
| 363 | +--------------------+------------------------------------+--------+ |
| 364 | | ``math.ceil(x)`` | the least integral float >= *x* | | |
| 365 | +--------------------+------------------------------------+--------+ |
Christian Heimes | faf2f63 | 2008-01-06 16:59:19 +0000 | [diff] [blame] | 366 | |
Mark Summerfield | bbfd71d | 2008-07-01 15:50:04 +0000 | [diff] [blame] | 367 | For additional numeric operations see the :mod:`math` and :mod:`cmath` |
| 368 | modules. |
| 369 | |
Christian Heimes | 5b5e81c | 2007-12-31 16:14:33 +0000 | [diff] [blame] | 370 | .. XXXJH exceptions: overflow (when? what operations?) zerodivision |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 371 | |
| 372 | |
| 373 | .. _bitstring-ops: |
| 374 | |
| 375 | Bit-string Operations on Integer Types |
| 376 | -------------------------------------- |
| 377 | |
Georg Brandl | c5605df | 2009-08-13 08:26:44 +0000 | [diff] [blame] | 378 | .. index:: |
| 379 | triple: operations on; integer; types |
| 380 | pair: bit-string; operations |
| 381 | pair: shifting; operations |
| 382 | pair: masking; operations |
| 383 | operator: ^ |
| 384 | operator: & |
| 385 | operator: << |
| 386 | operator: >> |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 387 | |
Georg Brandl | 905ec32 | 2007-09-28 13:39:25 +0000 | [diff] [blame] | 388 | Integers support additional operations that make sense only for bit-strings. |
| 389 | Negative numbers are treated as their 2's complement value (this assumes a |
| 390 | sufficiently large number of bits that no overflow occurs during the operation). |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 391 | |
Christian Heimes | faf2f63 | 2008-01-06 16:59:19 +0000 | [diff] [blame] | 392 | The priorities of the binary bitwise operations are all lower than the numeric |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 393 | operations and higher than the comparisons; the unary operation ``~`` has the |
| 394 | same priority as the other unary numeric operations (``+`` and ``-``). |
| 395 | |
| 396 | This table lists the bit-string operations sorted in ascending priority |
| 397 | (operations in the same box have the same priority): |
| 398 | |
| 399 | +------------+--------------------------------+----------+ |
| 400 | | Operation | Result | Notes | |
| 401 | +============+================================+==========+ |
| 402 | | ``x | y`` | bitwise :dfn:`or` of *x* and | | |
| 403 | | | *y* | | |
| 404 | +------------+--------------------------------+----------+ |
| 405 | | ``x ^ y`` | bitwise :dfn:`exclusive or` of | | |
| 406 | | | *x* and *y* | | |
| 407 | +------------+--------------------------------+----------+ |
| 408 | | ``x & y`` | bitwise :dfn:`and` of *x* and | | |
| 409 | | | *y* | | |
| 410 | +------------+--------------------------------+----------+ |
Christian Heimes | 043d6f6 | 2008-01-07 17:19:16 +0000 | [diff] [blame] | 411 | | ``x << n`` | *x* shifted left by *n* bits | (1)(2) | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 412 | +------------+--------------------------------+----------+ |
Christian Heimes | 043d6f6 | 2008-01-07 17:19:16 +0000 | [diff] [blame] | 413 | | ``x >> n`` | *x* shifted right by *n* bits | (1)(3) | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 414 | +------------+--------------------------------+----------+ |
| 415 | | ``~x`` | the bits of *x* inverted | | |
| 416 | +------------+--------------------------------+----------+ |
| 417 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 418 | Notes: |
| 419 | |
| 420 | (1) |
| 421 | Negative shift counts are illegal and cause a :exc:`ValueError` to be raised. |
| 422 | |
| 423 | (2) |
| 424 | A left shift by *n* bits is equivalent to multiplication by ``pow(2, n)`` |
| 425 | without overflow check. |
| 426 | |
| 427 | (3) |
| 428 | A right shift by *n* bits is equivalent to division by ``pow(2, n)`` without |
| 429 | overflow check. |
| 430 | |
| 431 | |
Mark Dickinson | 54bc1ec | 2008-12-17 16:19:07 +0000 | [diff] [blame] | 432 | Additional Methods on Integer Types |
| 433 | ----------------------------------- |
| 434 | |
| 435 | .. method:: int.bit_length() |
| 436 | |
Raymond Hettinger | d3e18b7 | 2008-12-19 09:11:49 +0000 | [diff] [blame] | 437 | Return the number of bits necessary to represent an integer in binary, |
| 438 | excluding the sign and leading zeros:: |
Mark Dickinson | 54bc1ec | 2008-12-17 16:19:07 +0000 | [diff] [blame] | 439 | |
Raymond Hettinger | d3e18b7 | 2008-12-19 09:11:49 +0000 | [diff] [blame] | 440 | >>> n = -37 |
Mark Dickinson | 54bc1ec | 2008-12-17 16:19:07 +0000 | [diff] [blame] | 441 | >>> bin(n) |
Raymond Hettinger | d3e18b7 | 2008-12-19 09:11:49 +0000 | [diff] [blame] | 442 | '-0b100101' |
Mark Dickinson | 54bc1ec | 2008-12-17 16:19:07 +0000 | [diff] [blame] | 443 | >>> n.bit_length() |
| 444 | 6 |
Mark Dickinson | 54bc1ec | 2008-12-17 16:19:07 +0000 | [diff] [blame] | 445 | |
Raymond Hettinger | d3e18b7 | 2008-12-19 09:11:49 +0000 | [diff] [blame] | 446 | More precisely, if ``x`` is nonzero, then ``x.bit_length()`` is the |
| 447 | unique positive integer ``k`` such that ``2**(k-1) <= abs(x) < 2**k``. |
| 448 | Equivalently, when ``abs(x)`` is small enough to have a correctly |
| 449 | rounded logarithm, then ``k = 1 + int(log(abs(x), 2))``. |
| 450 | If ``x`` is zero, then ``x.bit_length()`` returns ``0``. |
Mark Dickinson | 54bc1ec | 2008-12-17 16:19:07 +0000 | [diff] [blame] | 451 | |
| 452 | Equivalent to:: |
| 453 | |
| 454 | def bit_length(self): |
Senthil Kumaran | fd51270 | 2010-06-22 02:46:49 +0000 | [diff] [blame] | 455 | s = bin(self) # binary representation: bin(-37) --> '-0b100101' |
Raymond Hettinger | d3e18b7 | 2008-12-19 09:11:49 +0000 | [diff] [blame] | 456 | s = s.lstrip('-0b') # remove leading zeros and minus sign |
| 457 | return len(s) # len('100101') --> 6 |
Mark Dickinson | 54bc1ec | 2008-12-17 16:19:07 +0000 | [diff] [blame] | 458 | |
| 459 | .. versionadded:: 3.1 |
| 460 | |
| 461 | |
Mark Dickinson | 65fe25e | 2008-07-16 11:30:51 +0000 | [diff] [blame] | 462 | Additional Methods on Float |
| 463 | --------------------------- |
| 464 | |
Benjamin Peterson | d7b0328 | 2008-09-13 15:58:53 +0000 | [diff] [blame] | 465 | The float type has some additional methods. |
| 466 | |
| 467 | .. method:: float.as_integer_ratio() |
| 468 | |
| 469 | Return a pair of integers whose ratio is exactly equal to the |
| 470 | original float and with a positive denominator. Raises |
| 471 | :exc:`OverflowError` on infinities and a :exc:`ValueError` on |
| 472 | NaNs. |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 473 | |
Benjamin Peterson | d7b0328 | 2008-09-13 15:58:53 +0000 | [diff] [blame] | 474 | Two methods support conversion to |
Mark Dickinson | 65fe25e | 2008-07-16 11:30:51 +0000 | [diff] [blame] | 475 | and from hexadecimal strings. Since Python's floats are stored |
| 476 | internally as binary numbers, converting a float to or from a |
| 477 | *decimal* string usually involves a small rounding error. In |
| 478 | contrast, hexadecimal strings allow exact representation and |
| 479 | specification of floating-point numbers. This can be useful when |
| 480 | debugging, and in numerical work. |
| 481 | |
| 482 | |
| 483 | .. method:: float.hex() |
| 484 | |
| 485 | Return a representation of a floating-point number as a hexadecimal |
| 486 | string. For finite floating-point numbers, this representation |
| 487 | will always include a leading ``0x`` and a trailing ``p`` and |
| 488 | exponent. |
| 489 | |
| 490 | |
Georg Brandl | abc3877 | 2009-04-12 15:51:51 +0000 | [diff] [blame] | 491 | .. classmethod:: float.fromhex(s) |
Mark Dickinson | 65fe25e | 2008-07-16 11:30:51 +0000 | [diff] [blame] | 492 | |
| 493 | Class method to return the float represented by a hexadecimal |
| 494 | string *s*. The string *s* may have leading and trailing |
| 495 | whitespace. |
| 496 | |
| 497 | |
| 498 | Note that :meth:`float.hex` is an instance method, while |
| 499 | :meth:`float.fromhex` is a class method. |
| 500 | |
| 501 | A hexadecimal string takes the form:: |
| 502 | |
| 503 | [sign] ['0x'] integer ['.' fraction] ['p' exponent] |
| 504 | |
| 505 | where the optional ``sign`` may by either ``+`` or ``-``, ``integer`` |
| 506 | and ``fraction`` are strings of hexadecimal digits, and ``exponent`` |
| 507 | is a decimal integer with an optional leading sign. Case is not |
| 508 | significant, and there must be at least one hexadecimal digit in |
| 509 | either the integer or the fraction. This syntax is similar to the |
| 510 | syntax specified in section 6.4.4.2 of the C99 standard, and also to |
| 511 | the syntax used in Java 1.5 onwards. In particular, the output of |
| 512 | :meth:`float.hex` is usable as a hexadecimal floating-point literal in |
| 513 | C or Java code, and hexadecimal strings produced by C's ``%a`` format |
| 514 | character or Java's ``Double.toHexString`` are accepted by |
| 515 | :meth:`float.fromhex`. |
| 516 | |
| 517 | |
| 518 | Note that the exponent is written in decimal rather than hexadecimal, |
| 519 | and that it gives the power of 2 by which to multiply the coefficient. |
| 520 | For example, the hexadecimal string ``0x3.a7p10`` represents the |
| 521 | floating-point number ``(3 + 10./16 + 7./16**2) * 2.0**10``, or |
| 522 | ``3740.0``:: |
| 523 | |
| 524 | >>> float.fromhex('0x3.a7p10') |
| 525 | 3740.0 |
| 526 | |
| 527 | |
| 528 | Applying the reverse conversion to ``3740.0`` gives a different |
| 529 | hexadecimal string representing the same number:: |
| 530 | |
| 531 | >>> float.hex(3740.0) |
| 532 | '0x1.d380000000000p+11' |
| 533 | |
| 534 | |
Georg Brandl | 6ea420b | 2008-07-16 12:58:29 +0000 | [diff] [blame] | 535 | .. _typeiter: |
| 536 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 537 | Iterator Types |
| 538 | ============== |
| 539 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 540 | .. index:: |
| 541 | single: iterator protocol |
| 542 | single: protocol; iterator |
| 543 | single: sequence; iteration |
| 544 | single: container; iteration over |
| 545 | |
| 546 | Python supports a concept of iteration over containers. This is implemented |
| 547 | using two distinct methods; these are used to allow user-defined classes to |
| 548 | support iteration. Sequences, described below in more detail, always support |
| 549 | the iteration methods. |
| 550 | |
| 551 | One method needs to be defined for container objects to provide iteration |
| 552 | support: |
| 553 | |
Christian Heimes | 790c823 | 2008-01-07 21:14:23 +0000 | [diff] [blame] | 554 | .. XXX duplicated in reference/datamodel! |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 555 | |
Christian Heimes | 790c823 | 2008-01-07 21:14:23 +0000 | [diff] [blame] | 556 | .. method:: container.__iter__() |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 557 | |
| 558 | Return an iterator object. The object is required to support the iterator |
| 559 | protocol described below. If a container supports different types of |
| 560 | iteration, additional methods can be provided to specifically request |
| 561 | iterators for those iteration types. (An example of an object supporting |
| 562 | multiple forms of iteration would be a tree structure which supports both |
| 563 | breadth-first and depth-first traversal.) This method corresponds to the |
| 564 | :attr:`tp_iter` slot of the type structure for Python objects in the Python/C |
| 565 | API. |
| 566 | |
| 567 | The iterator objects themselves are required to support the following two |
| 568 | methods, which together form the :dfn:`iterator protocol`: |
| 569 | |
| 570 | |
| 571 | .. method:: iterator.__iter__() |
| 572 | |
| 573 | Return the iterator object itself. This is required to allow both containers |
| 574 | and iterators to be used with the :keyword:`for` and :keyword:`in` statements. |
| 575 | This method corresponds to the :attr:`tp_iter` slot of the type structure for |
| 576 | Python objects in the Python/C API. |
| 577 | |
| 578 | |
Georg Brandl | 905ec32 | 2007-09-28 13:39:25 +0000 | [diff] [blame] | 579 | .. method:: iterator.__next__() |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 580 | |
| 581 | Return the next item from the container. If there are no further items, raise |
| 582 | the :exc:`StopIteration` exception. This method corresponds to the |
| 583 | :attr:`tp_iternext` slot of the type structure for Python objects in the |
| 584 | Python/C API. |
| 585 | |
| 586 | Python defines several iterator objects to support iteration over general and |
| 587 | specific sequence types, dictionaries, and other more specialized forms. The |
| 588 | specific types are not important beyond their implementation of the iterator |
| 589 | protocol. |
| 590 | |
Georg Brandl | 905ec32 | 2007-09-28 13:39:25 +0000 | [diff] [blame] | 591 | Once an iterator's :meth:`__next__` method raises :exc:`StopIteration`, it must |
| 592 | continue to do so on subsequent calls. Implementations that do not obey this |
| 593 | property are deemed broken. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 594 | |
Benjamin Peterson | d76c8da | 2009-06-28 17:35:48 +0000 | [diff] [blame] | 595 | |
| 596 | .. _generator-types: |
| 597 | |
| 598 | Generator Types |
| 599 | --------------- |
| 600 | |
Georg Brandl | 9afde1c | 2007-11-01 20:32:30 +0000 | [diff] [blame] | 601 | Python's :term:`generator`\s provide a convenient way to implement the iterator |
| 602 | protocol. If a container object's :meth:`__iter__` method is implemented as a |
| 603 | generator, it will automatically return an iterator object (technically, a |
| 604 | generator object) supplying the :meth:`__iter__` and :meth:`__next__` methods. |
Benjamin Peterson | d76c8da | 2009-06-28 17:35:48 +0000 | [diff] [blame] | 605 | More information about generators can be found in :ref:`the documentation for |
| 606 | the yield expression <yieldexpr>`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 607 | |
| 608 | |
| 609 | .. _typesseq: |
| 610 | |
Georg Brandl | 9541463 | 2007-11-22 11:00:28 +0000 | [diff] [blame] | 611 | Sequence Types --- :class:`str`, :class:`bytes`, :class:`bytearray`, :class:`list`, :class:`tuple`, :class:`range` |
| 612 | ================================================================================================================== |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 613 | |
Georg Brandl | e17d586 | 2009-01-18 10:40:25 +0000 | [diff] [blame] | 614 | There are six sequence types: strings, byte sequences (:class:`bytes` objects), |
Benjamin Peterson | b58dda7 | 2009-01-18 22:27:04 +0000 | [diff] [blame] | 615 | byte arrays (:class:`bytearray` objects), lists, tuples, and range objects. For |
| 616 | other containers see the built in :class:`dict` and :class:`set` classes, and |
| 617 | the :mod:`collections` module. |
Georg Brandl | e17d586 | 2009-01-18 10:40:25 +0000 | [diff] [blame] | 618 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 619 | |
| 620 | .. index:: |
| 621 | object: sequence |
| 622 | object: string |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 623 | object: bytes |
Georg Brandl | e17d586 | 2009-01-18 10:40:25 +0000 | [diff] [blame] | 624 | object: bytearray |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 625 | object: tuple |
| 626 | object: list |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 627 | object: range |
| 628 | |
Georg Brandl | 7c67613 | 2007-10-23 18:17:00 +0000 | [diff] [blame] | 629 | Strings contain Unicode characters. Their literals are written in single or |
| 630 | double quotes: ``'xyzzy'``, ``"frobozz"``. See :ref:`strings` for more about |
| 631 | string literals. In addition to the functionality described here, there are |
| 632 | also string-specific methods described in the :ref:`string-methods` section. |
| 633 | |
Georg Brandl | 9541463 | 2007-11-22 11:00:28 +0000 | [diff] [blame] | 634 | Bytes and bytearray objects contain single bytes -- the former is immutable |
Georg Brandl | 18da8f0 | 2008-07-01 20:08:02 +0000 | [diff] [blame] | 635 | while the latter is a mutable sequence. Bytes objects can be constructed the |
| 636 | constructor, :func:`bytes`, and from literals; use a ``b`` prefix with normal |
| 637 | string syntax: ``b'xyzzy'``. To construct byte arrays, use the |
| 638 | :func:`bytearray` function. |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 639 | |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 640 | .. warning:: |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 641 | |
| 642 | While string objects are sequences of characters (represented by strings of |
Georg Brandl | 9541463 | 2007-11-22 11:00:28 +0000 | [diff] [blame] | 643 | length 1), bytes and bytearray objects are sequences of *integers* (between 0 |
Georg Brandl | 7c67613 | 2007-10-23 18:17:00 +0000 | [diff] [blame] | 644 | and 255), representing the ASCII value of single bytes. That means that for |
Georg Brandl | 18da8f0 | 2008-07-01 20:08:02 +0000 | [diff] [blame] | 645 | a bytes or bytearray object *b*, ``b[0]`` will be an integer, while |
| 646 | ``b[0:1]`` will be a bytes or bytearray object of length 1. The |
| 647 | representation of bytes objects uses the literal format (``b'...'``) since it |
| 648 | is generally more useful than e.g. ``bytes([50, 19, 100])``. You can always |
| 649 | convert a bytes object into a list of integers using ``list(b)``. |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 650 | |
Georg Brandl | 2326a79 | 2007-09-01 12:08:51 +0000 | [diff] [blame] | 651 | Also, while in previous Python versions, byte strings and Unicode strings |
| 652 | could be exchanged for each other rather freely (barring encoding issues), |
Georg Brandl | 7c67613 | 2007-10-23 18:17:00 +0000 | [diff] [blame] | 653 | strings and bytes are now completely separate concepts. There's no implicit |
Ezio Melotti | 4cadc7f | 2009-12-31 12:26:02 +0000 | [diff] [blame] | 654 | en-/decoding if you pass an object of the wrong type. A string always |
Georg Brandl | 9541463 | 2007-11-22 11:00:28 +0000 | [diff] [blame] | 655 | compares unequal to a bytes or bytearray object. |
Georg Brandl | 2326a79 | 2007-09-01 12:08:51 +0000 | [diff] [blame] | 656 | |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 657 | Lists are constructed with square brackets, separating items with commas: ``[a, |
| 658 | b, c]``. Tuples are constructed by the comma operator (not within square |
| 659 | brackets), with or without enclosing parentheses, but an empty tuple must have |
| 660 | the enclosing parentheses, such as ``a, b, c`` or ``()``. A single item tuple |
| 661 | must have a trailing comma, such as ``(d,)``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 662 | |
Georg Brandl | 9541463 | 2007-11-22 11:00:28 +0000 | [diff] [blame] | 663 | Objects of type range are created using the :func:`range` function. They don't |
| 664 | support slicing, concatenation or repetition, and using ``in``, ``not in``, |
| 665 | :func:`min` or :func:`max` on them is inefficient. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 666 | |
| 667 | Most sequence types support the following operations. The ``in`` and ``not in`` |
| 668 | operations have the same priorities as the comparison operations. The ``+`` and |
| 669 | ``*`` operations have the same priority as the corresponding numeric operations. |
Christian Heimes | 043d6f6 | 2008-01-07 17:19:16 +0000 | [diff] [blame] | 670 | [#]_ Additional methods are provided for :ref:`typesseq-mutable`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 671 | |
| 672 | This table lists the sequence operations sorted in ascending priority |
| 673 | (operations in the same box have the same priority). In the table, *s* and *t* |
| 674 | are sequences of the same type; *n*, *i* and *j* are integers: |
| 675 | |
| 676 | +------------------+--------------------------------+----------+ |
| 677 | | Operation | Result | Notes | |
| 678 | +==================+================================+==========+ |
| 679 | | ``x in s`` | ``True`` if an item of *s* is | \(1) | |
| 680 | | | equal to *x*, else ``False`` | | |
| 681 | +------------------+--------------------------------+----------+ |
| 682 | | ``x not in s`` | ``False`` if an item of *s* is | \(1) | |
| 683 | | | equal to *x*, else ``True`` | | |
| 684 | +------------------+--------------------------------+----------+ |
| 685 | | ``s + t`` | the concatenation of *s* and | \(6) | |
| 686 | | | *t* | | |
| 687 | +------------------+--------------------------------+----------+ |
| 688 | | ``s * n, n * s`` | *n* shallow copies of *s* | \(2) | |
| 689 | | | concatenated | | |
| 690 | +------------------+--------------------------------+----------+ |
| 691 | | ``s[i]`` | *i*'th item of *s*, origin 0 | \(3) | |
| 692 | +------------------+--------------------------------+----------+ |
Christian Heimes | 043d6f6 | 2008-01-07 17:19:16 +0000 | [diff] [blame] | 693 | | ``s[i:j]`` | slice of *s* from *i* to *j* | (3)(4) | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 694 | +------------------+--------------------------------+----------+ |
Christian Heimes | 043d6f6 | 2008-01-07 17:19:16 +0000 | [diff] [blame] | 695 | | ``s[i:j:k]`` | slice of *s* from *i* to *j* | (3)(5) | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 696 | | | with step *k* | | |
| 697 | +------------------+--------------------------------+----------+ |
| 698 | | ``len(s)`` | length of *s* | | |
| 699 | +------------------+--------------------------------+----------+ |
| 700 | | ``min(s)`` | smallest item of *s* | | |
| 701 | +------------------+--------------------------------+----------+ |
| 702 | | ``max(s)`` | largest item of *s* | | |
| 703 | +------------------+--------------------------------+----------+ |
| 704 | |
Georg Brandl | 7c67613 | 2007-10-23 18:17:00 +0000 | [diff] [blame] | 705 | Sequence types also support comparisons. In particular, tuples and lists are |
| 706 | compared lexicographically by comparing corresponding elements. This means that |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 707 | to compare equal, every element must compare equal and the two sequences must be |
Georg Brandl | 7c67613 | 2007-10-23 18:17:00 +0000 | [diff] [blame] | 708 | of the same type and have the same length. (For full details see |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 709 | :ref:`comparisons` in the language reference.) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 710 | |
| 711 | .. index:: |
| 712 | triple: operations on; sequence; types |
| 713 | builtin: len |
| 714 | builtin: min |
| 715 | builtin: max |
| 716 | pair: concatenation; operation |
| 717 | pair: repetition; operation |
| 718 | pair: subscript; operation |
| 719 | pair: slice; operation |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 720 | operator: in |
| 721 | operator: not in |
| 722 | |
| 723 | Notes: |
| 724 | |
| 725 | (1) |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 726 | When *s* is a string object, the ``in`` and ``not in`` operations act like a |
| 727 | substring test. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 728 | |
| 729 | (2) |
| 730 | Values of *n* less than ``0`` are treated as ``0`` (which yields an empty |
| 731 | sequence of the same type as *s*). Note also that the copies are shallow; |
| 732 | nested structures are not copied. This often haunts new Python programmers; |
Christian Heimes | fe337bf | 2008-03-23 21:54:12 +0000 | [diff] [blame] | 733 | consider: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 734 | |
| 735 | >>> lists = [[]] * 3 |
| 736 | >>> lists |
| 737 | [[], [], []] |
| 738 | >>> lists[0].append(3) |
| 739 | >>> lists |
| 740 | [[3], [3], [3]] |
| 741 | |
| 742 | What has happened is that ``[[]]`` is a one-element list containing an empty |
Christian Heimes | fe337bf | 2008-03-23 21:54:12 +0000 | [diff] [blame] | 743 | list, so all three elements of ``[[]] * 3`` are (pointers to) this single empty |
| 744 | list. Modifying any of the elements of ``lists`` modifies this single list. |
| 745 | You can create a list of different lists this way: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 746 | |
| 747 | >>> lists = [[] for i in range(3)] |
| 748 | >>> lists[0].append(3) |
| 749 | >>> lists[1].append(5) |
| 750 | >>> lists[2].append(7) |
| 751 | >>> lists |
| 752 | [[3], [5], [7]] |
| 753 | |
| 754 | (3) |
| 755 | If *i* or *j* is negative, the index is relative to the end of the string: |
Georg Brandl | 7c67613 | 2007-10-23 18:17:00 +0000 | [diff] [blame] | 756 | ``len(s) + i`` or ``len(s) + j`` is substituted. But note that ``-0`` is |
| 757 | still ``0``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 758 | |
| 759 | (4) |
| 760 | The slice of *s* from *i* to *j* is defined as the sequence of items with index |
| 761 | *k* such that ``i <= k < j``. If *i* or *j* is greater than ``len(s)``, use |
| 762 | ``len(s)``. If *i* is omitted or ``None``, use ``0``. If *j* is omitted or |
| 763 | ``None``, use ``len(s)``. If *i* is greater than or equal to *j*, the slice is |
| 764 | empty. |
| 765 | |
| 766 | (5) |
| 767 | The slice of *s* from *i* to *j* with step *k* is defined as the sequence of |
Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 768 | items with index ``x = i + n*k`` such that ``0 <= n < (j-i)/k``. In other words, |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 769 | the indices are ``i``, ``i+k``, ``i+2*k``, ``i+3*k`` and so on, stopping when |
| 770 | *j* is reached (but never including *j*). If *i* or *j* is greater than |
| 771 | ``len(s)``, use ``len(s)``. If *i* or *j* are omitted or ``None``, they become |
| 772 | "end" values (which end depends on the sign of *k*). Note, *k* cannot be zero. |
| 773 | If *k* is ``None``, it is treated like ``1``. |
| 774 | |
| 775 | (6) |
Georg Brandl | 628e6f9 | 2009-10-27 20:24:45 +0000 | [diff] [blame] | 776 | .. impl-detail:: |
| 777 | |
| 778 | If *s* and *t* are both strings, some Python implementations such as |
| 779 | CPython can usually perform an in-place optimization for assignments of |
| 780 | the form ``s = s + t`` or ``s += t``. When applicable, this optimization |
| 781 | makes quadratic run-time much less likely. This optimization is both |
| 782 | version and implementation dependent. For performance sensitive code, it |
| 783 | is preferable to use the :meth:`str.join` method which assures consistent |
| 784 | linear concatenation performance across versions and implementations. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 785 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 786 | |
| 787 | .. _string-methods: |
| 788 | |
| 789 | String Methods |
| 790 | -------------- |
| 791 | |
| 792 | .. index:: pair: string; methods |
| 793 | |
Thomas Wouters | 8ce81f7 | 2007-09-20 18:22:40 +0000 | [diff] [blame] | 794 | String objects support the methods listed below. Note that none of these |
| 795 | methods take keyword arguments. |
| 796 | |
| 797 | In addition, Python's strings support the sequence type methods described in |
| 798 | the :ref:`typesseq` section. To output formatted strings, see the |
| 799 | :ref:`string-formatting` section. Also, see the :mod:`re` module for string |
| 800 | functions based on regular expressions. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 801 | |
| 802 | .. method:: str.capitalize() |
| 803 | |
Senthil Kumaran | 3592a46 | 2010-07-05 11:44:49 +0000 | [diff] [blame] | 804 | Return a copy of the string with its first character capitalized and the |
Senthil Kumaran | 317ac61 | 2010-07-06 03:03:34 +0000 | [diff] [blame] | 805 | rest lowercased. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 806 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 807 | |
| 808 | .. method:: str.center(width[, fillchar]) |
| 809 | |
| 810 | Return centered in a string of length *width*. Padding is done using the |
| 811 | specified *fillchar* (default is a space). |
| 812 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 813 | |
| 814 | .. method:: str.count(sub[, start[, end]]) |
| 815 | |
Benjamin Peterson | ad3d5c2 | 2009-02-26 03:38:59 +0000 | [diff] [blame] | 816 | Return the number of non-overlapping occurrences of substring *sub* in the |
| 817 | range [*start*, *end*]. Optional arguments *start* and *end* are |
| 818 | interpreted as in slice notation. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 819 | |
| 820 | |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 821 | .. method:: str.encode([encoding[, errors]]) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 822 | |
Georg Brandl | 4f5f98d | 2009-05-04 21:01:20 +0000 | [diff] [blame] | 823 | Return an encoded version of the string as a bytes object. Default encoding |
| 824 | is the current default string encoding. *errors* may be given to set a |
| 825 | different error handling scheme. The default for *errors* is ``'strict'``, |
| 826 | meaning that encoding errors raise a :exc:`UnicodeError`. Other possible |
| 827 | values are ``'ignore'``, ``'replace'``, ``'xmlcharrefreplace'``, |
| 828 | ``'backslashreplace'`` and any other name registered via |
| 829 | :func:`codecs.register_error`, see section :ref:`codec-base-classes`. For a |
| 830 | list of possible encodings, see section :ref:`standard-encodings`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 831 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 832 | |
| 833 | .. method:: str.endswith(suffix[, start[, end]]) |
| 834 | |
| 835 | Return ``True`` if the string ends with the specified *suffix*, otherwise return |
| 836 | ``False``. *suffix* can also be a tuple of suffixes to look for. With optional |
| 837 | *start*, test beginning at that position. With optional *end*, stop comparing |
| 838 | at that position. |
| 839 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 840 | |
| 841 | .. method:: str.expandtabs([tabsize]) |
| 842 | |
Georg Brandl | 9afde1c | 2007-11-01 20:32:30 +0000 | [diff] [blame] | 843 | Return a copy of the string where all tab characters are replaced by one or |
| 844 | more spaces, depending on the current column and the given tab size. The |
| 845 | column number is reset to zero after each newline occurring in the string. |
| 846 | If *tabsize* is not given, a tab size of ``8`` characters is assumed. This |
| 847 | doesn't understand other non-printing characters or escape sequences. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 848 | |
| 849 | |
| 850 | .. method:: str.find(sub[, start[, end]]) |
| 851 | |
Benjamin Peterson | 480269e | 2010-04-27 23:04:53 +0000 | [diff] [blame] | 852 | Return the lowest index in the string where substring *sub* is found, such |
| 853 | that *sub* is contained in the slice ``s[start:end]``. Optional arguments |
| 854 | *start* and *end* are interpreted as in slice notation. Return ``-1`` if |
| 855 | *sub* is not found. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 856 | |
| 857 | |
Benjamin Peterson | ad3d5c2 | 2009-02-26 03:38:59 +0000 | [diff] [blame] | 858 | .. method:: str.format(*args, **kwargs) |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 859 | |
| 860 | Perform a string formatting operation. The *format_string* argument can |
| 861 | contain literal text or replacement fields delimited by braces ``{}``. Each |
| 862 | replacement field contains either the numeric index of a positional argument, |
| 863 | or the name of a keyword argument. Returns a copy of *format_string* where |
| 864 | each replacement field is replaced with the string value of the corresponding |
| 865 | argument. |
| 866 | |
| 867 | >>> "The sum of 1 + 2 is {0}".format(1+2) |
| 868 | 'The sum of 1 + 2 is 3' |
| 869 | |
| 870 | See :ref:`formatstrings` for a description of the various formatting options |
| 871 | that can be specified in format strings. |
| 872 | |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 873 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 874 | .. method:: str.index(sub[, start[, end]]) |
| 875 | |
| 876 | Like :meth:`find`, but raise :exc:`ValueError` when the substring is not found. |
| 877 | |
| 878 | |
| 879 | .. method:: str.isalnum() |
| 880 | |
| 881 | Return true if all characters in the string are alphanumeric and there is at |
| 882 | least one character, false otherwise. |
| 883 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 884 | |
| 885 | .. method:: str.isalpha() |
| 886 | |
| 887 | Return true if all characters in the string are alphabetic and there is at least |
| 888 | one character, false otherwise. |
| 889 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 890 | |
Mark Summerfield | bbfd71d | 2008-07-01 15:50:04 +0000 | [diff] [blame] | 891 | .. method:: str.isdecimal() |
| 892 | |
| 893 | Return true if all characters in the string are decimal |
| 894 | characters and there is at least one character, false |
| 895 | otherwise. Decimal characters include digit characters, and all characters |
| 896 | that that can be used to form decimal-radix numbers, e.g. U+0660, |
| 897 | ARABIC-INDIC DIGIT ZERO. |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 898 | |
Mark Summerfield | bbfd71d | 2008-07-01 15:50:04 +0000 | [diff] [blame] | 899 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 900 | .. method:: str.isdigit() |
| 901 | |
| 902 | Return true if all characters in the string are digits and there is at least one |
| 903 | character, false otherwise. |
| 904 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 905 | |
| 906 | .. method:: str.isidentifier() |
| 907 | |
| 908 | Return true if the string is a valid identifier according to the language |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 909 | definition, section :ref:`identifiers`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 910 | |
| 911 | |
| 912 | .. method:: str.islower() |
| 913 | |
| 914 | Return true if all cased characters in the string are lowercase and there is at |
| 915 | least one cased character, false otherwise. |
| 916 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 917 | |
Mark Summerfield | bbfd71d | 2008-07-01 15:50:04 +0000 | [diff] [blame] | 918 | .. method:: str.isnumeric() |
| 919 | |
| 920 | Return true if all characters in the string are numeric |
| 921 | characters, and there is at least one character, false |
| 922 | otherwise. Numeric characters include digit characters, and all characters |
| 923 | that have the Unicode numeric value property, e.g. U+2155, |
| 924 | VULGAR FRACTION ONE FIFTH. |
| 925 | |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 926 | |
Georg Brandl | 559e5d7 | 2008-06-11 18:37:52 +0000 | [diff] [blame] | 927 | .. method:: str.isprintable() |
| 928 | |
| 929 | Return true if all characters in the string are printable or the string is |
| 930 | empty, false otherwise. Nonprintable characters are those characters defined |
| 931 | in the Unicode character database as "Other" or "Separator", excepting the |
| 932 | ASCII space (0x20) which is considered printable. (Note that printable |
| 933 | characters in this context are those which should not be escaped when |
| 934 | :func:`repr` is invoked on a string. It has no bearing on the handling of |
| 935 | strings written to :data:`sys.stdout` or :data:`sys.stderr`.) |
| 936 | |
| 937 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 938 | .. method:: str.isspace() |
| 939 | |
| 940 | Return true if there are only whitespace characters in the string and there is |
| 941 | at least one character, false otherwise. |
| 942 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 943 | |
| 944 | .. method:: str.istitle() |
| 945 | |
| 946 | Return true if the string is a titlecased string and there is at least one |
| 947 | character, for example uppercase characters may only follow uncased characters |
| 948 | and lowercase characters only cased ones. Return false otherwise. |
| 949 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 950 | |
| 951 | .. method:: str.isupper() |
| 952 | |
| 953 | Return true if all cased characters in the string are uppercase and there is at |
| 954 | least one cased character, false otherwise. |
| 955 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 956 | |
Georg Brandl | 628e6f9 | 2009-10-27 20:24:45 +0000 | [diff] [blame] | 957 | .. method:: str.join(iterable) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 958 | |
Georg Brandl | 628e6f9 | 2009-10-27 20:24:45 +0000 | [diff] [blame] | 959 | Return a string which is the concatenation of the strings in the |
| 960 | :term:`iterable` *iterable*. A :exc:`TypeError` will be raised if there are |
| 961 | any non-string values in *seq*, including :class:`bytes` objects. The |
| 962 | separator between elements is the string providing this method. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 963 | |
| 964 | |
| 965 | .. method:: str.ljust(width[, fillchar]) |
| 966 | |
| 967 | Return the string left justified in a string of length *width*. Padding is done |
| 968 | using the specified *fillchar* (default is a space). The original string is |
| 969 | returned if *width* is less than ``len(s)``. |
| 970 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 971 | |
| 972 | .. method:: str.lower() |
| 973 | |
| 974 | Return a copy of the string converted to lowercase. |
| 975 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 976 | |
| 977 | .. method:: str.lstrip([chars]) |
| 978 | |
| 979 | Return a copy of the string with leading characters removed. The *chars* |
| 980 | argument is a string specifying the set of characters to be removed. If omitted |
| 981 | or ``None``, the *chars* argument defaults to removing whitespace. The *chars* |
Christian Heimes | fe337bf | 2008-03-23 21:54:12 +0000 | [diff] [blame] | 982 | argument is not a prefix; rather, all combinations of its values are stripped: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 983 | |
| 984 | >>> ' spacious '.lstrip() |
| 985 | 'spacious ' |
| 986 | >>> 'www.example.com'.lstrip('cmowz.') |
| 987 | 'example.com' |
| 988 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 989 | |
Georg Brandl | abc3877 | 2009-04-12 15:51:51 +0000 | [diff] [blame] | 990 | .. staticmethod:: str.maketrans(x[, y[, z]]) |
Georg Brandl | ceee077 | 2007-11-27 23:48:05 +0000 | [diff] [blame] | 991 | |
| 992 | This static method returns a translation table usable for :meth:`str.translate`. |
| 993 | |
| 994 | If there is only one argument, it must be a dictionary mapping Unicode |
| 995 | ordinals (integers) or characters (strings of length 1) to Unicode ordinals, |
| 996 | strings (of arbitrary lengths) or None. Character keys will then be |
| 997 | converted to ordinals. |
| 998 | |
| 999 | If there are two arguments, they must be strings of equal length, and in the |
| 1000 | resulting dictionary, each character in x will be mapped to the character at |
| 1001 | the same position in y. If there is a third argument, it must be a string, |
| 1002 | whose characters will be mapped to None in the result. |
| 1003 | |
| 1004 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1005 | .. method:: str.partition(sep) |
| 1006 | |
| 1007 | Split the string at the first occurrence of *sep*, and return a 3-tuple |
| 1008 | containing the part before the separator, the separator itself, and the part |
| 1009 | after the separator. If the separator is not found, return a 3-tuple containing |
| 1010 | the string itself, followed by two empty strings. |
| 1011 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1012 | |
| 1013 | .. method:: str.replace(old, new[, count]) |
| 1014 | |
| 1015 | Return a copy of the string with all occurrences of substring *old* replaced by |
| 1016 | *new*. If the optional argument *count* is given, only the first *count* |
| 1017 | occurrences are replaced. |
| 1018 | |
| 1019 | |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 1020 | .. method:: str.rfind(sub[, start[, end]]) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1021 | |
Benjamin Peterson | 480269e | 2010-04-27 23:04:53 +0000 | [diff] [blame] | 1022 | Return the highest index in the string where substring *sub* is found, such |
| 1023 | that *sub* is contained within ``s[start:end]``. Optional arguments *start* |
| 1024 | and *end* are interpreted as in slice notation. Return ``-1`` on failure. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1025 | |
| 1026 | |
| 1027 | .. method:: str.rindex(sub[, start[, end]]) |
| 1028 | |
| 1029 | Like :meth:`rfind` but raises :exc:`ValueError` when the substring *sub* is not |
| 1030 | found. |
| 1031 | |
| 1032 | |
| 1033 | .. method:: str.rjust(width[, fillchar]) |
| 1034 | |
| 1035 | Return the string right justified in a string of length *width*. Padding is done |
| 1036 | using the specified *fillchar* (default is a space). The original string is |
| 1037 | returned if *width* is less than ``len(s)``. |
| 1038 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1039 | |
| 1040 | .. method:: str.rpartition(sep) |
| 1041 | |
| 1042 | Split the string at the last occurrence of *sep*, and return a 3-tuple |
| 1043 | containing the part before the separator, the separator itself, and the part |
| 1044 | after the separator. If the separator is not found, return a 3-tuple containing |
| 1045 | two empty strings, followed by the string itself. |
| 1046 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1047 | |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 1048 | .. method:: str.rsplit([sep[, maxsplit]]) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1049 | |
| 1050 | Return a list of the words in the string, using *sep* as the delimiter string. |
| 1051 | If *maxsplit* is given, at most *maxsplit* splits are done, the *rightmost* |
| 1052 | ones. If *sep* is not specified or ``None``, any whitespace string is a |
| 1053 | separator. Except for splitting from the right, :meth:`rsplit` behaves like |
| 1054 | :meth:`split` which is described in detail below. |
| 1055 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1056 | |
| 1057 | .. method:: str.rstrip([chars]) |
| 1058 | |
| 1059 | Return a copy of the string with trailing characters removed. The *chars* |
| 1060 | argument is a string specifying the set of characters to be removed. If omitted |
| 1061 | or ``None``, the *chars* argument defaults to removing whitespace. The *chars* |
Christian Heimes | fe337bf | 2008-03-23 21:54:12 +0000 | [diff] [blame] | 1062 | argument is not a suffix; rather, all combinations of its values are stripped: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1063 | |
| 1064 | >>> ' spacious '.rstrip() |
| 1065 | ' spacious' |
| 1066 | >>> 'mississippi'.rstrip('ipz') |
| 1067 | 'mississ' |
| 1068 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1069 | |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 1070 | .. method:: str.split([sep[, maxsplit]]) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1071 | |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 1072 | Return a list of the words in the string, using *sep* as the delimiter |
| 1073 | string. If *maxsplit* is given, at most *maxsplit* splits are done (thus, |
| 1074 | the list will have at most ``maxsplit+1`` elements). If *maxsplit* is not |
| 1075 | specified, then there is no limit on the number of splits (all possible |
Georg Brandl | 9afde1c | 2007-11-01 20:32:30 +0000 | [diff] [blame] | 1076 | splits are made). |
| 1077 | |
Guido van Rossum | 2cc30da | 2007-11-02 23:46:40 +0000 | [diff] [blame] | 1078 | If *sep* is given, consecutive delimiters are not grouped together and are |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 1079 | deemed to delimit empty strings (for example, ``'1,,2'.split(',')`` returns |
| 1080 | ``['1', '', '2']``). The *sep* argument may consist of multiple characters |
Georg Brandl | 9afde1c | 2007-11-01 20:32:30 +0000 | [diff] [blame] | 1081 | (for example, ``'1<>2<>3'.split('<>')`` returns ``['1', '2', '3']``). |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 1082 | Splitting an empty string with a specified separator returns ``['']``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1083 | |
| 1084 | If *sep* is not specified or is ``None``, a different splitting algorithm is |
Georg Brandl | 9afde1c | 2007-11-01 20:32:30 +0000 | [diff] [blame] | 1085 | applied: runs of consecutive whitespace are regarded as a single separator, |
| 1086 | and the result will contain no empty strings at the start or end if the |
| 1087 | string has leading or trailing whitespace. Consequently, splitting an empty |
| 1088 | string or a string consisting of just whitespace with a ``None`` separator |
| 1089 | returns ``[]``. |
| 1090 | |
| 1091 | For example, ``' 1 2 3 '.split()`` returns ``['1', '2', '3']``, and |
| 1092 | ``' 1 2 3 '.split(None, 1)`` returns ``['1', '2 3 ']``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1093 | |
| 1094 | |
| 1095 | .. method:: str.splitlines([keepends]) |
| 1096 | |
| 1097 | Return a list of the lines in the string, breaking at line boundaries. Line |
| 1098 | breaks are not included in the resulting list unless *keepends* is given and |
| 1099 | true. |
| 1100 | |
| 1101 | |
| 1102 | .. method:: str.startswith(prefix[, start[, end]]) |
| 1103 | |
| 1104 | Return ``True`` if string starts with the *prefix*, otherwise return ``False``. |
| 1105 | *prefix* can also be a tuple of prefixes to look for. With optional *start*, |
| 1106 | test string beginning at that position. With optional *end*, stop comparing |
| 1107 | string at that position. |
| 1108 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1109 | |
| 1110 | .. method:: str.strip([chars]) |
| 1111 | |
| 1112 | Return a copy of the string with the leading and trailing characters removed. |
| 1113 | The *chars* argument is a string specifying the set of characters to be removed. |
| 1114 | If omitted or ``None``, the *chars* argument defaults to removing whitespace. |
| 1115 | The *chars* argument is not a prefix or suffix; rather, all combinations of its |
Christian Heimes | fe337bf | 2008-03-23 21:54:12 +0000 | [diff] [blame] | 1116 | values are stripped: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1117 | |
| 1118 | >>> ' spacious '.strip() |
| 1119 | 'spacious' |
| 1120 | >>> 'www.example.com'.strip('cmowz.') |
| 1121 | 'example' |
| 1122 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1123 | |
| 1124 | .. method:: str.swapcase() |
| 1125 | |
| 1126 | Return a copy of the string with uppercase characters converted to lowercase and |
| 1127 | vice versa. |
| 1128 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1129 | |
| 1130 | .. method:: str.title() |
| 1131 | |
Raymond Hettinger | 941071e | 2009-09-29 18:56:36 +0000 | [diff] [blame] | 1132 | Return a titlecased version of the string where words start with an uppercase |
| 1133 | character and the remaining characters are lowercase. |
| 1134 | |
| 1135 | The algorithm uses a simple language-independent definition of a word as |
| 1136 | groups of consecutive letters. The definition works in many contexts but |
| 1137 | it means that apostrophes in contractions and possessives form word |
| 1138 | boundaries, which may not be the desired result:: |
| 1139 | |
| 1140 | >>> "they're bill's friends from the UK".title() |
| 1141 | "They'Re Bill'S Friends From The Uk" |
| 1142 | |
| 1143 | A workaround for apostrophes can be constructed using regular expressions:: |
| 1144 | |
| 1145 | >>> import re |
| 1146 | >>> def titlecase(s): |
| 1147 | return re.sub(r"[A-Za-z]+('[A-Za-z]+)?", |
| 1148 | lambda mo: mo.group(0)[0].upper() + |
| 1149 | mo.group(0)[1:].lower(), |
| 1150 | s) |
| 1151 | |
| 1152 | >>> titlecase("they're bill's friends.") |
| 1153 | "They're Bill's Friends." |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1154 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1155 | |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 1156 | .. method:: str.translate(map) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1157 | |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 1158 | Return a copy of the *s* where all characters have been mapped through the |
Georg Brandl | 454636f | 2008-12-27 23:33:20 +0000 | [diff] [blame] | 1159 | *map* which must be a dictionary of Unicode ordinals (integers) to Unicode |
Georg Brandl | ceee077 | 2007-11-27 23:48:05 +0000 | [diff] [blame] | 1160 | ordinals, strings or ``None``. Unmapped characters are left untouched. |
| 1161 | Characters mapped to ``None`` are deleted. |
| 1162 | |
Georg Brandl | 454636f | 2008-12-27 23:33:20 +0000 | [diff] [blame] | 1163 | You can use :meth:`str.maketrans` to create a translation map from |
| 1164 | character-to-character mappings in different formats. |
Christian Heimes | fe337bf | 2008-03-23 21:54:12 +0000 | [diff] [blame] | 1165 | |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 1166 | .. note:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1167 | |
Georg Brandl | ceee077 | 2007-11-27 23:48:05 +0000 | [diff] [blame] | 1168 | An even more flexible approach is to create a custom character mapping |
| 1169 | codec using the :mod:`codecs` module (see :mod:`encodings.cp1251` for an |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 1170 | example). |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1171 | |
| 1172 | |
| 1173 | .. method:: str.upper() |
| 1174 | |
| 1175 | Return a copy of the string converted to uppercase. |
| 1176 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1177 | |
| 1178 | .. method:: str.zfill(width) |
| 1179 | |
Georg Brandl | 9afde1c | 2007-11-01 20:32:30 +0000 | [diff] [blame] | 1180 | Return the numeric string left filled with zeros in a string of length |
| 1181 | *width*. A sign prefix is handled correctly. The original string is |
| 1182 | returned if *width* is less than ``len(s)``. |
Christian Heimes | b186d00 | 2008-03-18 15:15:01 +0000 | [diff] [blame] | 1183 | |
| 1184 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1185 | |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 1186 | .. _old-string-formatting: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1187 | |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 1188 | Old String Formatting Operations |
| 1189 | -------------------------------- |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1190 | |
| 1191 | .. index:: |
| 1192 | single: formatting, string (%) |
| 1193 | single: interpolation, string (%) |
| 1194 | single: string; formatting |
| 1195 | single: string; interpolation |
| 1196 | single: printf-style formatting |
| 1197 | single: sprintf-style formatting |
| 1198 | single: % formatting |
| 1199 | single: % interpolation |
| 1200 | |
Georg Brandl | 81ac1ce | 2007-08-31 17:17:17 +0000 | [diff] [blame] | 1201 | .. XXX is the note enough? |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 1202 | |
| 1203 | .. note:: |
| 1204 | |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 1205 | The formatting operations described here are obsolete and may go away in future |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 1206 | versions of Python. Use the new :ref:`string-formatting` in new code. |
| 1207 | |
| 1208 | String objects have one unique built-in operation: the ``%`` operator (modulo). |
| 1209 | This is also known as the string *formatting* or *interpolation* operator. |
| 1210 | Given ``format % values`` (where *format* is a string), ``%`` conversion |
| 1211 | specifications in *format* are replaced with zero or more elements of *values*. |
| 1212 | The effect is similar to the using :cfunc:`sprintf` in the C language. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1213 | |
| 1214 | If *format* requires a single argument, *values* may be a single non-tuple |
| 1215 | object. [#]_ Otherwise, *values* must be a tuple with exactly the number of |
| 1216 | items specified by the format string, or a single mapping object (for example, a |
| 1217 | dictionary). |
| 1218 | |
| 1219 | A conversion specifier contains two or more characters and has the following |
| 1220 | components, which must occur in this order: |
| 1221 | |
| 1222 | #. The ``'%'`` character, which marks the start of the specifier. |
| 1223 | |
| 1224 | #. Mapping key (optional), consisting of a parenthesised sequence of characters |
| 1225 | (for example, ``(somename)``). |
| 1226 | |
| 1227 | #. Conversion flags (optional), which affect the result of some conversion |
| 1228 | types. |
| 1229 | |
| 1230 | #. Minimum field width (optional). If specified as an ``'*'`` (asterisk), the |
| 1231 | actual width is read from the next element of the tuple in *values*, and the |
| 1232 | object to convert comes after the minimum field width and optional precision. |
| 1233 | |
| 1234 | #. Precision (optional), given as a ``'.'`` (dot) followed by the precision. If |
| 1235 | specified as ``'*'`` (an asterisk), the actual width is read from the next |
| 1236 | element of the tuple in *values*, and the value to convert comes after the |
| 1237 | precision. |
| 1238 | |
| 1239 | #. Length modifier (optional). |
| 1240 | |
| 1241 | #. Conversion type. |
| 1242 | |
| 1243 | When the right argument is a dictionary (or other mapping type), then the |
| 1244 | formats in the string *must* include a parenthesised mapping key into that |
| 1245 | dictionary inserted immediately after the ``'%'`` character. The mapping key |
Christian Heimes | fe337bf | 2008-03-23 21:54:12 +0000 | [diff] [blame] | 1246 | selects the value to be formatted from the mapping. For example: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1247 | |
Christian Heimes | fe337bf | 2008-03-23 21:54:12 +0000 | [diff] [blame] | 1248 | |
| 1249 | >>> print('%(language)s has %(#)03d quote types.' % \ |
| 1250 | ... {'language': "Python", "#": 2}) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1251 | Python has 002 quote types. |
| 1252 | |
| 1253 | In this case no ``*`` specifiers may occur in a format (since they require a |
| 1254 | sequential parameter list). |
| 1255 | |
| 1256 | The conversion flag characters are: |
| 1257 | |
| 1258 | +---------+---------------------------------------------------------------------+ |
| 1259 | | Flag | Meaning | |
| 1260 | +=========+=====================================================================+ |
| 1261 | | ``'#'`` | The value conversion will use the "alternate form" (where defined | |
| 1262 | | | below). | |
| 1263 | +---------+---------------------------------------------------------------------+ |
| 1264 | | ``'0'`` | The conversion will be zero padded for numeric values. | |
| 1265 | +---------+---------------------------------------------------------------------+ |
| 1266 | | ``'-'`` | The converted value is left adjusted (overrides the ``'0'`` | |
| 1267 | | | conversion if both are given). | |
| 1268 | +---------+---------------------------------------------------------------------+ |
| 1269 | | ``' '`` | (a space) A blank should be left before a positive number (or empty | |
| 1270 | | | string) produced by a signed conversion. | |
| 1271 | +---------+---------------------------------------------------------------------+ |
| 1272 | | ``'+'`` | A sign character (``'+'`` or ``'-'``) will precede the conversion | |
| 1273 | | | (overrides a "space" flag). | |
| 1274 | +---------+---------------------------------------------------------------------+ |
| 1275 | |
| 1276 | A length modifier (``h``, ``l``, or ``L``) may be present, but is ignored as it |
Alexandre Vassalotti | 5f8ced2 | 2008-05-16 00:03:33 +0000 | [diff] [blame] | 1277 | is not necessary for Python -- so e.g. ``%ld`` is identical to ``%d``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1278 | |
| 1279 | The conversion types are: |
| 1280 | |
| 1281 | +------------+-----------------------------------------------------+-------+ |
| 1282 | | Conversion | Meaning | Notes | |
| 1283 | +============+=====================================================+=======+ |
| 1284 | | ``'d'`` | Signed integer decimal. | | |
| 1285 | +------------+-----------------------------------------------------+-------+ |
| 1286 | | ``'i'`` | Signed integer decimal. | | |
| 1287 | +------------+-----------------------------------------------------+-------+ |
Alexandre Vassalotti | 5f8ced2 | 2008-05-16 00:03:33 +0000 | [diff] [blame] | 1288 | | ``'o'`` | Signed octal value. | \(1) | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1289 | +------------+-----------------------------------------------------+-------+ |
Benjamin Peterson | e0124bd | 2009-03-09 21:04:33 +0000 | [diff] [blame] | 1290 | | ``'u'`` | Obsolete type -- it is identical to ``'d'``. | \(7) | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1291 | +------------+-----------------------------------------------------+-------+ |
Alexandre Vassalotti | 5f8ced2 | 2008-05-16 00:03:33 +0000 | [diff] [blame] | 1292 | | ``'x'`` | Signed hexadecimal (lowercase). | \(2) | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1293 | +------------+-----------------------------------------------------+-------+ |
Alexandre Vassalotti | 5f8ced2 | 2008-05-16 00:03:33 +0000 | [diff] [blame] | 1294 | | ``'X'`` | Signed hexadecimal (uppercase). | \(2) | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1295 | +------------+-----------------------------------------------------+-------+ |
| 1296 | | ``'e'`` | Floating point exponential format (lowercase). | \(3) | |
| 1297 | +------------+-----------------------------------------------------+-------+ |
| 1298 | | ``'E'`` | Floating point exponential format (uppercase). | \(3) | |
| 1299 | +------------+-----------------------------------------------------+-------+ |
Eric Smith | 22b85b3 | 2008-07-17 19:18:29 +0000 | [diff] [blame] | 1300 | | ``'f'`` | Floating point decimal format. | \(3) | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1301 | +------------+-----------------------------------------------------+-------+ |
Eric Smith | 22b85b3 | 2008-07-17 19:18:29 +0000 | [diff] [blame] | 1302 | | ``'F'`` | Floating point decimal format. | \(3) | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1303 | +------------+-----------------------------------------------------+-------+ |
Christian Heimes | 8dc226f | 2008-05-06 23:45:46 +0000 | [diff] [blame] | 1304 | | ``'g'`` | Floating point format. Uses lowercase exponential | \(4) | |
| 1305 | | | format if exponent is less than -4 or not less than | | |
| 1306 | | | precision, decimal format otherwise. | | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1307 | +------------+-----------------------------------------------------+-------+ |
Christian Heimes | 8dc226f | 2008-05-06 23:45:46 +0000 | [diff] [blame] | 1308 | | ``'G'`` | Floating point format. Uses uppercase exponential | \(4) | |
| 1309 | | | format if exponent is less than -4 or not less than | | |
| 1310 | | | precision, decimal format otherwise. | | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1311 | +------------+-----------------------------------------------------+-------+ |
| 1312 | | ``'c'`` | Single character (accepts integer or single | | |
| 1313 | | | character string). | | |
| 1314 | +------------+-----------------------------------------------------+-------+ |
Ezio Melotti | 890c193 | 2009-12-19 23:33:46 +0000 | [diff] [blame] | 1315 | | ``'r'`` | String (converts any Python object using | \(5) | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1316 | | | :func:`repr`). | | |
| 1317 | +------------+-----------------------------------------------------+-------+ |
Ezio Melotti | 890c193 | 2009-12-19 23:33:46 +0000 | [diff] [blame] | 1318 | | ``'s'`` | String (converts any Python object using | | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1319 | | | :func:`str`). | | |
| 1320 | +------------+-----------------------------------------------------+-------+ |
| 1321 | | ``'%'`` | No argument is converted, results in a ``'%'`` | | |
| 1322 | | | character in the result. | | |
| 1323 | +------------+-----------------------------------------------------+-------+ |
| 1324 | |
| 1325 | Notes: |
| 1326 | |
| 1327 | (1) |
| 1328 | The alternate form causes a leading zero (``'0'``) to be inserted between |
| 1329 | left-hand padding and the formatting of the number if the leading character |
| 1330 | of the result is not already a zero. |
| 1331 | |
| 1332 | (2) |
| 1333 | The alternate form causes a leading ``'0x'`` or ``'0X'`` (depending on whether |
| 1334 | the ``'x'`` or ``'X'`` format was used) to be inserted between left-hand padding |
| 1335 | and the formatting of the number if the leading character of the result is not |
| 1336 | already a zero. |
| 1337 | |
| 1338 | (3) |
| 1339 | The alternate form causes the result to always contain a decimal point, even if |
| 1340 | no digits follow it. |
| 1341 | |
| 1342 | The precision determines the number of digits after the decimal point and |
| 1343 | defaults to 6. |
| 1344 | |
| 1345 | (4) |
| 1346 | The alternate form causes the result to always contain a decimal point, and |
| 1347 | trailing zeroes are not removed as they would otherwise be. |
| 1348 | |
| 1349 | The precision determines the number of significant digits before and after the |
| 1350 | decimal point and defaults to 6. |
| 1351 | |
| 1352 | (5) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1353 | The precision determines the maximal number of characters used. |
| 1354 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1355 | |
Alexandre Vassalotti | 5f8ced2 | 2008-05-16 00:03:33 +0000 | [diff] [blame] | 1356 | (7) |
| 1357 | See :pep:`237`. |
| 1358 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1359 | Since Python strings have an explicit length, ``%s`` conversions do not assume |
| 1360 | that ``'\0'`` is the end of the string. |
| 1361 | |
Christian Heimes | 5b5e81c | 2007-12-31 16:14:33 +0000 | [diff] [blame] | 1362 | .. XXX Examples? |
| 1363 | |
Mark Dickinson | 33841c3 | 2009-05-01 15:37:04 +0000 | [diff] [blame] | 1364 | .. versionchanged:: 3.1 |
| 1365 | ``%f`` conversions for numbers whose absolute value is over 1e50 are no |
| 1366 | longer replaced by ``%g`` conversions. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1367 | |
| 1368 | .. index:: |
| 1369 | module: string |
| 1370 | module: re |
| 1371 | |
| 1372 | Additional string operations are defined in standard modules :mod:`string` and |
| 1373 | :mod:`re`. |
| 1374 | |
| 1375 | |
| 1376 | .. _typesseq-range: |
| 1377 | |
Georg Brandl | 905ec32 | 2007-09-28 13:39:25 +0000 | [diff] [blame] | 1378 | Range Type |
| 1379 | ---------- |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1380 | |
| 1381 | .. index:: object: range |
| 1382 | |
| 1383 | The :class:`range` type is an immutable sequence which is commonly used for |
| 1384 | looping. The advantage of the :class:`range` type is that an :class:`range` |
| 1385 | object will always take the same amount of memory, no matter the size of the |
| 1386 | range it represents. There are no consistent performance advantages. |
| 1387 | |
Georg Brandl | 905ec32 | 2007-09-28 13:39:25 +0000 | [diff] [blame] | 1388 | Range objects have very little behavior: they only support indexing, iteration, |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1389 | and the :func:`len` function. |
| 1390 | |
| 1391 | |
| 1392 | .. _typesseq-mutable: |
| 1393 | |
| 1394 | Mutable Sequence Types |
| 1395 | ---------------------- |
| 1396 | |
| 1397 | .. index:: |
| 1398 | triple: mutable; sequence; types |
| 1399 | object: list |
Georg Brandl | 9541463 | 2007-11-22 11:00:28 +0000 | [diff] [blame] | 1400 | object: bytearray |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1401 | |
Georg Brandl | 9541463 | 2007-11-22 11:00:28 +0000 | [diff] [blame] | 1402 | List and bytearray objects support additional operations that allow in-place |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 1403 | modification of the object. Other mutable sequence types (when added to the |
| 1404 | language) should also support these operations. Strings and tuples are |
| 1405 | immutable sequence types: such objects cannot be modified once created. The |
| 1406 | following operations are defined on mutable sequence types (where *x* is an |
| 1407 | arbitrary object). |
| 1408 | |
Georg Brandl | 9541463 | 2007-11-22 11:00:28 +0000 | [diff] [blame] | 1409 | Note that while lists allow their items to be of any type, bytearray object |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 1410 | "items" are all integers in the range 0 <= x < 256. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1411 | |
Senthil Kumaran | d8d1cea | 2010-10-02 03:25:12 +0000 | [diff] [blame] | 1412 | .. index:: |
| 1413 | triple: operations on; sequence; types |
| 1414 | triple: operations on; list; type |
| 1415 | pair: subscript; assignment |
| 1416 | pair: slice; assignment |
| 1417 | statement: del |
| 1418 | single: append() (sequence method) |
| 1419 | single: extend() (sequence method) |
| 1420 | single: count() (sequence method) |
| 1421 | single: index() (sequence method) |
| 1422 | single: insert() (sequence method) |
| 1423 | single: pop() (sequence method) |
| 1424 | single: remove() (sequence method) |
| 1425 | single: reverse() (sequence method) |
| 1426 | single: sort() (sequence method) |
| 1427 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1428 | +------------------------------+--------------------------------+---------------------+ |
| 1429 | | Operation | Result | Notes | |
| 1430 | +==============================+================================+=====================+ |
| 1431 | | ``s[i] = x`` | item *i* of *s* is replaced by | | |
| 1432 | | | *x* | | |
| 1433 | +------------------------------+--------------------------------+---------------------+ |
| 1434 | | ``s[i:j] = t`` | slice of *s* from *i* to *j* | | |
| 1435 | | | is replaced by the contents of | | |
| 1436 | | | the iterable *t* | | |
| 1437 | +------------------------------+--------------------------------+---------------------+ |
| 1438 | | ``del s[i:j]`` | same as ``s[i:j] = []`` | | |
| 1439 | +------------------------------+--------------------------------+---------------------+ |
| 1440 | | ``s[i:j:k] = t`` | the elements of ``s[i:j:k]`` | \(1) | |
| 1441 | | | are replaced by those of *t* | | |
| 1442 | +------------------------------+--------------------------------+---------------------+ |
| 1443 | | ``del s[i:j:k]`` | removes the elements of | | |
| 1444 | | | ``s[i:j:k]`` from the list | | |
| 1445 | +------------------------------+--------------------------------+---------------------+ |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 1446 | | ``s.append(x)`` | same as ``s[len(s):len(s)] = | | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1447 | | | [x]`` | | |
| 1448 | +------------------------------+--------------------------------+---------------------+ |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 1449 | | ``s.extend(x)`` | same as ``s[len(s):len(s)] = | \(2) | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1450 | | | x`` | | |
| 1451 | +------------------------------+--------------------------------+---------------------+ |
| 1452 | | ``s.count(x)`` | return number of *i*'s for | | |
| 1453 | | | which ``s[i] == x`` | | |
| 1454 | +------------------------------+--------------------------------+---------------------+ |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 1455 | | ``s.index(x[, i[, j]])`` | return smallest *k* such that | \(3) | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1456 | | | ``s[k] == x`` and ``i <= k < | | |
| 1457 | | | j`` | | |
| 1458 | +------------------------------+--------------------------------+---------------------+ |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 1459 | | ``s.insert(i, x)`` | same as ``s[i:i] = [x]`` | \(4) | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1460 | +------------------------------+--------------------------------+---------------------+ |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 1461 | | ``s.pop([i])`` | same as ``x = s[i]; del s[i]; | \(5) | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1462 | | | return x`` | | |
| 1463 | +------------------------------+--------------------------------+---------------------+ |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 1464 | | ``s.remove(x)`` | same as ``del s[s.index(x)]`` | \(3) | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1465 | +------------------------------+--------------------------------+---------------------+ |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 1466 | | ``s.reverse()`` | reverses the items of *s* in | \(6) | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1467 | | | place | | |
| 1468 | +------------------------------+--------------------------------+---------------------+ |
Raymond Hettinger | 7f73295 | 2008-02-14 13:34:38 +0000 | [diff] [blame] | 1469 | | ``s.sort([key[, reverse]])`` | sort the items of *s* in place | (6), (7), (8) | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1470 | +------------------------------+--------------------------------+---------------------+ |
| 1471 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1472 | |
| 1473 | Notes: |
| 1474 | |
| 1475 | (1) |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 1476 | *t* must have the same length as the slice it is replacing. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1477 | |
| 1478 | (2) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1479 | *x* can be any iterable object. |
| 1480 | |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 1481 | (3) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1482 | Raises :exc:`ValueError` when *x* is not found in *s*. When a negative index is |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 1483 | passed as the second or third parameter to the :meth:`index` method, the sequence |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1484 | length is added, as for slice indices. If it is still negative, it is truncated |
| 1485 | to zero, as for slice indices. |
| 1486 | |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 1487 | (4) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1488 | When a negative index is passed as the first parameter to the :meth:`insert` |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 1489 | method, the sequence length is added, as for slice indices. If it is still |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1490 | negative, it is truncated to zero, as for slice indices. |
| 1491 | |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 1492 | (5) |
| 1493 | The optional argument *i* defaults to ``-1``, so that by default the last |
| 1494 | item is removed and returned. |
| 1495 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1496 | (6) |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 1497 | The :meth:`sort` and :meth:`reverse` methods modify the sequence in place for |
| 1498 | economy of space when sorting or reversing a large sequence. To remind you |
| 1499 | that they operate by side effect, they don't return the sorted or reversed |
| 1500 | sequence. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1501 | |
| 1502 | (7) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1503 | The :meth:`sort` method takes optional arguments for controlling the |
Raymond Hettinger | 7f73295 | 2008-02-14 13:34:38 +0000 | [diff] [blame] | 1504 | comparisons. Each must be specified as a keyword argument. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1505 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1506 | *key* specifies a function of one argument that is used to extract a comparison |
Christian Heimes | faf2f63 | 2008-01-06 16:59:19 +0000 | [diff] [blame] | 1507 | key from each list element: ``key=str.lower``. The default value is ``None``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1508 | |
| 1509 | *reverse* is a boolean value. If set to ``True``, then the list elements are |
| 1510 | sorted as if each comparison were reversed. |
| 1511 | |
Raymond Hettinger | 7116186 | 2008-02-14 13:32:18 +0000 | [diff] [blame] | 1512 | The :meth:`sort` method is guaranteed to be stable. A |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1513 | sort is stable if it guarantees not to change the relative order of elements |
| 1514 | that compare equal --- this is helpful for sorting in multiple passes (for |
| 1515 | example, sort by department, then by salary grade). |
| 1516 | |
Georg Brandl | 628e6f9 | 2009-10-27 20:24:45 +0000 | [diff] [blame] | 1517 | .. impl-detail:: |
| 1518 | |
| 1519 | While a list is being sorted, the effect of attempting to mutate, or even |
| 1520 | inspect, the list is undefined. The C implementation of Python makes the |
| 1521 | list appear empty for the duration, and raises :exc:`ValueError` if it can |
| 1522 | detect that the list has been mutated during a sort. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1523 | |
Raymond Hettinger | 7f73295 | 2008-02-14 13:34:38 +0000 | [diff] [blame] | 1524 | (8) |
| 1525 | :meth:`sort` is not supported by :class:`bytearray` objects. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1526 | |
Georg Brandl | 628e6f9 | 2009-10-27 20:24:45 +0000 | [diff] [blame] | 1527 | |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 1528 | .. _bytes-methods: |
| 1529 | |
Georg Brandl | 9541463 | 2007-11-22 11:00:28 +0000 | [diff] [blame] | 1530 | Bytes and Byte Array Methods |
| 1531 | ---------------------------- |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 1532 | |
| 1533 | .. index:: pair: bytes; methods |
Georg Brandl | 9541463 | 2007-11-22 11:00:28 +0000 | [diff] [blame] | 1534 | pair: bytearray; methods |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 1535 | |
Georg Brandl | 9541463 | 2007-11-22 11:00:28 +0000 | [diff] [blame] | 1536 | Bytes and bytearray objects, being "strings of bytes", have all methods found on |
Georg Brandl | 7c67613 | 2007-10-23 18:17:00 +0000 | [diff] [blame] | 1537 | strings, with the exception of :func:`encode`, :func:`format` and |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 1538 | :func:`isidentifier`, which do not make sense with these types. For converting |
| 1539 | the objects to strings, they have a :func:`decode` method. |
| 1540 | |
| 1541 | Wherever one of these methods needs to interpret the bytes as characters |
| 1542 | (e.g. the :func:`is...` methods), the ASCII character set is assumed. |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 1543 | |
Georg Brandl | 7c67613 | 2007-10-23 18:17:00 +0000 | [diff] [blame] | 1544 | .. note:: |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 1545 | |
Georg Brandl | 9541463 | 2007-11-22 11:00:28 +0000 | [diff] [blame] | 1546 | The methods on bytes and bytearray objects don't accept strings as their |
Georg Brandl | 7c67613 | 2007-10-23 18:17:00 +0000 | [diff] [blame] | 1547 | arguments, just as the methods on strings don't accept bytes as their |
| 1548 | arguments. For example, you have to write :: |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 1549 | |
Georg Brandl | 7c67613 | 2007-10-23 18:17:00 +0000 | [diff] [blame] | 1550 | a = "abc" |
| 1551 | b = a.replace("a", "f") |
| 1552 | |
| 1553 | and :: |
| 1554 | |
| 1555 | a = b"abc" |
| 1556 | b = a.replace(b"a", b"f") |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 1557 | |
| 1558 | |
Georg Brandl | 4f5f98d | 2009-05-04 21:01:20 +0000 | [diff] [blame] | 1559 | .. method:: bytes.decode([encoding[, errors]]) |
| 1560 | bytearray.decode([encoding[, errors]]) |
| 1561 | |
| 1562 | Return a string decoded from the given bytes. Default encoding is the |
| 1563 | current default string encoding. *errors* may be given to set a different |
| 1564 | error handling scheme. The default for *errors* is ``'strict'``, meaning |
| 1565 | that encoding errors raise a :exc:`UnicodeError`. Other possible values are |
| 1566 | ``'ignore'``, ``'replace'`` and any other name registered via |
| 1567 | :func:`codecs.register_error`, see section :ref:`codec-base-classes`. For a |
| 1568 | list of possible encodings, see section :ref:`standard-encodings`. |
| 1569 | |
| 1570 | |
Georg Brandl | 9541463 | 2007-11-22 11:00:28 +0000 | [diff] [blame] | 1571 | The bytes and bytearray types have an additional class method: |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 1572 | |
Georg Brandl | abc3877 | 2009-04-12 15:51:51 +0000 | [diff] [blame] | 1573 | .. classmethod:: bytes.fromhex(string) |
| 1574 | bytearray.fromhex(string) |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 1575 | |
Georg Brandl | 18da8f0 | 2008-07-01 20:08:02 +0000 | [diff] [blame] | 1576 | This :class:`bytes` class method returns a bytes or bytearray object, |
| 1577 | decoding the given string object. The string must contain two hexadecimal |
| 1578 | digits per byte, spaces are ignored. |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 1579 | |
Georg Brandl | 18da8f0 | 2008-07-01 20:08:02 +0000 | [diff] [blame] | 1580 | >>> bytes.fromhex('f0 f1f2 ') |
| 1581 | b'\xf0\xf1\xf2' |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 1582 | |
Georg Brandl | abc3877 | 2009-04-12 15:51:51 +0000 | [diff] [blame] | 1583 | |
| 1584 | The maketrans and translate methods differ in semantics from the versions |
| 1585 | available on strings: |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 1586 | |
Georg Brandl | 454636f | 2008-12-27 23:33:20 +0000 | [diff] [blame] | 1587 | .. method:: bytes.translate(table[, delete]) |
Georg Brandl | 751771b | 2009-05-31 21:38:37 +0000 | [diff] [blame] | 1588 | bytearray.translate(table[, delete]) |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 1589 | |
Georg Brandl | 454636f | 2008-12-27 23:33:20 +0000 | [diff] [blame] | 1590 | Return a copy of the bytes or bytearray object where all bytes occurring in |
| 1591 | the optional argument *delete* are removed, and the remaining bytes have been |
| 1592 | mapped through the given translation table, which must be a bytes object of |
| 1593 | length 256. |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 1594 | |
Georg Brandl | abc3877 | 2009-04-12 15:51:51 +0000 | [diff] [blame] | 1595 | You can use the :func:`bytes.maketrans` method to create a translation table. |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 1596 | |
Georg Brandl | 454636f | 2008-12-27 23:33:20 +0000 | [diff] [blame] | 1597 | Set the *table* argument to ``None`` for translations that only delete |
| 1598 | characters:: |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 1599 | |
Georg Brandl | 454636f | 2008-12-27 23:33:20 +0000 | [diff] [blame] | 1600 | >>> b'read this short text'.translate(None, b'aeiou') |
| 1601 | b'rd ths shrt txt' |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 1602 | |
| 1603 | |
Georg Brandl | abc3877 | 2009-04-12 15:51:51 +0000 | [diff] [blame] | 1604 | .. staticmethod:: bytes.maketrans(from, to) |
Georg Brandl | 751771b | 2009-05-31 21:38:37 +0000 | [diff] [blame] | 1605 | bytearray.maketrans(from, to) |
Georg Brandl | abc3877 | 2009-04-12 15:51:51 +0000 | [diff] [blame] | 1606 | |
| 1607 | This static method returns a translation table usable for |
| 1608 | :meth:`bytes.translate` that will map each character in *from* into the |
| 1609 | character at the same position in *to*; *from* and *to* must be bytes objects |
| 1610 | and have the same length. |
| 1611 | |
| 1612 | .. versionadded:: 3.1 |
| 1613 | |
| 1614 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1615 | .. _types-set: |
| 1616 | |
| 1617 | Set Types --- :class:`set`, :class:`frozenset` |
| 1618 | ============================================== |
| 1619 | |
| 1620 | .. index:: object: set |
| 1621 | |
Guido van Rossum | 2cc30da | 2007-11-02 23:46:40 +0000 | [diff] [blame] | 1622 | A :dfn:`set` object is an unordered collection of distinct :term:`hashable` objects. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1623 | Common uses include membership testing, removing duplicates from a sequence, and |
| 1624 | computing mathematical operations such as intersection, union, difference, and |
| 1625 | symmetric difference. |
| 1626 | (For other containers see the built in :class:`dict`, :class:`list`, |
| 1627 | and :class:`tuple` classes, and the :mod:`collections` module.) |
| 1628 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1629 | Like other collections, sets support ``x in set``, ``len(set)``, and ``for x in |
| 1630 | set``. Being an unordered collection, sets do not record element position or |
| 1631 | order of insertion. Accordingly, sets do not support indexing, slicing, or |
| 1632 | other sequence-like behavior. |
| 1633 | |
Georg Brandl | c5605df | 2009-08-13 08:26:44 +0000 | [diff] [blame] | 1634 | There are currently two built-in set types, :class:`set` and :class:`frozenset`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1635 | The :class:`set` type is mutable --- the contents can be changed using methods |
| 1636 | like :meth:`add` and :meth:`remove`. Since it is mutable, it has no hash value |
| 1637 | and cannot be used as either a dictionary key or as an element of another set. |
Guido van Rossum | 2cc30da | 2007-11-02 23:46:40 +0000 | [diff] [blame] | 1638 | The :class:`frozenset` type is immutable and :term:`hashable` --- its contents cannot be |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1639 | altered after it is created; it can therefore be used as a dictionary key or as |
| 1640 | an element of another set. |
| 1641 | |
| 1642 | The constructors for both classes work the same: |
| 1643 | |
| 1644 | .. class:: set([iterable]) |
| 1645 | frozenset([iterable]) |
| 1646 | |
| 1647 | Return a new set or frozenset object whose elements are taken from |
| 1648 | *iterable*. The elements of a set must be hashable. To represent sets of |
| 1649 | sets, the inner sets must be :class:`frozenset` objects. If *iterable* is |
| 1650 | not specified, a new empty set is returned. |
| 1651 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1652 | Instances of :class:`set` and :class:`frozenset` provide the following |
| 1653 | operations: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1654 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1655 | .. describe:: len(s) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1656 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1657 | Return the cardinality of set *s*. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1658 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1659 | .. describe:: x in s |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1660 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1661 | Test *x* for membership in *s*. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1662 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1663 | .. describe:: x not in s |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1664 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1665 | Test *x* for non-membership in *s*. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1666 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1667 | .. method:: isdisjoint(other) |
Guido van Rossum | 58da931 | 2007-11-10 23:39:45 +0000 | [diff] [blame] | 1668 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1669 | Return True if the set has no elements in common with *other*. Sets are |
Georg Brandl | 2ee470f | 2008-07-16 12:55:28 +0000 | [diff] [blame] | 1670 | disjoint if and only if their intersection is the empty set. |
Guido van Rossum | 58da931 | 2007-11-10 23:39:45 +0000 | [diff] [blame] | 1671 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1672 | .. method:: issubset(other) |
| 1673 | set <= other |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1674 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1675 | Test whether every element in the set is in *other*. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1676 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1677 | .. method:: set < other |
Georg Brandl | a6f5278 | 2007-09-01 15:49:30 +0000 | [diff] [blame] | 1678 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1679 | Test whether the set is a true subset of *other*, that is, |
| 1680 | ``set <= other and set != other``. |
Georg Brandl | a6f5278 | 2007-09-01 15:49:30 +0000 | [diff] [blame] | 1681 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1682 | .. method:: issuperset(other) |
| 1683 | set >= other |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1684 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1685 | Test whether every element in *other* is in the set. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1686 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1687 | .. method:: set > other |
Georg Brandl | a6f5278 | 2007-09-01 15:49:30 +0000 | [diff] [blame] | 1688 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1689 | Test whether the set is a true superset of *other*, that is, ``set >= |
| 1690 | other and set != other``. |
Georg Brandl | a6f5278 | 2007-09-01 15:49:30 +0000 | [diff] [blame] | 1691 | |
Georg Brandl | c28e1fa | 2008-06-10 19:20:26 +0000 | [diff] [blame] | 1692 | .. method:: union(other, ...) |
| 1693 | set | other | ... |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1694 | |
Benjamin Peterson | b58dda7 | 2009-01-18 22:27:04 +0000 | [diff] [blame] | 1695 | Return a new set with elements from the set and all others. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1696 | |
Georg Brandl | c28e1fa | 2008-06-10 19:20:26 +0000 | [diff] [blame] | 1697 | .. method:: intersection(other, ...) |
| 1698 | set & other & ... |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1699 | |
Benjamin Peterson | b58dda7 | 2009-01-18 22:27:04 +0000 | [diff] [blame] | 1700 | Return a new set with elements common to the set and all others. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1701 | |
Amaury Forgeot d'Arc | fdfe62d | 2008-06-17 20:36:03 +0000 | [diff] [blame] | 1702 | .. method:: difference(other, ...) |
| 1703 | set - other - ... |
Georg Brandl | c28e1fa | 2008-06-10 19:20:26 +0000 | [diff] [blame] | 1704 | |
Amaury Forgeot d'Arc | fdfe62d | 2008-06-17 20:36:03 +0000 | [diff] [blame] | 1705 | Return a new set with elements in the set that are not in the others. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1706 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1707 | .. method:: symmetric_difference(other) |
| 1708 | set ^ other |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1709 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1710 | Return a new set with elements in either the set or *other* but not both. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1711 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1712 | .. method:: copy() |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1713 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1714 | Return a new set with a shallow copy of *s*. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1715 | |
| 1716 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1717 | Note, the non-operator versions of :meth:`union`, :meth:`intersection`, |
| 1718 | :meth:`difference`, and :meth:`symmetric_difference`, :meth:`issubset`, and |
| 1719 | :meth:`issuperset` methods will accept any iterable as an argument. In |
| 1720 | contrast, their operator based counterparts require their arguments to be |
| 1721 | sets. This precludes error-prone constructions like ``set('abc') & 'cbs'`` |
| 1722 | in favor of the more readable ``set('abc').intersection('cbs')``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1723 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1724 | Both :class:`set` and :class:`frozenset` support set to set comparisons. Two |
| 1725 | sets are equal if and only if every element of each set is contained in the |
| 1726 | other (each is a subset of the other). A set is less than another set if and |
| 1727 | only if the first set is a proper subset of the second set (is a subset, but |
| 1728 | is not equal). A set is greater than another set if and only if the first set |
| 1729 | is a proper superset of the second set (is a superset, but is not equal). |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1730 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1731 | Instances of :class:`set` are compared to instances of :class:`frozenset` |
| 1732 | based on their members. For example, ``set('abc') == frozenset('abc')`` |
| 1733 | returns ``True`` and so does ``set('abc') in set([frozenset('abc')])``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1734 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1735 | The subset and equality comparisons do not generalize to a complete ordering |
| 1736 | function. For example, any two disjoint sets are not equal and are not |
| 1737 | subsets of each other, so *all* of the following return ``False``: ``a<b``, |
Georg Brandl | 05f5ab7 | 2008-09-24 09:11:47 +0000 | [diff] [blame] | 1738 | ``a==b``, or ``a>b``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1739 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1740 | Since sets only define partial ordering (subset relationships), the output of |
| 1741 | the :meth:`list.sort` method is undefined for lists of sets. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1742 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1743 | Set elements, like dictionary keys, must be :term:`hashable`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1744 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1745 | Binary operations that mix :class:`set` instances with :class:`frozenset` |
| 1746 | return the type of the first operand. For example: ``frozenset('ab') | |
| 1747 | set('bc')`` returns an instance of :class:`frozenset`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1748 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1749 | The following table lists operations available for :class:`set` that do not |
| 1750 | apply to immutable instances of :class:`frozenset`: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1751 | |
Georg Brandl | c28e1fa | 2008-06-10 19:20:26 +0000 | [diff] [blame] | 1752 | .. method:: update(other, ...) |
| 1753 | set |= other | ... |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1754 | |
Georg Brandl | 7baf625 | 2009-09-01 08:13:16 +0000 | [diff] [blame] | 1755 | Update the set, adding elements from all others. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1756 | |
Georg Brandl | c28e1fa | 2008-06-10 19:20:26 +0000 | [diff] [blame] | 1757 | .. method:: intersection_update(other, ...) |
| 1758 | set &= other & ... |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1759 | |
Georg Brandl | 7baf625 | 2009-09-01 08:13:16 +0000 | [diff] [blame] | 1760 | Update the set, keeping only elements found in it and all others. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1761 | |
Amaury Forgeot d'Arc | fdfe62d | 2008-06-17 20:36:03 +0000 | [diff] [blame] | 1762 | .. method:: difference_update(other, ...) |
| 1763 | set -= other | ... |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1764 | |
Amaury Forgeot d'Arc | fdfe62d | 2008-06-17 20:36:03 +0000 | [diff] [blame] | 1765 | Update the set, removing elements found in others. |
| 1766 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1767 | .. method:: symmetric_difference_update(other) |
| 1768 | set ^= other |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1769 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1770 | Update the set, keeping only elements found in either set, but not in both. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1771 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1772 | .. method:: add(elem) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1773 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1774 | Add element *elem* to the set. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1775 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1776 | .. method:: remove(elem) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1777 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1778 | Remove element *elem* from the set. Raises :exc:`KeyError` if *elem* is |
| 1779 | not contained in the set. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1780 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1781 | .. method:: discard(elem) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1782 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1783 | Remove element *elem* from the set if it is present. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1784 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1785 | .. method:: pop() |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1786 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1787 | Remove and return an arbitrary element from the set. Raises |
| 1788 | :exc:`KeyError` if the set is empty. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1789 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1790 | .. method:: clear() |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1791 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1792 | Remove all elements from the set. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1793 | |
| 1794 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1795 | Note, the non-operator versions of the :meth:`update`, |
| 1796 | :meth:`intersection_update`, :meth:`difference_update`, and |
| 1797 | :meth:`symmetric_difference_update` methods will accept any iterable as an |
| 1798 | argument. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1799 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1800 | Note, the *elem* argument to the :meth:`__contains__`, :meth:`remove`, and |
| 1801 | :meth:`discard` methods may be a set. To support searching for an equivalent |
| 1802 | frozenset, the *elem* set is temporarily mutated during the search and then |
| 1803 | restored. During the search, the *elem* set should not be read or mutated |
| 1804 | since it does not have a meaningful value. |
Benjamin Peterson | 699adb9 | 2008-05-08 22:27:58 +0000 | [diff] [blame] | 1805 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1806 | |
| 1807 | .. _typesmapping: |
| 1808 | |
| 1809 | Mapping Types --- :class:`dict` |
| 1810 | =============================== |
| 1811 | |
| 1812 | .. index:: |
| 1813 | object: mapping |
| 1814 | object: dictionary |
| 1815 | triple: operations on; mapping; types |
| 1816 | triple: operations on; dictionary; type |
| 1817 | statement: del |
| 1818 | builtin: len |
| 1819 | |
Guido van Rossum | 2cc30da | 2007-11-02 23:46:40 +0000 | [diff] [blame] | 1820 | A :dfn:`mapping` object maps :term:`hashable` values to arbitrary objects. |
| 1821 | Mappings are mutable objects. There is currently only one standard mapping |
| 1822 | type, the :dfn:`dictionary`. (For other containers see the built in |
| 1823 | :class:`list`, :class:`set`, and :class:`tuple` classes, and the |
| 1824 | :mod:`collections` module.) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1825 | |
Guido van Rossum | 2cc30da | 2007-11-02 23:46:40 +0000 | [diff] [blame] | 1826 | A dictionary's keys are *almost* arbitrary values. Values that are not |
| 1827 | :term:`hashable`, that is, values containing lists, dictionaries or other |
| 1828 | mutable types (that are compared by value rather than by object identity) may |
| 1829 | not be used as keys. Numeric types used for keys obey the normal rules for |
| 1830 | numeric comparison: if two numbers compare equal (such as ``1`` and ``1.0``) |
| 1831 | then they can be used interchangeably to index the same dictionary entry. (Note |
| 1832 | however, that since computers store floating-point numbers as approximations it |
| 1833 | is usually unwise to use them as dictionary keys.) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1834 | |
| 1835 | Dictionaries can be created by placing a comma-separated list of ``key: value`` |
| 1836 | pairs within braces, for example: ``{'jack': 4098, 'sjoerd': 4127}`` or ``{4098: |
| 1837 | 'jack', 4127: 'sjoerd'}``, or by the :class:`dict` constructor. |
| 1838 | |
| 1839 | .. class:: dict([arg]) |
| 1840 | |
Georg Brandl | d22a815 | 2007-09-04 17:43:37 +0000 | [diff] [blame] | 1841 | Return a new dictionary initialized from an optional positional argument or |
| 1842 | from a set of keyword arguments. If no arguments are given, return a new |
| 1843 | empty dictionary. If the positional argument *arg* is a mapping object, |
| 1844 | return a dictionary mapping the same keys to the same values as does the |
| 1845 | mapping object. Otherwise the positional argument must be a sequence, a |
| 1846 | container that supports iteration, or an iterator object. The elements of |
| 1847 | the argument must each also be of one of those kinds, and each must in turn |
| 1848 | contain exactly two objects. The first is used as a key in the new |
| 1849 | dictionary, and the second as the key's value. If a given key is seen more |
| 1850 | than once, the last value associated with it is retained in the new |
| 1851 | dictionary. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1852 | |
| 1853 | If keyword arguments are given, the keywords themselves with their associated |
Georg Brandl | d22a815 | 2007-09-04 17:43:37 +0000 | [diff] [blame] | 1854 | values are added as items to the dictionary. If a key is specified both in |
| 1855 | the positional argument and as a keyword argument, the value associated with |
| 1856 | the keyword is retained in the dictionary. For example, these all return a |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1857 | dictionary equal to ``{"one": 2, "two": 3}``: |
| 1858 | |
| 1859 | * ``dict(one=2, two=3)`` |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1860 | * ``dict({'one': 2, 'two': 3})`` |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1861 | * ``dict(zip(('one', 'two'), (2, 3)))`` |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1862 | * ``dict([['two', 3], ['one', 2]])`` |
| 1863 | |
Georg Brandl | d22a815 | 2007-09-04 17:43:37 +0000 | [diff] [blame] | 1864 | The first example only works for keys that are valid Python identifiers; the |
| 1865 | others work with any valid keys. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1866 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1867 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1868 | These are the operations that dictionaries support (and therefore, custom |
| 1869 | mapping types should support too): |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1870 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1871 | .. describe:: len(d) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1872 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1873 | Return the number of items in the dictionary *d*. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1874 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1875 | .. describe:: d[key] |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1876 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1877 | Return the item of *d* with key *key*. Raises a :exc:`KeyError` if *key* is |
| 1878 | not in the map. |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 1879 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1880 | If a subclass of dict defines a method :meth:`__missing__`, if the key *key* |
| 1881 | is not present, the ``d[key]`` operation calls that method with the key *key* |
| 1882 | as argument. The ``d[key]`` operation then returns or raises whatever is |
| 1883 | returned or raised by the ``__missing__(key)`` call if the key is not |
| 1884 | present. No other operations or methods invoke :meth:`__missing__`. If |
| 1885 | :meth:`__missing__` is not defined, :exc:`KeyError` is raised. |
| 1886 | :meth:`__missing__` must be a method; it cannot be an instance variable. For |
| 1887 | an example, see :class:`collections.defaultdict`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1888 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1889 | .. describe:: d[key] = value |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1890 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1891 | Set ``d[key]`` to *value*. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1892 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1893 | .. describe:: del d[key] |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1894 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1895 | Remove ``d[key]`` from *d*. Raises a :exc:`KeyError` if *key* is not in the |
| 1896 | map. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1897 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1898 | .. describe:: key in d |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1899 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1900 | Return ``True`` if *d* has a key *key*, else ``False``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1901 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1902 | .. describe:: key not in d |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1903 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1904 | Equivalent to ``not key in d``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1905 | |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 1906 | .. describe:: iter(d) |
| 1907 | |
| 1908 | Return an iterator over the keys of the dictionary. This is a shortcut |
Georg Brandl | 31a0f86 | 2010-07-04 17:33:33 +0000 | [diff] [blame] | 1909 | for ``iter(d.keys())``. |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 1910 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1911 | .. method:: clear() |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1912 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1913 | Remove all items from the dictionary. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1914 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1915 | .. method:: copy() |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1916 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1917 | Return a shallow copy of the dictionary. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1918 | |
Georg Brandl | abc3877 | 2009-04-12 15:51:51 +0000 | [diff] [blame] | 1919 | .. classmethod:: fromkeys(seq[, value]) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1920 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1921 | Create a new dictionary with keys from *seq* and values set to *value*. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1922 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1923 | :meth:`fromkeys` is a class method that returns a new dictionary. *value* |
| 1924 | defaults to ``None``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1925 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1926 | .. method:: get(key[, default]) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1927 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1928 | Return the value for *key* if *key* is in the dictionary, else *default*. |
| 1929 | If *default* is not given, it defaults to ``None``, so that this method |
| 1930 | never raises a :exc:`KeyError`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1931 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1932 | .. method:: items() |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1933 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1934 | Return a new view of the dictionary's items (``(key, value)`` pairs). See |
| 1935 | below for documentation of view objects. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1936 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1937 | .. method:: keys() |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1938 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1939 | Return a new view of the dictionary's keys. See below for documentation of |
| 1940 | view objects. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1941 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1942 | .. method:: pop(key[, default]) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1943 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1944 | If *key* is in the dictionary, remove it and return its value, else return |
| 1945 | *default*. If *default* is not given and *key* is not in the dictionary, |
| 1946 | a :exc:`KeyError` is raised. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1947 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1948 | .. method:: popitem() |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1949 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1950 | Remove and return an arbitrary ``(key, value)`` pair from the dictionary. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1951 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1952 | :meth:`popitem` is useful to destructively iterate over a dictionary, as |
| 1953 | often used in set algorithms. If the dictionary is empty, calling |
| 1954 | :meth:`popitem` raises a :exc:`KeyError`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1955 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1956 | .. method:: setdefault(key[, default]) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1957 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1958 | If *key* is in the dictionary, return its value. If not, insert *key* |
| 1959 | with a value of *default* and return *default*. *default* defaults to |
| 1960 | ``None``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1961 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1962 | .. method:: update([other]) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1963 | |
Éric Araujo | 790c9af | 2010-08-18 22:42:07 +0000 | [diff] [blame] | 1964 | Update the dictionary with the key/value pairs from *other*, overwriting |
| 1965 | existing keys. Return ``None``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1966 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1967 | :meth:`update` accepts either another dictionary object or an iterable of |
| 1968 | key/value pairs (as a tuple or other iterable of length two). If keyword |
Benjamin Peterson | a833206 | 2009-09-11 22:36:27 +0000 | [diff] [blame] | 1969 | arguments are specified, the dictionary is then updated with those |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1970 | key/value pairs: ``d.update(red=1, blue=2)``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1971 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1972 | .. method:: values() |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1973 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1974 | Return a new view of the dictionary's values. See below for documentation of |
| 1975 | view objects. |
Georg Brandl | d22a815 | 2007-09-04 17:43:37 +0000 | [diff] [blame] | 1976 | |
| 1977 | |
Benjamin Peterson | 44309e6 | 2008-11-22 00:41:45 +0000 | [diff] [blame] | 1978 | .. _dict-views: |
| 1979 | |
Georg Brandl | d22a815 | 2007-09-04 17:43:37 +0000 | [diff] [blame] | 1980 | Dictionary view objects |
| 1981 | ----------------------- |
| 1982 | |
| 1983 | The objects returned by :meth:`dict.keys`, :meth:`dict.values` and |
| 1984 | :meth:`dict.items` are *view objects*. They provide a dynamic view on the |
| 1985 | dictionary's entries, which means that when the dictionary changes, the view |
Benjamin Peterson | ce0506c | 2008-11-17 21:47:41 +0000 | [diff] [blame] | 1986 | reflects these changes. |
Georg Brandl | d22a815 | 2007-09-04 17:43:37 +0000 | [diff] [blame] | 1987 | |
| 1988 | Dictionary views can be iterated over to yield their respective data, and |
| 1989 | support membership tests: |
| 1990 | |
| 1991 | .. describe:: len(dictview) |
| 1992 | |
| 1993 | Return the number of entries in the dictionary. |
| 1994 | |
| 1995 | .. describe:: iter(dictview) |
| 1996 | |
| 1997 | Return an iterator over the keys, values or items (represented as tuples of |
| 1998 | ``(key, value)``) in the dictionary. |
| 1999 | |
| 2000 | Keys and values are iterated over in an arbitrary order which is non-random, |
| 2001 | varies across Python implementations, and depends on the dictionary's history |
| 2002 | of insertions and deletions. If keys, values and items views are iterated |
| 2003 | over with no intervening modifications to the dictionary, the order of items |
| 2004 | will directly correspond. This allows the creation of ``(value, key)`` pairs |
| 2005 | using :func:`zip`: ``pairs = zip(d.values(), d.keys())``. Another way to |
| 2006 | create the same list is ``pairs = [(v, k) for (k, v) in d.items()]``. |
| 2007 | |
Georg Brandl | 8126914 | 2009-05-17 08:31:29 +0000 | [diff] [blame] | 2008 | Iterating views while adding or deleting entries in the dictionary may raise |
| 2009 | a :exc:`RuntimeError` or fail to iterate over all entries. |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 2010 | |
Georg Brandl | d22a815 | 2007-09-04 17:43:37 +0000 | [diff] [blame] | 2011 | .. describe:: x in dictview |
| 2012 | |
| 2013 | Return ``True`` if *x* is in the underlying dictionary's keys, values or |
| 2014 | items (in the latter case, *x* should be a ``(key, value)`` tuple). |
| 2015 | |
| 2016 | |
Benjamin Peterson | ce0506c | 2008-11-17 21:47:41 +0000 | [diff] [blame] | 2017 | Keys views are set-like since their entries are unique and hashable. If all |
| 2018 | values are hashable, so that (key, value) pairs are unique and hashable, then |
| 2019 | the items view is also set-like. (Values views are not treated as set-like |
| 2020 | since the entries are generally not unique.) Then these set operations are |
| 2021 | available ("other" refers either to another view or a set): |
Georg Brandl | d22a815 | 2007-09-04 17:43:37 +0000 | [diff] [blame] | 2022 | |
| 2023 | .. describe:: dictview & other |
| 2024 | |
| 2025 | Return the intersection of the dictview and the other object as a new set. |
| 2026 | |
| 2027 | .. describe:: dictview | other |
| 2028 | |
| 2029 | Return the union of the dictview and the other object as a new set. |
| 2030 | |
| 2031 | .. describe:: dictview - other |
| 2032 | |
| 2033 | Return the difference between the dictview and the other object (all elements |
| 2034 | in *dictview* that aren't in *other*) as a new set. |
| 2035 | |
| 2036 | .. describe:: dictview ^ other |
| 2037 | |
| 2038 | Return the symmetric difference (all elements either in *dictview* or |
| 2039 | *other*, but not in both) of the dictview and the other object as a new set. |
| 2040 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2041 | |
Georg Brandl | c53c966 | 2007-09-04 17:58:02 +0000 | [diff] [blame] | 2042 | An example of dictionary view usage:: |
| 2043 | |
| 2044 | >>> dishes = {'eggs': 2, 'sausage': 1, 'bacon': 1, 'spam': 500} |
| 2045 | >>> keys = dishes.keys() |
| 2046 | >>> values = dishes.values() |
| 2047 | |
| 2048 | >>> # iteration |
| 2049 | >>> n = 0 |
| 2050 | >>> for val in values: |
| 2051 | ... n += val |
| 2052 | >>> print(n) |
| 2053 | 504 |
| 2054 | |
| 2055 | >>> # keys and values are iterated over in the same order |
| 2056 | >>> list(keys) |
| 2057 | ['eggs', 'bacon', 'sausage', 'spam'] |
| 2058 | >>> list(values) |
| 2059 | [2, 1, 1, 500] |
| 2060 | |
| 2061 | >>> # view objects are dynamic and reflect dict changes |
| 2062 | >>> del dishes['eggs'] |
| 2063 | >>> del dishes['sausage'] |
| 2064 | >>> list(keys) |
| 2065 | ['spam', 'bacon'] |
| 2066 | |
| 2067 | >>> # set operations |
| 2068 | >>> keys & {'eggs', 'bacon', 'salad'} |
Gregory P. Smith | e838812 | 2008-09-04 04:18:09 +0000 | [diff] [blame] | 2069 | {'bacon'} |
Georg Brandl | c53c966 | 2007-09-04 17:58:02 +0000 | [diff] [blame] | 2070 | |
| 2071 | |
Benjamin Peterson | 1b25b92 | 2008-09-09 22:15:27 +0000 | [diff] [blame] | 2072 | .. _typememoryview: |
| 2073 | |
| 2074 | memoryview Types |
| 2075 | ================ |
| 2076 | |
| 2077 | :class:`memoryview`\s allow Python code to access the internal data of an object |
Georg Brandl | 1009d39 | 2008-09-10 07:14:18 +0000 | [diff] [blame] | 2078 | that supports the buffer protocol without copying. Memory can be interpreted as |
| 2079 | simple bytes or complex data structures. |
Benjamin Peterson | 1b25b92 | 2008-09-09 22:15:27 +0000 | [diff] [blame] | 2080 | |
| 2081 | .. class:: memoryview(obj) |
| 2082 | |
Georg Brandl | 1009d39 | 2008-09-10 07:14:18 +0000 | [diff] [blame] | 2083 | Create a :class:`memoryview` that references *obj*. *obj* must support the |
Benjamin Peterson | 1b25b92 | 2008-09-09 22:15:27 +0000 | [diff] [blame] | 2084 | buffer protocol. Builtin objects that support the buffer protocol include |
| 2085 | :class:`bytes` and :class:`bytearray`. |
| 2086 | |
Antoine Pitrou | dac55ea | 2010-07-12 20:04:01 +0000 | [diff] [blame] | 2087 | A :class:`memoryview` has the notion of an *element*, which is the |
| 2088 | atomic memory unit handled by the originating object *obj*. For many |
| 2089 | simple types such as :class:`bytes` and :class:`bytearray`, an element |
| 2090 | is a single byte, but other types such as :class:`array.array` may have |
| 2091 | bigger elements. |
| 2092 | |
| 2093 | ``len(view)`` returns the total number of elements in the memoryview, |
| 2094 | *view*. The :class:`~memoryview.itemsize` attribute will give you the |
| 2095 | number of bytes in a single element. |
Benjamin Peterson | 5e19e44 | 2008-09-10 21:47:03 +0000 | [diff] [blame] | 2096 | |
Georg Brandl | 1009d39 | 2008-09-10 07:14:18 +0000 | [diff] [blame] | 2097 | A :class:`memoryview` supports slicing to expose its data. Taking a single |
Antoine Pitrou | dac55ea | 2010-07-12 20:04:01 +0000 | [diff] [blame] | 2098 | index will return a single element as a :class:`bytes` object. Full |
| 2099 | slicing will result in a subview:: |
Benjamin Peterson | 1b25b92 | 2008-09-09 22:15:27 +0000 | [diff] [blame] | 2100 | |
| 2101 | >>> v = memoryview(b'abcefg') |
| 2102 | >>> v[1] |
| 2103 | b'b' |
| 2104 | >>> v[-1] |
| 2105 | b'g' |
| 2106 | >>> v[1:4] |
| 2107 | <memory at 0x77ab28> |
| 2108 | >>> bytes(v[1:4]) |
| 2109 | b'bce' |
Benjamin Peterson | 1b25b92 | 2008-09-09 22:15:27 +0000 | [diff] [blame] | 2110 | |
Antoine Pitrou | dac55ea | 2010-07-12 20:04:01 +0000 | [diff] [blame] | 2111 | If the object the memoryview is over supports changing its data, the |
Georg Brandl | 1009d39 | 2008-09-10 07:14:18 +0000 | [diff] [blame] | 2112 | memoryview supports slice assignment:: |
Benjamin Peterson | 1b25b92 | 2008-09-09 22:15:27 +0000 | [diff] [blame] | 2113 | |
| 2114 | >>> data = bytearray(b'abcefg') |
| 2115 | >>> v = memoryview(data) |
| 2116 | >>> v.readonly |
| 2117 | False |
Benjamin Peterson | 5250401 | 2009-06-23 03:09:33 +0000 | [diff] [blame] | 2118 | >>> v[0] = b'z' |
Benjamin Peterson | 1b25b92 | 2008-09-09 22:15:27 +0000 | [diff] [blame] | 2119 | >>> data |
| 2120 | bytearray(b'zbcefg') |
| 2121 | >>> v[1:4] = b'123' |
| 2122 | >>> data |
| 2123 | bytearray(b'a123fg') |
| 2124 | >>> v[2] = b'spam' |
| 2125 | Traceback (most recent call last): |
| 2126 | File "<stdin>", line 1, in <module> |
| 2127 | ValueError: cannot modify size of memoryview object |
| 2128 | |
Georg Brandl | c62efa8 | 2010-07-11 10:41:07 +0000 | [diff] [blame] | 2129 | Notice how the size of the memoryview object cannot be changed. |
Benjamin Peterson | 1b25b92 | 2008-09-09 22:15:27 +0000 | [diff] [blame] | 2130 | |
Benjamin Peterson | 0c80465 | 2008-09-10 21:31:58 +0000 | [diff] [blame] | 2131 | :class:`memoryview` has two methods: |
Benjamin Peterson | 1b25b92 | 2008-09-09 22:15:27 +0000 | [diff] [blame] | 2132 | |
| 2133 | .. method:: tobytes() |
| 2134 | |
Antoine Pitrou | dac55ea | 2010-07-12 20:04:01 +0000 | [diff] [blame] | 2135 | Return the data in the buffer as a bytestring. This is equivalent to |
| 2136 | calling the :class:`bytes` constructor on the memoryview. :: |
| 2137 | |
| 2138 | >>> m = memoryview(b"abc") |
| 2139 | >>> m.tobytes() |
| 2140 | b'abc' |
| 2141 | >>> bytes(m) |
| 2142 | b'abc' |
Benjamin Peterson | 0c80465 | 2008-09-10 21:31:58 +0000 | [diff] [blame] | 2143 | |
| 2144 | .. method:: tolist() |
| 2145 | |
| 2146 | Return the data in the buffer as a list of integers. :: |
| 2147 | |
| 2148 | >>> memoryview(b'abc').tolist() |
| 2149 | [97, 98, 99] |
Benjamin Peterson | 1b25b92 | 2008-09-09 22:15:27 +0000 | [diff] [blame] | 2150 | |
| 2151 | There are also several readonly attributes available: |
| 2152 | |
| 2153 | .. attribute:: format |
| 2154 | |
| 2155 | A string containing the format (in :mod:`struct` module style) for each |
| 2156 | element in the view. This defaults to ``'B'``, a simple bytestring. |
| 2157 | |
| 2158 | .. attribute:: itemsize |
| 2159 | |
Antoine Pitrou | dac55ea | 2010-07-12 20:04:01 +0000 | [diff] [blame] | 2160 | The size in bytes of each element of the memoryview:: |
| 2161 | |
| 2162 | >>> m = memoryview(array.array('H', [1,2,3])) |
| 2163 | >>> m.itemsize |
| 2164 | 2 |
| 2165 | >>> m[0] |
| 2166 | b'\x01\x00' |
| 2167 | >>> len(m[0]) == m.itemsize |
| 2168 | True |
Benjamin Peterson | 1b25b92 | 2008-09-09 22:15:27 +0000 | [diff] [blame] | 2169 | |
| 2170 | .. attribute:: shape |
| 2171 | |
Georg Brandl | 1009d39 | 2008-09-10 07:14:18 +0000 | [diff] [blame] | 2172 | A tuple of integers the length of :attr:`ndim` giving the shape of the |
| 2173 | memory as a N-dimensional array. |
Benjamin Peterson | 1b25b92 | 2008-09-09 22:15:27 +0000 | [diff] [blame] | 2174 | |
| 2175 | .. attribute:: ndim |
| 2176 | |
| 2177 | An integer indicating how many dimensions of a multi-dimensional array the |
| 2178 | memory represents. |
| 2179 | |
| 2180 | .. attribute:: strides |
| 2181 | |
Benjamin Peterson | 2409dc7 | 2008-09-10 21:38:31 +0000 | [diff] [blame] | 2182 | A tuple of integers the length of :attr:`ndim` giving the size in bytes to |
| 2183 | access each element for each dimension of the array. |
Benjamin Peterson | 1b25b92 | 2008-09-09 22:15:27 +0000 | [diff] [blame] | 2184 | |
Benjamin Peterson | 1b25b92 | 2008-09-09 22:15:27 +0000 | [diff] [blame] | 2185 | .. memoryview.suboffsets isn't documented because it only seems useful for C |
| 2186 | |
| 2187 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2188 | .. _typecontextmanager: |
| 2189 | |
| 2190 | Context Manager Types |
| 2191 | ===================== |
| 2192 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2193 | .. index:: |
| 2194 | single: context manager |
| 2195 | single: context management protocol |
| 2196 | single: protocol; context management |
| 2197 | |
| 2198 | Python's :keyword:`with` statement supports the concept of a runtime context |
| 2199 | defined by a context manager. This is implemented using two separate methods |
| 2200 | that allow user-defined classes to define a runtime context that is entered |
| 2201 | before the statement body is executed and exited when the statement ends. |
| 2202 | |
| 2203 | The :dfn:`context management protocol` consists of a pair of methods that need |
| 2204 | to be provided for a context manager object to define a runtime context: |
| 2205 | |
| 2206 | |
| 2207 | .. method:: contextmanager.__enter__() |
| 2208 | |
| 2209 | Enter the runtime context and return either this object or another object |
| 2210 | related to the runtime context. The value returned by this method is bound to |
| 2211 | the identifier in the :keyword:`as` clause of :keyword:`with` statements using |
| 2212 | this context manager. |
| 2213 | |
Antoine Pitrou | 25d535e | 2010-09-15 11:25:11 +0000 | [diff] [blame] | 2214 | An example of a context manager that returns itself is a :term:`file object`. |
| 2215 | File objects return themselves from __enter__() to allow :func:`open` to be |
| 2216 | used as the context expression in a :keyword:`with` statement. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2217 | |
| 2218 | An example of a context manager that returns a related object is the one |
Christian Heimes | faf2f63 | 2008-01-06 16:59:19 +0000 | [diff] [blame] | 2219 | returned by :func:`decimal.localcontext`. These managers set the active |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2220 | decimal context to a copy of the original decimal context and then return the |
| 2221 | copy. This allows changes to be made to the current decimal context in the body |
| 2222 | of the :keyword:`with` statement without affecting code outside the |
| 2223 | :keyword:`with` statement. |
| 2224 | |
| 2225 | |
| 2226 | .. method:: contextmanager.__exit__(exc_type, exc_val, exc_tb) |
| 2227 | |
Georg Brandl | 9afde1c | 2007-11-01 20:32:30 +0000 | [diff] [blame] | 2228 | Exit the runtime context and return a Boolean flag indicating if any exception |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2229 | that occurred should be suppressed. If an exception occurred while executing the |
| 2230 | body of the :keyword:`with` statement, the arguments contain the exception type, |
| 2231 | value and traceback information. Otherwise, all three arguments are ``None``. |
| 2232 | |
| 2233 | Returning a true value from this method will cause the :keyword:`with` statement |
| 2234 | to suppress the exception and continue execution with the statement immediately |
| 2235 | following the :keyword:`with` statement. Otherwise the exception continues |
| 2236 | propagating after this method has finished executing. Exceptions that occur |
| 2237 | during execution of this method will replace any exception that occurred in the |
| 2238 | body of the :keyword:`with` statement. |
| 2239 | |
| 2240 | The exception passed in should never be reraised explicitly - instead, this |
| 2241 | method should return a false value to indicate that the method completed |
| 2242 | successfully and does not want to suppress the raised exception. This allows |
| 2243 | context management code (such as ``contextlib.nested``) to easily detect whether |
| 2244 | or not an :meth:`__exit__` method has actually failed. |
| 2245 | |
| 2246 | Python defines several context managers to support easy thread synchronisation, |
| 2247 | prompt closure of files or other objects, and simpler manipulation of the active |
| 2248 | decimal arithmetic context. The specific types are not treated specially beyond |
| 2249 | their implementation of the context management protocol. See the |
| 2250 | :mod:`contextlib` module for some examples. |
| 2251 | |
Georg Brandl | 7baf625 | 2009-09-01 08:13:16 +0000 | [diff] [blame] | 2252 | Python's :term:`generator`\s and the ``contextlib.contextmanager`` :term:`decorator` |
Christian Heimes | d8654cf | 2007-12-02 15:22:16 +0000 | [diff] [blame] | 2253 | provide a convenient way to implement these protocols. If a generator function is |
Georg Brandl | 7baf625 | 2009-09-01 08:13:16 +0000 | [diff] [blame] | 2254 | decorated with the ``contextlib.contextmanager`` decorator, it will return a |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2255 | context manager implementing the necessary :meth:`__enter__` and |
| 2256 | :meth:`__exit__` methods, rather than the iterator produced by an undecorated |
| 2257 | generator function. |
| 2258 | |
| 2259 | Note that there is no specific slot for any of these methods in the type |
| 2260 | structure for Python objects in the Python/C API. Extension types wanting to |
| 2261 | define these methods must provide them as a normal Python accessible method. |
| 2262 | Compared to the overhead of setting up the runtime context, the overhead of a |
| 2263 | single class dictionary lookup is negligible. |
| 2264 | |
| 2265 | |
| 2266 | .. _typesother: |
| 2267 | |
| 2268 | Other Built-in Types |
| 2269 | ==================== |
| 2270 | |
| 2271 | The interpreter supports several other kinds of objects. Most of these support |
| 2272 | only one or two operations. |
| 2273 | |
| 2274 | |
| 2275 | .. _typesmodules: |
| 2276 | |
| 2277 | Modules |
| 2278 | ------- |
| 2279 | |
| 2280 | The only special operation on a module is attribute access: ``m.name``, where |
| 2281 | *m* is a module and *name* accesses a name defined in *m*'s symbol table. |
| 2282 | Module attributes can be assigned to. (Note that the :keyword:`import` |
| 2283 | statement is not, strictly speaking, an operation on a module object; ``import |
| 2284 | foo`` does not require a module object named *foo* to exist, rather it requires |
| 2285 | an (external) *definition* for a module named *foo* somewhere.) |
| 2286 | |
| 2287 | A special member of every module is :attr:`__dict__`. This is the dictionary |
| 2288 | containing the module's symbol table. Modifying this dictionary will actually |
| 2289 | change the module's symbol table, but direct assignment to the :attr:`__dict__` |
| 2290 | attribute is not possible (you can write ``m.__dict__['a'] = 1``, which defines |
| 2291 | ``m.a`` to be ``1``, but you can't write ``m.__dict__ = {}``). Modifying |
| 2292 | :attr:`__dict__` directly is not recommended. |
| 2293 | |
| 2294 | Modules built into the interpreter are written like this: ``<module 'sys' |
| 2295 | (built-in)>``. If loaded from a file, they are written as ``<module 'os' from |
| 2296 | '/usr/local/lib/pythonX.Y/os.pyc'>``. |
| 2297 | |
| 2298 | |
| 2299 | .. _typesobjects: |
| 2300 | |
| 2301 | Classes and Class Instances |
| 2302 | --------------------------- |
| 2303 | |
| 2304 | See :ref:`objects` and :ref:`class` for these. |
| 2305 | |
| 2306 | |
| 2307 | .. _typesfunctions: |
| 2308 | |
| 2309 | Functions |
| 2310 | --------- |
| 2311 | |
| 2312 | Function objects are created by function definitions. The only operation on a |
| 2313 | function object is to call it: ``func(argument-list)``. |
| 2314 | |
| 2315 | There are really two flavors of function objects: built-in functions and |
| 2316 | user-defined functions. Both support the same operation (to call the function), |
| 2317 | but the implementation is different, hence the different object types. |
| 2318 | |
| 2319 | See :ref:`function` for more information. |
| 2320 | |
| 2321 | |
| 2322 | .. _typesmethods: |
| 2323 | |
| 2324 | Methods |
| 2325 | ------- |
| 2326 | |
| 2327 | .. index:: object: method |
| 2328 | |
| 2329 | Methods are functions that are called using the attribute notation. There are |
| 2330 | two flavors: built-in methods (such as :meth:`append` on lists) and class |
| 2331 | instance methods. Built-in methods are described with the types that support |
| 2332 | them. |
| 2333 | |
Georg Brandl | 2e0b755 | 2007-11-27 12:43:08 +0000 | [diff] [blame] | 2334 | If you access a method (a function defined in a class namespace) through an |
| 2335 | instance, you get a special object: a :dfn:`bound method` (also called |
| 2336 | :dfn:`instance method`) object. When called, it will add the ``self`` argument |
| 2337 | to the argument list. Bound methods have two special read-only attributes: |
| 2338 | ``m.__self__`` is the object on which the method operates, and ``m.__func__`` is |
| 2339 | the function implementing the method. Calling ``m(arg-1, arg-2, ..., arg-n)`` |
| 2340 | is completely equivalent to calling ``m.__func__(m.__self__, arg-1, arg-2, ..., |
| 2341 | arg-n)``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2342 | |
Georg Brandl | 2e0b755 | 2007-11-27 12:43:08 +0000 | [diff] [blame] | 2343 | Like function objects, bound method objects support getting arbitrary |
| 2344 | attributes. However, since method attributes are actually stored on the |
| 2345 | underlying function object (``meth.__func__``), setting method attributes on |
| 2346 | bound methods is disallowed. Attempting to set a method attribute results in a |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2347 | :exc:`TypeError` being raised. In order to set a method attribute, you need to |
| 2348 | explicitly set it on the underlying function object:: |
| 2349 | |
| 2350 | class C: |
| 2351 | def method(self): |
| 2352 | pass |
| 2353 | |
| 2354 | c = C() |
Christian Heimes | ff73795 | 2007-11-27 10:40:20 +0000 | [diff] [blame] | 2355 | c.method.__func__.whoami = 'my name is c' |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2356 | |
| 2357 | See :ref:`types` for more information. |
| 2358 | |
| 2359 | |
| 2360 | .. _bltin-code-objects: |
| 2361 | |
| 2362 | Code Objects |
| 2363 | ------------ |
| 2364 | |
| 2365 | .. index:: object: code |
| 2366 | |
| 2367 | .. index:: |
| 2368 | builtin: compile |
| 2369 | single: __code__ (function object attribute) |
| 2370 | |
| 2371 | Code objects are used by the implementation to represent "pseudo-compiled" |
| 2372 | executable Python code such as a function body. They differ from function |
| 2373 | objects because they don't contain a reference to their global execution |
| 2374 | environment. Code objects are returned by the built-in :func:`compile` function |
| 2375 | and can be extracted from function objects through their :attr:`__code__` |
| 2376 | attribute. See also the :mod:`code` module. |
| 2377 | |
| 2378 | .. index:: |
| 2379 | builtin: exec |
| 2380 | builtin: eval |
| 2381 | |
| 2382 | A code object can be executed or evaluated by passing it (instead of a source |
| 2383 | string) to the :func:`exec` or :func:`eval` built-in functions. |
| 2384 | |
| 2385 | See :ref:`types` for more information. |
| 2386 | |
| 2387 | |
| 2388 | .. _bltin-type-objects: |
| 2389 | |
| 2390 | Type Objects |
| 2391 | ------------ |
| 2392 | |
| 2393 | .. index:: |
| 2394 | builtin: type |
| 2395 | module: types |
| 2396 | |
| 2397 | Type objects represent the various object types. An object's type is accessed |
| 2398 | by the built-in function :func:`type`. There are no special operations on |
| 2399 | types. The standard module :mod:`types` defines names for all standard built-in |
| 2400 | types. |
| 2401 | |
Martin v. Löwis | 250ad61 | 2008-04-07 05:43:42 +0000 | [diff] [blame] | 2402 | Types are written like this: ``<class 'int'>``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2403 | |
| 2404 | |
| 2405 | .. _bltin-null-object: |
| 2406 | |
| 2407 | The Null Object |
| 2408 | --------------- |
| 2409 | |
| 2410 | This object is returned by functions that don't explicitly return a value. It |
| 2411 | supports no special operations. There is exactly one null object, named |
| 2412 | ``None`` (a built-in name). |
| 2413 | |
| 2414 | It is written as ``None``. |
| 2415 | |
| 2416 | |
| 2417 | .. _bltin-ellipsis-object: |
| 2418 | |
| 2419 | The Ellipsis Object |
| 2420 | ------------------- |
| 2421 | |
Georg Brandl | cb8ecb1 | 2007-09-04 06:35:14 +0000 | [diff] [blame] | 2422 | This object is commonly used by slicing (see :ref:`slicings`). It supports no |
| 2423 | special operations. There is exactly one ellipsis object, named |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2424 | :const:`Ellipsis` (a built-in name). |
| 2425 | |
| 2426 | It is written as ``Ellipsis`` or ``...``. |
| 2427 | |
| 2428 | |
| 2429 | Boolean Values |
| 2430 | -------------- |
| 2431 | |
| 2432 | Boolean values are the two constant objects ``False`` and ``True``. They are |
| 2433 | used to represent truth values (although other values can also be considered |
| 2434 | false or true). In numeric contexts (for example when used as the argument to |
| 2435 | an arithmetic operator), they behave like the integers 0 and 1, respectively. |
| 2436 | The built-in function :func:`bool` can be used to cast any value to a Boolean, |
| 2437 | if the value can be interpreted as a truth value (see section Truth Value |
| 2438 | Testing above). |
| 2439 | |
| 2440 | .. index:: |
| 2441 | single: False |
| 2442 | single: True |
| 2443 | pair: Boolean; values |
| 2444 | |
| 2445 | They are written as ``False`` and ``True``, respectively. |
| 2446 | |
| 2447 | |
| 2448 | .. _typesinternal: |
| 2449 | |
| 2450 | Internal Objects |
| 2451 | ---------------- |
| 2452 | |
| 2453 | See :ref:`types` for this information. It describes stack frame objects, |
| 2454 | traceback objects, and slice objects. |
| 2455 | |
| 2456 | |
| 2457 | .. _specialattrs: |
| 2458 | |
| 2459 | Special Attributes |
| 2460 | ================== |
| 2461 | |
| 2462 | The implementation adds a few special read-only attributes to several object |
| 2463 | types, where they are relevant. Some of these are not reported by the |
| 2464 | :func:`dir` built-in function. |
| 2465 | |
| 2466 | |
| 2467 | .. attribute:: object.__dict__ |
| 2468 | |
| 2469 | A dictionary or other mapping object used to store an object's (writable) |
| 2470 | attributes. |
| 2471 | |
| 2472 | |
| 2473 | .. attribute:: instance.__class__ |
| 2474 | |
| 2475 | The class to which a class instance belongs. |
| 2476 | |
| 2477 | |
| 2478 | .. attribute:: class.__bases__ |
| 2479 | |
Benjamin Peterson | 68dbebc | 2009-12-31 03:30:26 +0000 | [diff] [blame] | 2480 | The tuple of base classes of a class object. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2481 | |
| 2482 | |
| 2483 | .. attribute:: class.__name__ |
| 2484 | |
| 2485 | The name of the class or type. |
| 2486 | |
Georg Brandl | 7a51e58 | 2009-03-28 19:13:21 +0000 | [diff] [blame] | 2487 | |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 2488 | The following attributes are only supported by :term:`new-style class`\ es. |
| 2489 | |
| 2490 | .. attribute:: class.__mro__ |
| 2491 | |
| 2492 | This attribute is a tuple of classes that are considered when looking for |
| 2493 | base classes during method resolution. |
| 2494 | |
| 2495 | |
| 2496 | .. method:: class.mro() |
| 2497 | |
| 2498 | This method can be overridden by a metaclass to customize the method |
| 2499 | resolution order for its instances. It is called at class instantiation, and |
| 2500 | its result is stored in :attr:`__mro__`. |
| 2501 | |
| 2502 | |
Georg Brandl | 7a51e58 | 2009-03-28 19:13:21 +0000 | [diff] [blame] | 2503 | .. method:: class.__subclasses__ |
| 2504 | |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 2505 | Each new-style class keeps a list of weak references to its immediate |
| 2506 | subclasses. This method returns a list of all those references still alive. |
| 2507 | Example:: |
Georg Brandl | 7a51e58 | 2009-03-28 19:13:21 +0000 | [diff] [blame] | 2508 | |
| 2509 | >>> int.__subclasses__() |
| 2510 | [<type 'bool'>] |
| 2511 | |
| 2512 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2513 | .. rubric:: Footnotes |
| 2514 | |
| 2515 | .. [#] Additional information on these special methods may be found in the Python |
| 2516 | Reference Manual (:ref:`customization`). |
| 2517 | |
| 2518 | .. [#] As a consequence, the list ``[1, 2]`` is considered equal to ``[1.0, 2.0]``, and |
| 2519 | similarly for tuples. |
| 2520 | |
| 2521 | .. [#] They must have since the parser can't tell the type of the operands. |
| 2522 | |
| 2523 | .. [#] To format only a tuple you should therefore provide a singleton tuple whose only |
| 2524 | element is the tuple to be formatted. |