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