blob: 3242d4acbb99851bd45d8fb31b19557a0f269dff [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001.. XXX: reference/datamodel and this have quite a few overlaps!
2
3
4.. _bltin-types:
5
6**************
7Built-in Types
8**************
9
10The following sections describe the standard types that are built into the
11interpreter.
12
Georg Brandl116aa622007-08-15 14:28:22 +000013.. index:: pair: built-in; types
14
Antoine Pitroue231e392009-12-19 18:22:15 +000015The principal built-in types are numerics, sequences, mappings, classes,
Georg Brandl116aa622007-08-15 14:28:22 +000016instances and exceptions.
17
Georg Brandl388349a2011-10-08 18:32:40 +020018Some collection classes are mutable. The methods that add, subtract, or
19rearrange their members in place, and don't return a specific item, never return
20the collection instance itself but ``None``.
21
Georg Brandl116aa622007-08-15 14:28:22 +000022Some operations are supported by several object types; in particular,
23practically all objects can be compared, tested for truth value, and converted
24to a string (with the :func:`repr` function or the slightly different
25:func:`str` function). The latter function is implicitly used when an object is
26written by the :func:`print` function.
27
28
29.. _truth:
30
31Truth Value Testing
32===================
33
34.. index::
35 statement: if
36 statement: while
37 pair: truth; value
38 pair: Boolean; operations
39 single: false
40
41Any object can be tested for truth value, for use in an :keyword:`if` or
42:keyword:`while` condition or as operand of the Boolean operations below. The
43following values are considered false:
44
45 .. index:: single: None (Built-in object)
46
47* ``None``
48
49 .. index:: single: False (Built-in object)
50
51* ``False``
52
Mark Summerfieldbbfd71d2008-07-01 15:50:04 +000053* zero of any numeric type, for example, ``0``, ``0.0``, ``0j``.
Georg Brandl116aa622007-08-15 14:28:22 +000054
55* any empty sequence, for example, ``''``, ``()``, ``[]``.
56
57* any empty mapping, for example, ``{}``.
58
59* instances of user-defined classes, if the class defines a :meth:`__bool__` or
60 :meth:`__len__` method, when that method returns the integer zero or
Ezio Melotti0656a562011-08-15 14:27:19 +030061 :class:`bool` value ``False``. [1]_
Georg Brandl116aa622007-08-15 14:28:22 +000062
63.. index:: single: true
64
65All other values are considered true --- so objects of many types are always
66true.
67
68.. index::
69 operator: or
70 operator: and
71 single: False
72 single: True
73
74Operations and built-in functions that have a Boolean result always return ``0``
75or ``False`` for false and ``1`` or ``True`` for true, unless otherwise stated.
76(Important exception: the Boolean operations ``or`` and ``and`` always return
77one of their operands.)
78
79
80.. _boolean:
81
82Boolean Operations --- :keyword:`and`, :keyword:`or`, :keyword:`not`
83====================================================================
84
85.. index:: pair: Boolean; operations
86
87These are the Boolean operations, ordered by ascending priority:
88
89+-------------+---------------------------------+-------+
90| Operation | Result | Notes |
91+=============+=================================+=======+
92| ``x or y`` | if *x* is false, then *y*, else | \(1) |
93| | *x* | |
94+-------------+---------------------------------+-------+
95| ``x and y`` | if *x* is false, then *x*, else | \(2) |
96| | *y* | |
97+-------------+---------------------------------+-------+
98| ``not x`` | if *x* is false, then ``True``, | \(3) |
99| | else ``False`` | |
100+-------------+---------------------------------+-------+
101
102.. index::
103 operator: and
104 operator: or
105 operator: not
106
107Notes:
108
109(1)
110 This is a short-circuit operator, so it only evaluates the second
111 argument if the first one is :const:`False`.
112
113(2)
114 This is a short-circuit operator, so it only evaluates the second
115 argument if the first one is :const:`True`.
116
117(3)
118 ``not`` has a lower priority than non-Boolean operators, so ``not a == b`` is
119 interpreted as ``not (a == b)``, and ``a == not b`` is a syntax error.
120
121
122.. _stdcomparisons:
123
124Comparisons
125===========
126
Alexandre Vassalotti6d3dfc32009-07-29 19:54:39 +0000127.. index::
128 pair: chaining; comparisons
129 pair: operator; comparison
130 operator: ==
131 operator: <
132 operator: <=
133 operator: >
134 operator: >=
135 operator: !=
136 operator: is
137 operator: is not
Georg Brandl116aa622007-08-15 14:28:22 +0000138
Georg Brandl905ec322007-09-28 13:39:25 +0000139There are eight comparison operations in Python. They all have the same
140priority (which is higher than that of the Boolean operations). Comparisons can
Georg Brandl116aa622007-08-15 14:28:22 +0000141be chained arbitrarily; for example, ``x < y <= z`` is equivalent to ``x < y and
142y <= z``, except that *y* is evaluated only once (but in both cases *z* is not
143evaluated at all when ``x < y`` is found to be false).
144
145This table summarizes the comparison operations:
146
Georg Brandlfd855162008-01-07 09:13:03 +0000147+------------+-------------------------+
148| Operation | Meaning |
149+============+=========================+
150| ``<`` | strictly less than |
151+------------+-------------------------+
152| ``<=`` | less than or equal |
153+------------+-------------------------+
154| ``>`` | strictly greater than |
155+------------+-------------------------+
156| ``>=`` | greater than or equal |
157+------------+-------------------------+
158| ``==`` | equal |
159+------------+-------------------------+
160| ``!=`` | not equal |
161+------------+-------------------------+
162| ``is`` | object identity |
163+------------+-------------------------+
164| ``is not`` | negated object identity |
165+------------+-------------------------+
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000166
167.. index::
Georg Brandl116aa622007-08-15 14:28:22 +0000168 pair: object; numeric
169 pair: objects; comparing
170
Georg Brandl905ec322007-09-28 13:39:25 +0000171Objects of different types, except different numeric types, never compare equal.
Antoine Pitroue231e392009-12-19 18:22:15 +0000172Furthermore, some types (for example, function objects) support only a degenerate
Georg Brandl905ec322007-09-28 13:39:25 +0000173notion of comparison where any two objects of that type are unequal. The ``<``,
174``<=``, ``>`` and ``>=`` operators will raise a :exc:`TypeError` exception when
Mark Dickinsonf673f0c2010-03-13 09:48:39 +0000175comparing a complex number with another built-in numeric type, when the objects
176are of different types that cannot be compared, or in other cases where there is
177no defined ordering.
Georg Brandl116aa622007-08-15 14:28:22 +0000178
Georg Brandl48310cd2009-01-03 21:18:54 +0000179.. index::
Georg Brandl905ec322007-09-28 13:39:25 +0000180 single: __eq__() (instance method)
181 single: __ne__() (instance method)
182 single: __lt__() (instance method)
183 single: __le__() (instance method)
184 single: __gt__() (instance method)
185 single: __ge__() (instance method)
Georg Brandl116aa622007-08-15 14:28:22 +0000186
Georg Brandl05f5ab72008-09-24 09:11:47 +0000187Non-identical instances of a class normally compare as non-equal unless the
188class defines the :meth:`__eq__` method.
Georg Brandl116aa622007-08-15 14:28:22 +0000189
Georg Brandl905ec322007-09-28 13:39:25 +0000190Instances of a class cannot be ordered with respect to other instances of the
191same class, or other types of object, unless the class defines enough of the
Georg Brandl05f5ab72008-09-24 09:11:47 +0000192methods :meth:`__lt__`, :meth:`__le__`, :meth:`__gt__`, and :meth:`__ge__` (in
193general, :meth:`__lt__` and :meth:`__eq__` are sufficient, if you want the
194conventional meanings of the comparison operators).
Georg Brandl905ec322007-09-28 13:39:25 +0000195
196The behavior of the :keyword:`is` and :keyword:`is not` operators cannot be
197customized; also they can be applied to any two objects and never raise an
198exception.
Georg Brandl116aa622007-08-15 14:28:22 +0000199
200.. index::
201 operator: in
202 operator: not in
203
Georg Brandl375aec22011-01-15 17:03:02 +0000204Two more operations with the same syntactic priority, :keyword:`in` and
205:keyword:`not in`, are supported only by sequence types (below).
Georg Brandl116aa622007-08-15 14:28:22 +0000206
207
208.. _typesnumeric:
209
Georg Brandl905ec322007-09-28 13:39:25 +0000210Numeric Types --- :class:`int`, :class:`float`, :class:`complex`
211================================================================
Georg Brandl116aa622007-08-15 14:28:22 +0000212
213.. index::
214 object: numeric
215 object: Boolean
216 object: integer
Georg Brandl116aa622007-08-15 14:28:22 +0000217 object: floating point
218 object: complex number
219 pair: C; language
220
Mark Summerfieldbbfd71d2008-07-01 15:50:04 +0000221There are three distinct numeric types: :dfn:`integers`, :dfn:`floating
222point numbers`, and :dfn:`complex numbers`. In addition, Booleans are a
223subtype of integers. Integers have unlimited precision. Floating point
Georg Brandl60203b42010-10-06 10:11:56 +0000224numbers are usually implemented using :c:type:`double` in C; information
Mark Dickinson74f59022010-08-04 18:42:43 +0000225about the precision and internal representation of floating point
226numbers for the machine on which your program is running is available
227in :data:`sys.float_info`. Complex numbers have a real and imaginary
228part, which are each a floating point number. To extract these parts
229from a complex number *z*, use ``z.real`` and ``z.imag``. (The standard
230library includes additional numeric types, :mod:`fractions` that hold
231rationals, and :mod:`decimal` that hold floating-point numbers with
232user-definable precision.)
Georg Brandl116aa622007-08-15 14:28:22 +0000233
234.. index::
235 pair: numeric; literals
236 pair: integer; literals
Georg Brandl116aa622007-08-15 14:28:22 +0000237 pair: floating point; literals
238 pair: complex number; literals
239 pair: hexadecimal; literals
240 pair: octal; literals
Neal Norwitz1d2aef52007-10-02 07:26:14 +0000241 pair: binary; literals
Georg Brandl116aa622007-08-15 14:28:22 +0000242
243Numbers are created by numeric literals or as the result of built-in functions
Georg Brandl905ec322007-09-28 13:39:25 +0000244and operators. Unadorned integer literals (including hex, octal and binary
245numbers) yield integers. Numeric literals containing a decimal point or an
246exponent sign yield floating point numbers. Appending ``'j'`` or ``'J'`` to a
247numeric literal yields an imaginary number (a complex number with a zero real
248part) which you can add to an integer or float to get a complex number with real
249and imaginary parts.
Georg Brandl116aa622007-08-15 14:28:22 +0000250
251.. index::
252 single: arithmetic
253 builtin: int
Georg Brandl116aa622007-08-15 14:28:22 +0000254 builtin: float
255 builtin: complex
Alexandre Vassalotti6d3dfc32009-07-29 19:54:39 +0000256 operator: +
257 operator: -
258 operator: *
259 operator: /
260 operator: //
261 operator: %
262 operator: **
Georg Brandl116aa622007-08-15 14:28:22 +0000263
264Python fully supports mixed arithmetic: when a binary arithmetic operator has
265operands of different numeric types, the operand with the "narrower" type is
Georg Brandl905ec322007-09-28 13:39:25 +0000266widened to that of the other, where integer is narrower than floating point,
267which is narrower than complex. Comparisons between numbers of mixed type use
Ezio Melotti0656a562011-08-15 14:27:19 +0300268the same rule. [2]_ The constructors :func:`int`, :func:`float`, and
Georg Brandl905ec322007-09-28 13:39:25 +0000269:func:`complex` can be used to produce numbers of a specific type.
Georg Brandl116aa622007-08-15 14:28:22 +0000270
271All numeric types (except complex) support the following operations, sorted by
272ascending priority (operations in the same box have the same priority; all
273numeric operations have a higher priority than comparison operations):
274
Raymond Hettingerc706dbf2011-03-22 17:33:17 -0700275+---------------------+---------------------------------+---------+--------------------+
276| Operation | Result | Notes | Full documentation |
277+=====================+=================================+=========+====================+
278| ``x + y`` | sum of *x* and *y* | | |
279+---------------------+---------------------------------+---------+--------------------+
280| ``x - y`` | difference of *x* and *y* | | |
281+---------------------+---------------------------------+---------+--------------------+
282| ``x * y`` | product of *x* and *y* | | |
283+---------------------+---------------------------------+---------+--------------------+
284| ``x / y`` | quotient of *x* and *y* | | |
285+---------------------+---------------------------------+---------+--------------------+
286| ``x // y`` | floored quotient of *x* and | \(1) | |
287| | *y* | | |
288+---------------------+---------------------------------+---------+--------------------+
289| ``x % y`` | remainder of ``x / y`` | \(2) | |
290+---------------------+---------------------------------+---------+--------------------+
291| ``-x`` | *x* negated | | |
292+---------------------+---------------------------------+---------+--------------------+
293| ``+x`` | *x* unchanged | | |
294+---------------------+---------------------------------+---------+--------------------+
295| ``abs(x)`` | absolute value or magnitude of | | :func:`abs` |
296| | *x* | | |
297+---------------------+---------------------------------+---------+--------------------+
298| ``int(x)`` | *x* converted to integer | \(3)\(6)| :func:`int` |
299+---------------------+---------------------------------+---------+--------------------+
300| ``float(x)`` | *x* converted to floating point | \(4)\(6)| :func:`float` |
301+---------------------+---------------------------------+---------+--------------------+
302| ``complex(re, im)`` | a complex number with real part | \(6) | :func:`complex` |
303| | *re*, imaginary part *im*. | | |
304| | *im* defaults to zero. | | |
305+---------------------+---------------------------------+---------+--------------------+
306| ``c.conjugate()`` | conjugate of the complex number | | |
307| | *c* | | |
308+---------------------+---------------------------------+---------+--------------------+
309| ``divmod(x, y)`` | the pair ``(x // y, x % y)`` | \(2) | :func:`divmod` |
310+---------------------+---------------------------------+---------+--------------------+
311| ``pow(x, y)`` | *x* to the power *y* | \(5) | :func:`pow` |
312+---------------------+---------------------------------+---------+--------------------+
313| ``x ** y`` | *x* to the power *y* | \(5) | |
314+---------------------+---------------------------------+---------+--------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000315
316.. index::
317 triple: operations on; numeric; types
318 single: conjugate() (complex number method)
319
320Notes:
321
322(1)
Georg Brandl905ec322007-09-28 13:39:25 +0000323 Also referred to as integer division. The resultant value is a whole
324 integer, though the result's type is not necessarily int. The result is
325 always rounded towards minus infinity: ``1//2`` is ``0``, ``(-1)//2`` is
326 ``-1``, ``1//(-2)`` is ``-1``, and ``(-1)//(-2)`` is ``0``.
Georg Brandl116aa622007-08-15 14:28:22 +0000327
328(2)
Georg Brandl905ec322007-09-28 13:39:25 +0000329 Not for complex numbers. Instead convert to floats using :func:`abs` if
330 appropriate.
331
332(3)
Georg Brandl116aa622007-08-15 14:28:22 +0000333 .. index::
334 module: math
335 single: floor() (in module math)
336 single: ceil() (in module math)
Benjamin Peterson28d88b42009-01-09 03:03:23 +0000337 single: trunc() (in module math)
Georg Brandl116aa622007-08-15 14:28:22 +0000338 pair: numeric; conversions
339 pair: C; language
340
Georg Brandlba956ae2007-11-29 17:24:34 +0000341 Conversion from floating point to integer may round or truncate
Georg Brandl116aa622007-08-15 14:28:22 +0000342 as in C; see functions :func:`floor` and :func:`ceil` in the :mod:`math` module
343 for well-defined conversions.
344
Georg Brandl74f36692008-01-06 17:39:49 +0000345(4)
Georg Brandl48310cd2009-01-03 21:18:54 +0000346 float also accepts the strings "nan" and "inf" with an optional prefix "+"
Christian Heimes99170a52007-12-19 02:07:34 +0000347 or "-" for Not a Number (NaN) and positive or negative infinity.
Christian Heimes7f044312008-01-06 17:05:40 +0000348
Georg Brandl74f36692008-01-06 17:39:49 +0000349(5)
Christian Heimes7f044312008-01-06 17:05:40 +0000350 Python defines ``pow(0, 0)`` and ``0 ** 0`` to be ``1``, as is common for
351 programming languages.
352
Raymond Hettingerc706dbf2011-03-22 17:33:17 -0700353(6)
354 The numeric literals accepted include the digits ``0`` to ``9`` or any
355 Unicode equivalent (code points with the ``Nd`` property).
356
357 See http://www.unicode.org/Public/6.0.0/ucd/extracted/DerivedNumericType.txt
358 for a complete list of code points with the ``Nd`` property.
Georg Brandl48310cd2009-01-03 21:18:54 +0000359
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000360
Benjamin Peterson10116d42011-05-01 17:38:17 -0500361All :class:`numbers.Real` types (:class:`int` and :class:`float`) also include
362the following operations:
Christian Heimesfaf2f632008-01-06 16:59:19 +0000363
Benjamin Petersonb58dda72009-01-18 22:27:04 +0000364+--------------------+------------------------------------+--------+
365| Operation | Result | Notes |
366+====================+====================================+========+
367| ``math.trunc(x)`` | *x* truncated to Integral | |
368+--------------------+------------------------------------+--------+
369| ``round(x[, n])`` | *x* rounded to n digits, | |
370| | rounding half to even. If n is | |
371| | omitted, it defaults to 0. | |
372+--------------------+------------------------------------+--------+
373| ``math.floor(x)`` | the greatest integral float <= *x* | |
374+--------------------+------------------------------------+--------+
375| ``math.ceil(x)`` | the least integral float >= *x* | |
376+--------------------+------------------------------------+--------+
Christian Heimesfaf2f632008-01-06 16:59:19 +0000377
Mark Summerfieldbbfd71d2008-07-01 15:50:04 +0000378For additional numeric operations see the :mod:`math` and :mod:`cmath`
379modules.
380
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000381.. XXXJH exceptions: overflow (when? what operations?) zerodivision
Georg Brandl116aa622007-08-15 14:28:22 +0000382
383
384.. _bitstring-ops:
385
Benjamin Petersone9fca252012-01-25 16:29:03 -0500386Bitwise Operations on Integer Types
Georg Brandl116aa622007-08-15 14:28:22 +0000387--------------------------------------
388
Alexandre Vassalotti6d3dfc32009-07-29 19:54:39 +0000389.. index::
390 triple: operations on; integer; types
Benjamin Petersone9fca252012-01-25 16:29:03 -0500391 pair: bitwise; operations
Alexandre Vassalotti6d3dfc32009-07-29 19:54:39 +0000392 pair: shifting; operations
393 pair: masking; operations
394 operator: ^
395 operator: &
396 operator: <<
397 operator: >>
Georg Brandl116aa622007-08-15 14:28:22 +0000398
Benjamin Petersonb4b0b352012-01-25 16:30:18 -0500399Bitwise operations only make sense for integers. Negative numbers are treated
400as their 2's complement value (this assumes a sufficiently large number of bits
401that no overflow occurs during the operation).
Georg Brandl116aa622007-08-15 14:28:22 +0000402
Christian Heimesfaf2f632008-01-06 16:59:19 +0000403The priorities of the binary bitwise operations are all lower than the numeric
Georg Brandl116aa622007-08-15 14:28:22 +0000404operations and higher than the comparisons; the unary operation ``~`` has the
405same priority as the other unary numeric operations (``+`` and ``-``).
406
Benjamin Petersone9fca252012-01-25 16:29:03 -0500407This table lists the bitwise operations sorted in ascending priority
Georg Brandl116aa622007-08-15 14:28:22 +0000408(operations in the same box have the same priority):
409
410+------------+--------------------------------+----------+
411| Operation | Result | Notes |
412+============+================================+==========+
413| ``x | y`` | bitwise :dfn:`or` of *x* and | |
414| | *y* | |
415+------------+--------------------------------+----------+
416| ``x ^ y`` | bitwise :dfn:`exclusive or` of | |
417| | *x* and *y* | |
418+------------+--------------------------------+----------+
419| ``x & y`` | bitwise :dfn:`and` of *x* and | |
420| | *y* | |
421+------------+--------------------------------+----------+
Christian Heimes043d6f62008-01-07 17:19:16 +0000422| ``x << n`` | *x* shifted left by *n* bits | (1)(2) |
Georg Brandl116aa622007-08-15 14:28:22 +0000423+------------+--------------------------------+----------+
Christian Heimes043d6f62008-01-07 17:19:16 +0000424| ``x >> n`` | *x* shifted right by *n* bits | (1)(3) |
Georg Brandl116aa622007-08-15 14:28:22 +0000425+------------+--------------------------------+----------+
426| ``~x`` | the bits of *x* inverted | |
427+------------+--------------------------------+----------+
428
Georg Brandl116aa622007-08-15 14:28:22 +0000429Notes:
430
431(1)
432 Negative shift counts are illegal and cause a :exc:`ValueError` to be raised.
433
434(2)
435 A left shift by *n* bits is equivalent to multiplication by ``pow(2, n)``
436 without overflow check.
437
438(3)
439 A right shift by *n* bits is equivalent to division by ``pow(2, n)`` without
440 overflow check.
441
442
Mark Dickinson54bc1ec2008-12-17 16:19:07 +0000443Additional Methods on Integer Types
444-----------------------------------
445
Raymond Hettinger9b2fd322011-05-01 18:14:49 -0700446The int type implements the :class:`numbers.Integral` :term:`abstract base
Éric Araujob79c2342011-05-02 13:10:18 +0200447class`. In addition, it provides one more method:
Benjamin Peterson10116d42011-05-01 17:38:17 -0500448
Mark Dickinson54bc1ec2008-12-17 16:19:07 +0000449.. method:: int.bit_length()
450
Raymond Hettingerd3e18b72008-12-19 09:11:49 +0000451 Return the number of bits necessary to represent an integer in binary,
452 excluding the sign and leading zeros::
Mark Dickinson54bc1ec2008-12-17 16:19:07 +0000453
Raymond Hettingerd3e18b72008-12-19 09:11:49 +0000454 >>> n = -37
Mark Dickinson54bc1ec2008-12-17 16:19:07 +0000455 >>> bin(n)
Raymond Hettingerd3e18b72008-12-19 09:11:49 +0000456 '-0b100101'
Mark Dickinson54bc1ec2008-12-17 16:19:07 +0000457 >>> n.bit_length()
458 6
Mark Dickinson54bc1ec2008-12-17 16:19:07 +0000459
Raymond Hettingerd3e18b72008-12-19 09:11:49 +0000460 More precisely, if ``x`` is nonzero, then ``x.bit_length()`` is the
461 unique positive integer ``k`` such that ``2**(k-1) <= abs(x) < 2**k``.
462 Equivalently, when ``abs(x)`` is small enough to have a correctly
463 rounded logarithm, then ``k = 1 + int(log(abs(x), 2))``.
464 If ``x`` is zero, then ``x.bit_length()`` returns ``0``.
Mark Dickinson54bc1ec2008-12-17 16:19:07 +0000465
466 Equivalent to::
467
468 def bit_length(self):
Senthil Kumaran0aae6dc2010-06-22 02:57:23 +0000469 s = bin(self) # binary representation: bin(-37) --> '-0b100101'
Raymond Hettingerd3e18b72008-12-19 09:11:49 +0000470 s = s.lstrip('-0b') # remove leading zeros and minus sign
471 return len(s) # len('100101') --> 6
Mark Dickinson54bc1ec2008-12-17 16:19:07 +0000472
473 .. versionadded:: 3.1
474
Georg Brandl67b21b72010-08-17 15:07:14 +0000475.. method:: int.to_bytes(length, byteorder, \*, signed=False)
Alexandre Vassalottic36c3782010-01-09 20:35:09 +0000476
477 Return an array of bytes representing an integer.
478
479 >>> (1024).to_bytes(2, byteorder='big')
480 b'\x04\x00'
481 >>> (1024).to_bytes(10, byteorder='big')
482 b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00'
483 >>> (-1024).to_bytes(10, byteorder='big', signed=True)
484 b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00'
485 >>> x = 1000
486 >>> x.to_bytes((x.bit_length() // 8) + 1, byteorder='little')
487 b'\xe8\x03'
488
489 The integer is represented using *length* bytes. An :exc:`OverflowError`
490 is raised if the integer is not representable with the given number of
491 bytes.
492
493 The *byteorder* argument determines the byte order used to represent the
494 integer. If *byteorder* is ``"big"``, the most significant byte is at the
495 beginning of the byte array. If *byteorder* is ``"little"``, the most
496 significant byte is at the end of the byte array. To request the native
497 byte order of the host system, use :data:`sys.byteorder` as the byte order
498 value.
499
500 The *signed* argument determines whether two's complement is used to
501 represent the integer. If *signed* is ``False`` and a negative integer is
502 given, an :exc:`OverflowError` is raised. The default value for *signed*
503 is ``False``.
504
505 .. versionadded:: 3.2
506
Georg Brandl67b21b72010-08-17 15:07:14 +0000507.. classmethod:: int.from_bytes(bytes, byteorder, \*, signed=False)
Alexandre Vassalottic36c3782010-01-09 20:35:09 +0000508
509 Return the integer represented by the given array of bytes.
510
511 >>> int.from_bytes(b'\x00\x10', byteorder='big')
512 16
513 >>> int.from_bytes(b'\x00\x10', byteorder='little')
514 4096
515 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True)
516 -1024
517 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False)
518 64512
519 >>> int.from_bytes([255, 0, 0], byteorder='big')
520 16711680
521
522 The argument *bytes* must either support the buffer protocol or be an
523 iterable producing bytes. :class:`bytes` and :class:`bytearray` are
524 examples of built-in objects that support the buffer protocol.
525
526 The *byteorder* argument determines the byte order used to represent the
527 integer. If *byteorder* is ``"big"``, the most significant byte is at the
528 beginning of the byte array. If *byteorder* is ``"little"``, the most
529 significant byte is at the end of the byte array. To request the native
530 byte order of the host system, use :data:`sys.byteorder` as the byte order
531 value.
532
533 The *signed* argument indicates whether two's complement is used to
534 represent the integer.
535
536 .. versionadded:: 3.2
537
Mark Dickinson54bc1ec2008-12-17 16:19:07 +0000538
Mark Dickinson65fe25e2008-07-16 11:30:51 +0000539Additional Methods on Float
540---------------------------
541
Benjamin Peterson10116d42011-05-01 17:38:17 -0500542The float type implements the :class:`numbers.Real` :term:`abstract base
543class`. float also has the following additional methods.
Benjamin Petersond7b03282008-09-13 15:58:53 +0000544
545.. method:: float.as_integer_ratio()
546
Mark Dickinson4a3c7c42010-11-07 12:48:18 +0000547 Return a pair of integers whose ratio is exactly equal to the
548 original float and with a positive denominator. Raises
549 :exc:`OverflowError` on infinities and a :exc:`ValueError` on
550 NaNs.
551
552.. method:: float.is_integer()
553
554 Return ``True`` if the float instance is finite with integral
555 value, and ``False`` otherwise::
556
557 >>> (-2.0).is_integer()
558 True
559 >>> (3.2).is_integer()
560 False
Georg Brandl48310cd2009-01-03 21:18:54 +0000561
Benjamin Petersond7b03282008-09-13 15:58:53 +0000562Two methods support conversion to
Mark Dickinson65fe25e2008-07-16 11:30:51 +0000563and from hexadecimal strings. Since Python's floats are stored
564internally as binary numbers, converting a float to or from a
565*decimal* string usually involves a small rounding error. In
566contrast, hexadecimal strings allow exact representation and
567specification of floating-point numbers. This can be useful when
568debugging, and in numerical work.
569
570
571.. method:: float.hex()
572
573 Return a representation of a floating-point number as a hexadecimal
574 string. For finite floating-point numbers, this representation
575 will always include a leading ``0x`` and a trailing ``p`` and
576 exponent.
577
578
Georg Brandlabc38772009-04-12 15:51:51 +0000579.. classmethod:: float.fromhex(s)
Mark Dickinson65fe25e2008-07-16 11:30:51 +0000580
581 Class method to return the float represented by a hexadecimal
582 string *s*. The string *s* may have leading and trailing
583 whitespace.
584
585
586Note that :meth:`float.hex` is an instance method, while
587:meth:`float.fromhex` is a class method.
588
589A hexadecimal string takes the form::
590
591 [sign] ['0x'] integer ['.' fraction] ['p' exponent]
592
593where the optional ``sign`` may by either ``+`` or ``-``, ``integer``
594and ``fraction`` are strings of hexadecimal digits, and ``exponent``
595is a decimal integer with an optional leading sign. Case is not
596significant, and there must be at least one hexadecimal digit in
597either the integer or the fraction. This syntax is similar to the
598syntax specified in section 6.4.4.2 of the C99 standard, and also to
599the syntax used in Java 1.5 onwards. In particular, the output of
600:meth:`float.hex` is usable as a hexadecimal floating-point literal in
601C or Java code, and hexadecimal strings produced by C's ``%a`` format
602character or Java's ``Double.toHexString`` are accepted by
603:meth:`float.fromhex`.
604
605
606Note that the exponent is written in decimal rather than hexadecimal,
607and that it gives the power of 2 by which to multiply the coefficient.
608For example, the hexadecimal string ``0x3.a7p10`` represents the
609floating-point number ``(3 + 10./16 + 7./16**2) * 2.0**10``, or
610``3740.0``::
611
612 >>> float.fromhex('0x3.a7p10')
613 3740.0
614
615
616Applying the reverse conversion to ``3740.0`` gives a different
617hexadecimal string representing the same number::
618
619 >>> float.hex(3740.0)
620 '0x1.d380000000000p+11'
621
622
Mark Dickinsondc787d22010-05-23 13:33:13 +0000623.. _numeric-hash:
624
625Hashing of numeric types
626------------------------
627
628For numbers ``x`` and ``y``, possibly of different types, it's a requirement
629that ``hash(x) == hash(y)`` whenever ``x == y`` (see the :meth:`__hash__`
630method documentation for more details). For ease of implementation and
631efficiency across a variety of numeric types (including :class:`int`,
632:class:`float`, :class:`decimal.Decimal` and :class:`fractions.Fraction`)
633Python's hash for numeric types is based on a single mathematical function
634that's defined for any rational number, and hence applies to all instances of
635:class:`int` and :class:`fraction.Fraction`, and all finite instances of
636:class:`float` and :class:`decimal.Decimal`. Essentially, this function is
637given by reduction modulo ``P`` for a fixed prime ``P``. The value of ``P`` is
638made available to Python as the :attr:`modulus` attribute of
639:data:`sys.hash_info`.
640
641.. impl-detail::
642
643 Currently, the prime used is ``P = 2**31 - 1`` on machines with 32-bit C
644 longs and ``P = 2**61 - 1`` on machines with 64-bit C longs.
645
646Here are the rules in detail:
647
Georg Brandl226ed7e2012-03-24 08:12:41 +0100648- If ``x = m / n`` is a nonnegative rational number and ``n`` is not divisible
649 by ``P``, define ``hash(x)`` as ``m * invmod(n, P) % P``, where ``invmod(n,
650 P)`` gives the inverse of ``n`` modulo ``P``.
Mark Dickinsondc787d22010-05-23 13:33:13 +0000651
Georg Brandl226ed7e2012-03-24 08:12:41 +0100652- If ``x = m / n`` is a nonnegative rational number and ``n`` is
653 divisible by ``P`` (but ``m`` is not) then ``n`` has no inverse
654 modulo ``P`` and the rule above doesn't apply; in this case define
655 ``hash(x)`` to be the constant value ``sys.hash_info.inf``.
Mark Dickinsondc787d22010-05-23 13:33:13 +0000656
Georg Brandl226ed7e2012-03-24 08:12:41 +0100657- If ``x = m / n`` is a negative rational number define ``hash(x)``
658 as ``-hash(-x)``. If the resulting hash is ``-1``, replace it with
659 ``-2``.
Mark Dickinsondc787d22010-05-23 13:33:13 +0000660
Georg Brandl226ed7e2012-03-24 08:12:41 +0100661- The particular values ``sys.hash_info.inf``, ``-sys.hash_info.inf``
662 and ``sys.hash_info.nan`` are used as hash values for positive
663 infinity, negative infinity, or nans (respectively). (All hashable
664 nans have the same hash value.)
Mark Dickinsondc787d22010-05-23 13:33:13 +0000665
Georg Brandl226ed7e2012-03-24 08:12:41 +0100666- For a :class:`complex` number ``z``, the hash values of the real
667 and imaginary parts are combined by computing ``hash(z.real) +
668 sys.hash_info.imag * hash(z.imag)``, reduced modulo
669 ``2**sys.hash_info.width`` so that it lies in
670 ``range(-2**(sys.hash_info.width - 1), 2**(sys.hash_info.width -
671 1))``. Again, if the result is ``-1``, it's replaced with ``-2``.
Mark Dickinsondc787d22010-05-23 13:33:13 +0000672
673
674To clarify the above rules, here's some example Python code,
Nick Coghlan273069c2012-08-20 17:14:07 +1000675equivalent to the built-in hash, for computing the hash of a rational
Mark Dickinsondc787d22010-05-23 13:33:13 +0000676number, :class:`float`, or :class:`complex`::
677
678
679 import sys, math
680
681 def hash_fraction(m, n):
682 """Compute the hash of a rational number m / n.
683
684 Assumes m and n are integers, with n positive.
685 Equivalent to hash(fractions.Fraction(m, n)).
686
687 """
688 P = sys.hash_info.modulus
689 # Remove common factors of P. (Unnecessary if m and n already coprime.)
690 while m % P == n % P == 0:
691 m, n = m // P, n // P
692
693 if n % P == 0:
694 hash_ = sys.hash_info.inf
695 else:
696 # Fermat's Little Theorem: pow(n, P-1, P) is 1, so
697 # pow(n, P-2, P) gives the inverse of n modulo P.
698 hash_ = (abs(m) % P) * pow(n, P - 2, P) % P
699 if m < 0:
700 hash_ = -hash_
701 if hash_ == -1:
702 hash_ = -2
703 return hash_
704
705 def hash_float(x):
706 """Compute the hash of a float x."""
707
708 if math.isnan(x):
709 return sys.hash_info.nan
710 elif math.isinf(x):
711 return sys.hash_info.inf if x > 0 else -sys.hash_info.inf
712 else:
713 return hash_fraction(*x.as_integer_ratio())
714
715 def hash_complex(z):
716 """Compute the hash of a complex number z."""
717
718 hash_ = hash_float(z.real) + sys.hash_info.imag * hash_float(z.imag)
719 # do a signed reduction modulo 2**sys.hash_info.width
720 M = 2**(sys.hash_info.width - 1)
721 hash_ = (hash_ & (M - 1)) - (hash & M)
722 if hash_ == -1:
723 hash_ == -2
724 return hash_
725
Georg Brandl6ea420b2008-07-16 12:58:29 +0000726.. _typeiter:
727
Georg Brandl116aa622007-08-15 14:28:22 +0000728Iterator Types
729==============
730
Georg Brandl116aa622007-08-15 14:28:22 +0000731.. index::
732 single: iterator protocol
733 single: protocol; iterator
734 single: sequence; iteration
735 single: container; iteration over
736
737Python supports a concept of iteration over containers. This is implemented
738using two distinct methods; these are used to allow user-defined classes to
739support iteration. Sequences, described below in more detail, always support
740the iteration methods.
741
742One method needs to be defined for container objects to provide iteration
743support:
744
Christian Heimes790c8232008-01-07 21:14:23 +0000745.. XXX duplicated in reference/datamodel!
Georg Brandl116aa622007-08-15 14:28:22 +0000746
Christian Heimes790c8232008-01-07 21:14:23 +0000747.. method:: container.__iter__()
Georg Brandl116aa622007-08-15 14:28:22 +0000748
749 Return an iterator object. The object is required to support the iterator
750 protocol described below. If a container supports different types of
751 iteration, additional methods can be provided to specifically request
752 iterators for those iteration types. (An example of an object supporting
753 multiple forms of iteration would be a tree structure which supports both
754 breadth-first and depth-first traversal.) This method corresponds to the
755 :attr:`tp_iter` slot of the type structure for Python objects in the Python/C
756 API.
757
758The iterator objects themselves are required to support the following two
759methods, which together form the :dfn:`iterator protocol`:
760
761
762.. method:: iterator.__iter__()
763
764 Return the iterator object itself. This is required to allow both containers
765 and iterators to be used with the :keyword:`for` and :keyword:`in` statements.
766 This method corresponds to the :attr:`tp_iter` slot of the type structure for
767 Python objects in the Python/C API.
768
769
Georg Brandl905ec322007-09-28 13:39:25 +0000770.. method:: iterator.__next__()
Georg Brandl116aa622007-08-15 14:28:22 +0000771
772 Return the next item from the container. If there are no further items, raise
773 the :exc:`StopIteration` exception. This method corresponds to the
774 :attr:`tp_iternext` slot of the type structure for Python objects in the
775 Python/C API.
776
777Python defines several iterator objects to support iteration over general and
778specific sequence types, dictionaries, and other more specialized forms. The
779specific types are not important beyond their implementation of the iterator
780protocol.
781
Georg Brandl905ec322007-09-28 13:39:25 +0000782Once an iterator's :meth:`__next__` method raises :exc:`StopIteration`, it must
783continue to do so on subsequent calls. Implementations that do not obey this
784property are deemed broken.
Georg Brandl116aa622007-08-15 14:28:22 +0000785
Benjamin Peterson0289b152009-06-28 17:22:03 +0000786
787.. _generator-types:
788
789Generator Types
790---------------
791
Georg Brandl9afde1c2007-11-01 20:32:30 +0000792Python's :term:`generator`\s provide a convenient way to implement the iterator
793protocol. If a container object's :meth:`__iter__` method is implemented as a
794generator, it will automatically return an iterator object (technically, a
795generator object) supplying the :meth:`__iter__` and :meth:`__next__` methods.
Benjamin Peterson0289b152009-06-28 17:22:03 +0000796More information about generators can be found in :ref:`the documentation for
797the yield expression <yieldexpr>`.
Georg Brandl116aa622007-08-15 14:28:22 +0000798
799
800.. _typesseq:
801
Nick Coghlan273069c2012-08-20 17:14:07 +1000802Sequence Types --- :class:`list`, :class:`tuple`, :class:`range`
803================================================================
Georg Brandl116aa622007-08-15 14:28:22 +0000804
Nick Coghlan273069c2012-08-20 17:14:07 +1000805There are three basic sequence types: lists, tuples, and range objects.
806Additional sequence types tailored for processing of
807:ref:`binary data <binaryseq>` and :ref:`text strings <textseq>` are
808described in dedicated sections.
Georg Brandle17d5862009-01-18 10:40:25 +0000809
Georg Brandl116aa622007-08-15 14:28:22 +0000810
Nick Coghlan273069c2012-08-20 17:14:07 +1000811.. _typesseq-common:
Georg Brandl116aa622007-08-15 14:28:22 +0000812
Nick Coghlan273069c2012-08-20 17:14:07 +1000813Common Sequence Operations
814--------------------------
Georg Brandl7c676132007-10-23 18:17:00 +0000815
Nick Coghlan273069c2012-08-20 17:14:07 +1000816.. index:: object: sequence
Georg Brandl4b491312007-08-31 09:22:56 +0000817
Nick Coghlan273069c2012-08-20 17:14:07 +1000818The operations in the following table are supported by most sequence types,
819both mutable and immutable. The :class:`collections.abc.Sequence` ABC is
820provided to make it easier to correctly implement these operations on
821custom sequence types.
Georg Brandl116aa622007-08-15 14:28:22 +0000822
823This table lists the sequence operations sorted in ascending priority
824(operations in the same box have the same priority). In the table, *s* and *t*
Nick Coghlan273069c2012-08-20 17:14:07 +1000825are sequences of the same type, *n*, *i*, *j* and *k* are integers and *x* is
826an arbitrary object that meets any type and value restrictions imposed by *s*.
Georg Brandl116aa622007-08-15 14:28:22 +0000827
Nick Coghlan273069c2012-08-20 17:14:07 +1000828The ``in`` and ``not in`` operations have the same priorities as the
829comparison operations. The ``+`` (concatenation) and ``*`` (repetition)
830operations have the same priority as the corresponding numeric operations.
Georg Brandl116aa622007-08-15 14:28:22 +0000831
Nick Coghlan273069c2012-08-20 17:14:07 +1000832+--------------------------+--------------------------------+----------+
833| Operation | Result | Notes |
834+==========================+================================+==========+
835| ``x in s`` | ``True`` if an item of *s* is | \(1) |
836| | equal to *x*, else ``False`` | |
837+--------------------------+--------------------------------+----------+
838| ``x not in s`` | ``False`` if an item of *s* is | \(1) |
839| | equal to *x*, else ``True`` | |
840+--------------------------+--------------------------------+----------+
841| ``s + t`` | the concatenation of *s* and | (6)(7) |
842| | *t* | |
843+--------------------------+--------------------------------+----------+
844| ``s * n, n * s`` | *n* shallow copies of *s* | (2)(7) |
845| | concatenated | |
846+--------------------------+--------------------------------+----------+
847| ``s[i]`` | *i*\ th item of *s*, origin 0 | \(3) |
848+--------------------------+--------------------------------+----------+
849| ``s[i:j]`` | slice of *s* from *i* to *j* | (3)(4) |
850+--------------------------+--------------------------------+----------+
851| ``s[i:j:k]`` | slice of *s* from *i* to *j* | (3)(5) |
852| | with step *k* | |
853+--------------------------+--------------------------------+----------+
854| ``len(s)`` | length of *s* | |
855+--------------------------+--------------------------------+----------+
856| ``min(s)`` | smallest item of *s* | |
857+--------------------------+--------------------------------+----------+
858| ``max(s)`` | largest item of *s* | |
859+--------------------------+--------------------------------+----------+
860| ``s.index(x, [i[, j]])`` | index of the first occurence | \(8) |
861| | of *x* in *s* (at or after | |
862| | index *i* and before index *j*)| |
863+--------------------------+--------------------------------+----------+
864| ``s.count(x)`` | total number of occurences of | |
865| | *x* in *s* | |
866+--------------------------+--------------------------------+----------+
867
868Sequences of the same type also support comparisons. In particular, tuples
869and lists are compared lexicographically by comparing corresponding elements.
870This means that to compare equal, every element must compare equal and the
871two sequences must be of the same type and have the same length. (For full
872details see :ref:`comparisons` in the language reference.)
Georg Brandl116aa622007-08-15 14:28:22 +0000873
874.. index::
875 triple: operations on; sequence; types
876 builtin: len
877 builtin: min
878 builtin: max
879 pair: concatenation; operation
880 pair: repetition; operation
881 pair: subscript; operation
882 pair: slice; operation
Georg Brandl116aa622007-08-15 14:28:22 +0000883 operator: in
884 operator: not in
885
886Notes:
887
888(1)
Nick Coghlan273069c2012-08-20 17:14:07 +1000889 While the ``in`` and ``not in`` operations are used only for simple
890 containment testing in the general case, some specialised sequences
891 (such as :class:`str`, :class:`bytes` and :class:`bytearray`) also use
892 them for subsequence testing::
893
894 >>> "gg" in "eggs"
895 True
Georg Brandl116aa622007-08-15 14:28:22 +0000896
897(2)
898 Values of *n* less than ``0`` are treated as ``0`` (which yields an empty
899 sequence of the same type as *s*). Note also that the copies are shallow;
900 nested structures are not copied. This often haunts new Python programmers;
Nick Coghlan273069c2012-08-20 17:14:07 +1000901 consider::
Georg Brandl116aa622007-08-15 14:28:22 +0000902
903 >>> lists = [[]] * 3
904 >>> lists
905 [[], [], []]
906 >>> lists[0].append(3)
907 >>> lists
908 [[3], [3], [3]]
909
910 What has happened is that ``[[]]`` is a one-element list containing an empty
Christian Heimesfe337bf2008-03-23 21:54:12 +0000911 list, so all three elements of ``[[]] * 3`` are (pointers to) this single empty
912 list. Modifying any of the elements of ``lists`` modifies this single list.
Nick Coghlan273069c2012-08-20 17:14:07 +1000913 You can create a list of different lists this way::
Georg Brandl116aa622007-08-15 14:28:22 +0000914
915 >>> lists = [[] for i in range(3)]
916 >>> lists[0].append(3)
917 >>> lists[1].append(5)
918 >>> lists[2].append(7)
919 >>> lists
920 [[3], [5], [7]]
921
922(3)
923 If *i* or *j* is negative, the index is relative to the end of the string:
Georg Brandl7c676132007-10-23 18:17:00 +0000924 ``len(s) + i`` or ``len(s) + j`` is substituted. But note that ``-0`` is
925 still ``0``.
Georg Brandl116aa622007-08-15 14:28:22 +0000926
927(4)
928 The slice of *s* from *i* to *j* is defined as the sequence of items with index
929 *k* such that ``i <= k < j``. If *i* or *j* is greater than ``len(s)``, use
930 ``len(s)``. If *i* is omitted or ``None``, use ``0``. If *j* is omitted or
931 ``None``, use ``len(s)``. If *i* is greater than or equal to *j*, the slice is
932 empty.
933
934(5)
935 The slice of *s* from *i* to *j* with step *k* is defined as the sequence of
Christian Heimes2c181612007-12-17 20:04:13 +0000936 items with index ``x = i + n*k`` such that ``0 <= n < (j-i)/k``. In other words,
Georg Brandl116aa622007-08-15 14:28:22 +0000937 the indices are ``i``, ``i+k``, ``i+2*k``, ``i+3*k`` and so on, stopping when
938 *j* is reached (but never including *j*). If *i* or *j* is greater than
939 ``len(s)``, use ``len(s)``. If *i* or *j* are omitted or ``None``, they become
940 "end" values (which end depends on the sign of *k*). Note, *k* cannot be zero.
941 If *k* is ``None``, it is treated like ``1``.
942
943(6)
Nick Coghlan273069c2012-08-20 17:14:07 +1000944 Concatenating immutable sequences always results in a new object. This
945 means that building up a sequence by repeated concatenation will have a
946 quadratic runtime cost in the total sequence length. To get a linear
947 runtime cost, you must switch to one of the alternatives below:
Georg Brandl495f7b52009-10-27 15:28:25 +0000948
Antoine Pitroufd9ebd42011-11-25 16:33:53 +0100949 * if concatenating :class:`str` objects, you can build a list and use
Nick Coghlan273069c2012-08-20 17:14:07 +1000950 :meth:`str.join` at the end or else write to a :class:`io.StringIO`
951 instance and retrieve its value when complete;
Antoine Pitroufd9ebd42011-11-25 16:33:53 +0100952
953 * if concatenating :class:`bytes` objects, you can similarly use
Nick Coghlan273069c2012-08-20 17:14:07 +1000954 :meth:`bytes.join` or :class:`io.BytesIO`, or you can do in-place
955 concatenation with a :class:`bytearray` object. :class:`bytearray`
956 objects are mutable and have an efficient overallocation mechanism.
Georg Brandl116aa622007-08-15 14:28:22 +0000957
Nick Coghlan273069c2012-08-20 17:14:07 +1000958 * if concatenating :class:`tuple` objects, extend a :class:`list` instead.
959
960 * for other types, investigate the relevant class documentation
961
962
963(7)
964 Some sequence types (such as :class:`range`) only support item sequences
965 that follow specific patterns, and hence don't support sequence
966 concatenation or repetition.
967
968(8)
969 ``index`` raises :exc:`ValueError` when *x* is not found in *s*.
970 When supported, the additional arguments to the index method allow
971 efficient searching of subsections of the sequence. Passing the extra
972 arguments is roughly equivalent to using ``s[i:j].index(x)``, only
973 without copying any data and with the returned index being relative to
974 the start of the sequence rather than the start of the slice.
975
976
977.. _typesseq-immutable:
978
979Immutable Sequence Types
980------------------------
981
982.. index::
983 triple: immutable; sequence; types
984 object: tuple
985
986The only operation that immutable sequence types generally implement that is
987not also implemented by mutable sequence types is support for the :func:`hash`
988built-in.
989
990This support allows immutable sequences, such as :class:`tuple` instances, to
991be used as :class:`dict` keys and stored in :class:`set` and :class:`frozenset`
992instances.
993
994Attempting to hash an immutable sequence that contains unhashable values will
995result in :exc:`TypeError`.
996
997
998.. _typesseq-mutable:
999
1000Mutable Sequence Types
1001----------------------
1002
1003.. index::
1004 triple: mutable; sequence; types
1005 object: list
1006 object: bytearray
1007
1008The operations in the following table are defined on mutable sequence types.
1009The :class:`collections.abc.MutableSequence` ABC is provided to make it
1010easier to correctly implement these operations on custom sequence types.
1011
1012In the table *s* is an instance of a mutable sequence type, *t* is any
1013iterable object and *x* is an arbitrary object that meets any type
1014and value restrictions imposed by *s* (for example, :class:`bytearray` only
1015accepts integers that meet the value restriction ``0 <= x <= 255``).
1016
1017
1018.. index::
1019 triple: operations on; sequence; types
1020 triple: operations on; list; type
1021 pair: subscript; assignment
1022 pair: slice; assignment
1023 statement: del
1024 single: append() (sequence method)
1025 single: extend() (sequence method)
1026 single: count() (sequence method)
1027 single: index() (sequence method)
1028 single: insert() (sequence method)
1029 single: pop() (sequence method)
1030 single: remove() (sequence method)
1031 single: reverse() (sequence method)
1032
1033+------------------------------+--------------------------------+---------------------+
1034| Operation | Result | Notes |
1035+==============================+================================+=====================+
1036| ``s[i] = x`` | item *i* of *s* is replaced by | |
1037| | *x* | |
1038+------------------------------+--------------------------------+---------------------+
1039| ``s[i:j] = t`` | slice of *s* from *i* to *j* | |
1040| | is replaced by the contents of | |
1041| | the iterable *t* | |
1042+------------------------------+--------------------------------+---------------------+
1043| ``del s[i:j]`` | same as ``s[i:j] = []`` | |
1044+------------------------------+--------------------------------+---------------------+
1045| ``s[i:j:k] = t`` | the elements of ``s[i:j:k]`` | \(1) |
1046| | are replaced by those of *t* | |
1047+------------------------------+--------------------------------+---------------------+
1048| ``del s[i:j:k]`` | removes the elements of | |
1049| | ``s[i:j:k]`` from the list | |
1050+------------------------------+--------------------------------+---------------------+
1051| ``s.append(x)`` | same as ``s[len(s):len(s)] = | |
1052| | [x]`` | |
1053+------------------------------+--------------------------------+---------------------+
1054| ``s.clear()`` | remove all items from ``s`` | \(5) |
1055| | (same as ``del s[:]``) | |
1056+------------------------------+--------------------------------+---------------------+
1057| ``s.copy()`` | return a shallow copy of ``s`` | \(5) |
1058| | (same as ``s[:]``) | |
1059+------------------------------+--------------------------------+---------------------+
1060| ``s.extend(t)`` | same as ``s[len(s):len(s)] = | |
1061| | t`` | |
1062+------------------------------+--------------------------------+---------------------+
1063| ``s.insert(i, x)`` | same as ``s[i:i] = [x]`` | |
1064+------------------------------+--------------------------------+---------------------+
1065| ``s.pop([i])`` | same as ``x = s[i]; del s[i]; | \(2) |
1066| | return x`` | |
1067+------------------------------+--------------------------------+---------------------+
1068| ``s.remove(x)`` | same as ``del s[s.index(x)]`` | \(3) |
1069+------------------------------+--------------------------------+---------------------+
1070| ``s.reverse()`` | reverses the items of *s* in | \(4) |
1071| | place | |
1072+------------------------------+--------------------------------+---------------------+
1073
1074
1075Notes:
1076
1077(1)
1078 *t* must have the same length as the slice it is replacing.
1079
1080(2)
1081 The optional argument *i* defaults to ``-1``, so that by default the last
1082 item is removed and returned.
1083
1084(3)
1085 ``remove`` raises :exc:`ValueError` when *x* is not found in *s*.
1086
1087(4)
1088 The :meth:`reverse` method modifies the sequence in place for economy of
1089 space when reversing a large sequence. To remind users that it operates by
1090 side effect, it does not return the reversed sequence.
1091
1092(5)
1093 :meth:`clear` and :meth:`!copy` are included for consistency with the
1094 interfaces of mutable containers that don't support slicing operations
1095 (such as :class:`dict` and :class:`set`)
1096
1097 .. versionadded:: 3.3
1098 :meth:`clear` and :meth:`!copy` methods.
1099
1100
1101.. _typesseq-list:
1102
1103Lists
1104-----
1105
1106.. index:: object: list
1107
1108Lists are mutable sequences, typically used to store collections of
1109homogeneous items (where the precise degree of similarity will vary by
1110application).
1111
1112Lists may be constructed in several ways:
1113
1114* Using a pair of square brackets to denote the empty list: ``[]``
1115* Using square brackets, separating items with commas: ``[a]``, ``[a, b, c]``
1116* Using a list comprehension: ``[x for x in iterable]``
1117* Using the :func:`list` built-in: ``list()`` or ``list(iterable)``
1118
1119Many other operations also produce lists, including the :func:`sorted` built-in.
1120
1121Lists implement all of the :ref:`common <typesseq-common>` and
1122:ref:`mutable <typesseq-mutable>` sequence operations. Lists also provide the
1123following additional method:
1124
1125.. method:: list.sort(*, key=None, reverse=None)
1126
1127 This method sorts the list in place, using only ``<`` comparisons
1128 between items. Exceptions are not suppressed - if any comparison operations
1129 fail, the entire sort operation will fail (and the list will likely be left
1130 in a partially modified state).
1131
1132 *key* specifies a function of one argument that is used to extract a
1133 comparison key from each list element (for example, ``key=str.lower``).
1134 The key corresponding to each item in the list is calculated once and
1135 then used for the entire sorting process. The default value of ``None``
1136 means that list items are sorted directly without calculating a separate
1137 key value.
1138
1139 The :func:`functools.cmp_to_key` utility is available to convert a 2.x
1140 style *cmp* function to a *key* function.
1141
1142 *reverse* is a boolean value. If set to ``True``, then the list elements
1143 are sorted as if each comparison were reversed.
1144
1145 This method modifies the sequence in place for economy of space when
1146 sorting a large sequence. To remind users that it operates by side
1147 effect, it does not return the sorted sequence (use :func:`sorted` to
1148 explicitly request a new sorted list instance).
1149
1150 The :meth:`sort` method is guaranteed to be stable. A sort is stable if it
1151 guarantees not to change the relative order of elements that compare equal
1152 --- this is helpful for sorting in multiple passes (for example, sort by
1153 department, then by salary grade).
1154
1155 .. impl-detail::
1156
1157 While a list is being sorted, the effect of attempting to mutate, or even
1158 inspect, the list is undefined. The C implementation of Python makes the
1159 list appear empty for the duration, and raises :exc:`ValueError` if it can
1160 detect that the list has been mutated during a sort.
1161
1162
1163.. _typesseq-tuple:
1164
1165Tuples
1166------
1167
1168.. index:: object: tuple
1169
1170Tuples are immutable sequences, typically used to store collections of
1171heterogeneous data (such as the 2-tuples produced by the :func:`enumerate`
1172built-in). Tuples are also used for cases where an immutable sequence of
1173homogeneous data is needed (such as allowing storage in a :class:`set` or
1174:class:`dict` instance).
1175
1176Tuples may be constructed in a number of ways:
1177
1178* Using a pair of parentheses to denote the empty tuple: ``()``
1179* Using a trailing comma for a singleton tuple: ``a,`` or ``(a,)``
1180* Separating items with commas: ``a, b, c`` or ``(a, b, c)``
1181* Using the :func:`tuple` built-in: ``tuple()`` or ``tuple(iterable)``
1182
1183Note that the parentheses are optional (except in the empty tuple case, or
1184when needed to avoid syntactic ambiguity). It is actually the comma which
1185makes a tuple, not the parentheses.
1186
1187Tuples implement all of the :ref:`common <typesseq-common>` sequence
1188operations.
1189
1190For heterogeneous collections of data, :func:`collections.namedtuple` may
1191be more appropriate than a simple tuple object.
1192
1193
1194.. _typesseq-range:
1195
1196Ranges
1197------
1198
1199.. index:: object: range
1200
1201The :class:`range` type represents an immutable sequence of numbers and is
1202commonly used for looping a specific number of times. Instances are created
1203using the :func:`range` built-in.
1204
1205For positive indices with results between the defined ``start`` and ``stop``
1206values, integers within the range are determined by the formula:
1207``r[i] = start + step*i``
1208
1209For negative indices and slicing operations, a range instance determines the
1210appropriate result for the corresponding tuple and returns either the
1211appropriate integer (for negative indices) or an appropriate range object
1212(for slicing operations) .
1213
1214The advantage of the :class:`range` type over a regular :class:`list` or
1215:class:`tuple` is that a :class:`range` object will always take the same
1216(small) amount of memory, no matter the size of the range it represents (as it
1217only stores the ``start``, ``stop`` and ``step`` values, calculating individual
1218items and subranges as needed).
1219
1220Ranges implement all of the :ref:`common <typesseq-common>` sequence operations
1221except concatenation and repetition (due to the fact that range objects can
1222only represent sequences that follow a strict pattern and repetition and
1223concatenation will usually violate that pattern).
1224
1225
1226.. _textseq:
1227
1228Text Sequence Type --- :class:`str`
1229===================================
1230
1231.. index::
1232 object: string
1233 object: bytes
1234 object: bytearray
1235 object: io.StringIO
1236
1237
1238Textual data in Python is handled with :class:`str` objects, which are
1239immutable sequences of Unicode code points. String literals are
1240written in a variety of ways:
1241
1242* Single quotes: ``'allows embedded "double" quotes'``
1243* Double quotes: ``"allows embedded 'single' quotes"``.
1244* Triple quoted: ``'''Three single quotes'''``, ``"""Three double quotes"""``
1245
1246Triple quoted strings may span multiple lines - all associated whitespace will
1247be included in the string literal.
1248
1249String literals that are part of a single expression and have only whitespace
1250between them will be implicitly converted to a single string literal.
1251
1252See :ref:`strings` for more about the various forms of string literal,
1253including supported escape sequences, and the ``r`` ("raw") prefix that
1254disables most escape sequence processing.
1255
1256Strings may also be created from other objects with the :func:`str` built-in.
1257
1258Since there is no separate "character" type, indexing a string produces
1259strings of length 1. That is, for a non-empty string *s*, ``s[0] == s[0:1]``.
1260
1261There is also no mutable string type, but :meth:`str.join` or
1262:class:`io.StringIO` can be used to efficiently construct strings from
1263multiple fragments.
1264
1265.. versionchanged:: 3.3
1266 For backwards compatibility with the Python 2 series, the ``u`` prefix is
1267 once again permitted on string literals. It has no effect on the meaning
1268 of string literals and cannot be combined with the ``r`` prefix.
Georg Brandl116aa622007-08-15 14:28:22 +00001269
1270.. _string-methods:
1271
1272String Methods
1273--------------
1274
Nick Coghlan273069c2012-08-20 17:14:07 +10001275.. index::
1276 pair: string; methods
1277 module: re
Georg Brandl116aa622007-08-15 14:28:22 +00001278
Nick Coghlan273069c2012-08-20 17:14:07 +10001279Strings implement all of the :ref:`common <typesseq-common>` sequence
1280operations, along with the additional methods described below.
Thomas Wouters8ce81f72007-09-20 18:22:40 +00001281
Nick Coghlan273069c2012-08-20 17:14:07 +10001282Strings also support two styles of string formatting, one providing a large
1283degree of flexibility and customization (see :meth:`str.format`,
1284:ref:`formatstrings` and :ref:`string-formatting`) and the other based on C
1285``printf`` style formatting that handles a narrower range of types and is
1286slightly harder to use correctly, but is often faster for the cases it can
1287handle (:ref:`old-string-formatting`).
1288
1289The :ref:`textservices` section of the standard library covers a number of
1290other modules that provide various text related utilities (including regular
1291expression support in the :mod:`re` module).
Georg Brandl116aa622007-08-15 14:28:22 +00001292
1293.. method:: str.capitalize()
1294
Senthil Kumaranfa897982010-07-05 11:41:42 +00001295 Return a copy of the string with its first character capitalized and the
Senthil Kumaran37c63a32010-07-06 02:08:36 +00001296 rest lowercased.
Georg Brandl116aa622007-08-15 14:28:22 +00001297
Georg Brandl116aa622007-08-15 14:28:22 +00001298
Benjamin Petersond5890c82012-01-14 13:23:30 -05001299.. method:: str.casefold()
1300
1301 Return a casefolded copy of the string. Casefolded strings may be used for
Benjamin Peterson94303542012-01-18 23:09:32 -05001302 caseless matching.
1303
1304 Casefolding is similar to lowercasing but more aggressive because it is
1305 intended to remove all case distinctions in a string. For example, the German
1306 lowercase letter ``'ß'`` is equivalent to ``"ss"``. Since it is already
1307 lowercase, :meth:`lower` would do nothing to ``'ß'``; :meth:`casefold`
1308 converts it to ``"ss"``.
1309
1310 The casefolding algorithm is described in section 3.13 of the Unicode
1311 Standard.
Benjamin Petersond5890c82012-01-14 13:23:30 -05001312
1313 .. versionadded:: 3.3
1314
1315
Georg Brandl116aa622007-08-15 14:28:22 +00001316.. method:: str.center(width[, fillchar])
1317
1318 Return centered in a string of length *width*. Padding is done using the
1319 specified *fillchar* (default is a space).
1320
Georg Brandl116aa622007-08-15 14:28:22 +00001321
1322.. method:: str.count(sub[, start[, end]])
1323
Benjamin Petersonad3d5c22009-02-26 03:38:59 +00001324 Return the number of non-overlapping occurrences of substring *sub* in the
1325 range [*start*, *end*]. Optional arguments *start* and *end* are
1326 interpreted as in slice notation.
Georg Brandl116aa622007-08-15 14:28:22 +00001327
1328
Victor Stinnere14e2122010-11-07 18:41:46 +00001329.. method:: str.encode(encoding="utf-8", errors="strict")
Georg Brandl116aa622007-08-15 14:28:22 +00001330
Victor Stinnere14e2122010-11-07 18:41:46 +00001331 Return an encoded version of the string as a bytes object. Default encoding
1332 is ``'utf-8'``. *errors* may be given to set a different error handling scheme.
1333 The default for *errors* is ``'strict'``, meaning that encoding errors raise
1334 a :exc:`UnicodeError`. Other possible
Georg Brandl4f5f98d2009-05-04 21:01:20 +00001335 values are ``'ignore'``, ``'replace'``, ``'xmlcharrefreplace'``,
1336 ``'backslashreplace'`` and any other name registered via
1337 :func:`codecs.register_error`, see section :ref:`codec-base-classes`. For a
1338 list of possible encodings, see section :ref:`standard-encodings`.
Georg Brandl116aa622007-08-15 14:28:22 +00001339
Benjamin Peterson308d6372009-09-18 21:42:35 +00001340 .. versionchanged:: 3.1
Georg Brandl67b21b72010-08-17 15:07:14 +00001341 Support for keyword arguments added.
1342
Georg Brandl116aa622007-08-15 14:28:22 +00001343
1344.. method:: str.endswith(suffix[, start[, end]])
1345
1346 Return ``True`` if the string ends with the specified *suffix*, otherwise return
1347 ``False``. *suffix* can also be a tuple of suffixes to look for. With optional
1348 *start*, test beginning at that position. With optional *end*, stop comparing
1349 at that position.
1350
Georg Brandl116aa622007-08-15 14:28:22 +00001351
1352.. method:: str.expandtabs([tabsize])
1353
Eli Benderskyc2c89602011-11-11 10:40:14 +02001354 Return a copy of the string where all tab characters are replaced by zero or
Georg Brandl9afde1c2007-11-01 20:32:30 +00001355 more spaces, depending on the current column and the given tab size. The
1356 column number is reset to zero after each newline occurring in the string.
1357 If *tabsize* is not given, a tab size of ``8`` characters is assumed. This
1358 doesn't understand other non-printing characters or escape sequences.
Georg Brandl116aa622007-08-15 14:28:22 +00001359
1360
1361.. method:: str.find(sub[, start[, end]])
1362
Benjamin Petersond99cd812010-04-27 22:58:50 +00001363 Return the lowest index in the string where substring *sub* is found, such
1364 that *sub* is contained in the slice ``s[start:end]``. Optional arguments
1365 *start* and *end* are interpreted as in slice notation. Return ``-1`` if
1366 *sub* is not found.
Georg Brandl116aa622007-08-15 14:28:22 +00001367
Ezio Melotti0ed8c682011-05-09 03:54:30 +03001368 .. note::
1369
1370 The :meth:`~str.find` method should be used only if you need to know the
1371 position of *sub*. To check if *sub* is a substring or not, use the
1372 :keyword:`in` operator::
1373
1374 >>> 'Py' in 'Python'
1375 True
1376
Georg Brandl116aa622007-08-15 14:28:22 +00001377
Benjamin Petersonad3d5c22009-02-26 03:38:59 +00001378.. method:: str.format(*args, **kwargs)
Georg Brandl4b491312007-08-31 09:22:56 +00001379
Georg Brandl1f70cdf2010-03-21 09:04:24 +00001380 Perform a string formatting operation. The string on which this method is
1381 called can contain literal text or replacement fields delimited by braces
1382 ``{}``. Each replacement field contains either the numeric index of a
1383 positional argument, or the name of a keyword argument. Returns a copy of
1384 the string where each replacement field is replaced with the string value of
1385 the corresponding argument.
Georg Brandl4b491312007-08-31 09:22:56 +00001386
1387 >>> "The sum of 1 + 2 is {0}".format(1+2)
1388 'The sum of 1 + 2 is 3'
1389
1390 See :ref:`formatstrings` for a description of the various formatting options
1391 that can be specified in format strings.
1392
Georg Brandl4b491312007-08-31 09:22:56 +00001393
Eric Smith27bbca62010-11-04 17:06:58 +00001394.. method:: str.format_map(mapping)
1395
Éric Araujo2642ad02010-11-06 04:59:27 +00001396 Similar to ``str.format(**mapping)``, except that ``mapping`` is
Eric Smith27bbca62010-11-04 17:06:58 +00001397 used directly and not copied to a :class:`dict` . This is useful
Eric Smith5ad85f82010-11-06 13:22:13 +00001398 if for example ``mapping`` is a dict subclass:
Eric Smith27bbca62010-11-04 17:06:58 +00001399
Eric Smith5ad85f82010-11-06 13:22:13 +00001400 >>> class Default(dict):
1401 ... def __missing__(self, key):
1402 ... return key
1403 ...
1404 >>> '{name} was born in {country}'.format_map(Default(name='Guido'))
1405 'Guido was born in country'
1406
1407 .. versionadded:: 3.2
1408
Eric Smith27bbca62010-11-04 17:06:58 +00001409
Georg Brandl116aa622007-08-15 14:28:22 +00001410.. method:: str.index(sub[, start[, end]])
1411
1412 Like :meth:`find`, but raise :exc:`ValueError` when the substring is not found.
1413
1414
1415.. method:: str.isalnum()
1416
1417 Return true if all characters in the string are alphanumeric and there is at
Alexander Belopolsky0d267982010-12-23 02:58:25 +00001418 least one character, false otherwise. A character ``c`` is alphanumeric if one
1419 of the following returns ``True``: ``c.isalpha()``, ``c.isdecimal()``,
1420 ``c.isdigit()``, or ``c.isnumeric()``.
Georg Brandl116aa622007-08-15 14:28:22 +00001421
Georg Brandl116aa622007-08-15 14:28:22 +00001422
1423.. method:: str.isalpha()
1424
1425 Return true if all characters in the string are alphabetic and there is at least
Alexander Belopolsky0d267982010-12-23 02:58:25 +00001426 one character, false otherwise. Alphabetic characters are those characters defined
1427 in the Unicode character database as "Letter", i.e., those with general category
1428 property being one of "Lm", "Lt", "Lu", "Ll", or "Lo". Note that this is different
1429 from the "Alphabetic" property defined in the Unicode Standard.
Georg Brandl116aa622007-08-15 14:28:22 +00001430
Georg Brandl116aa622007-08-15 14:28:22 +00001431
Mark Summerfieldbbfd71d2008-07-01 15:50:04 +00001432.. method:: str.isdecimal()
1433
1434 Return true if all characters in the string are decimal
1435 characters and there is at least one character, false
Alexander Belopolsky0d267982010-12-23 02:58:25 +00001436 otherwise. Decimal characters are those from general category "Nd". This category
1437 includes digit characters, and all characters
Ezio Melottie130a522011-10-19 10:58:56 +03001438 that can be used to form decimal-radix numbers, e.g. U+0660,
Mark Summerfieldbbfd71d2008-07-01 15:50:04 +00001439 ARABIC-INDIC DIGIT ZERO.
Georg Brandl48310cd2009-01-03 21:18:54 +00001440
Mark Summerfieldbbfd71d2008-07-01 15:50:04 +00001441
Georg Brandl116aa622007-08-15 14:28:22 +00001442.. method:: str.isdigit()
1443
1444 Return true if all characters in the string are digits and there is at least one
Alexander Belopolsky0d267982010-12-23 02:58:25 +00001445 character, false otherwise. Digits include decimal characters and digits that need
1446 special handling, such as the compatibility superscript digits. Formally, a digit
1447 is a character that has the property value Numeric_Type=Digit or Numeric_Type=Decimal.
Georg Brandl116aa622007-08-15 14:28:22 +00001448
Georg Brandl116aa622007-08-15 14:28:22 +00001449
1450.. method:: str.isidentifier()
1451
1452 Return true if the string is a valid identifier according to the language
Georg Brandl4b491312007-08-31 09:22:56 +00001453 definition, section :ref:`identifiers`.
Georg Brandl116aa622007-08-15 14:28:22 +00001454
1455
1456.. method:: str.islower()
1457
Ezio Melotti0656a562011-08-15 14:27:19 +03001458 Return true if all cased characters [4]_ in the string are lowercase and
1459 there is at least one cased character, false otherwise.
Georg Brandl116aa622007-08-15 14:28:22 +00001460
Georg Brandl116aa622007-08-15 14:28:22 +00001461
Mark Summerfieldbbfd71d2008-07-01 15:50:04 +00001462.. method:: str.isnumeric()
1463
1464 Return true if all characters in the string are numeric
1465 characters, and there is at least one character, false
1466 otherwise. Numeric characters include digit characters, and all characters
1467 that have the Unicode numeric value property, e.g. U+2155,
Alexander Belopolsky0d267982010-12-23 02:58:25 +00001468 VULGAR FRACTION ONE FIFTH. Formally, numeric characters are those with the property
1469 value Numeric_Type=Digit, Numeric_Type=Decimal or Numeric_Type=Numeric.
Mark Summerfieldbbfd71d2008-07-01 15:50:04 +00001470
Georg Brandl48310cd2009-01-03 21:18:54 +00001471
Georg Brandl559e5d72008-06-11 18:37:52 +00001472.. method:: str.isprintable()
1473
1474 Return true if all characters in the string are printable or the string is
1475 empty, false otherwise. Nonprintable characters are those characters defined
1476 in the Unicode character database as "Other" or "Separator", excepting the
1477 ASCII space (0x20) which is considered printable. (Note that printable
1478 characters in this context are those which should not be escaped when
1479 :func:`repr` is invoked on a string. It has no bearing on the handling of
1480 strings written to :data:`sys.stdout` or :data:`sys.stderr`.)
1481
1482
Georg Brandl116aa622007-08-15 14:28:22 +00001483.. method:: str.isspace()
1484
1485 Return true if there are only whitespace characters in the string and there is
Alexander Belopolsky0d267982010-12-23 02:58:25 +00001486 at least one character, false otherwise. Whitespace characters are those
1487 characters defined in the Unicode character database as "Other" or "Separator"
1488 and those with bidirectional property being one of "WS", "B", or "S".
Georg Brandl116aa622007-08-15 14:28:22 +00001489
1490.. method:: str.istitle()
1491
1492 Return true if the string is a titlecased string and there is at least one
1493 character, for example uppercase characters may only follow uncased characters
1494 and lowercase characters only cased ones. Return false otherwise.
1495
Georg Brandl116aa622007-08-15 14:28:22 +00001496
1497.. method:: str.isupper()
1498
Ezio Melotti0656a562011-08-15 14:27:19 +03001499 Return true if all cased characters [4]_ in the string are uppercase and
1500 there is at least one cased character, false otherwise.
Georg Brandl116aa622007-08-15 14:28:22 +00001501
Georg Brandl116aa622007-08-15 14:28:22 +00001502
Georg Brandl495f7b52009-10-27 15:28:25 +00001503.. method:: str.join(iterable)
Georg Brandl116aa622007-08-15 14:28:22 +00001504
Georg Brandl495f7b52009-10-27 15:28:25 +00001505 Return a string which is the concatenation of the strings in the
1506 :term:`iterable` *iterable*. A :exc:`TypeError` will be raised if there are
Terry Jan Reedyf4ec3c52012-01-11 03:29:42 -05001507 any non-string values in *iterable*, including :class:`bytes` objects. The
Georg Brandl495f7b52009-10-27 15:28:25 +00001508 separator between elements is the string providing this method.
Georg Brandl116aa622007-08-15 14:28:22 +00001509
1510
1511.. method:: str.ljust(width[, fillchar])
1512
1513 Return the string left justified in a string of length *width*. Padding is done
1514 using the specified *fillchar* (default is a space). The original string is
Terry Jan Reedyf4ec3c52012-01-11 03:29:42 -05001515 returned if *width* is less than or equal to ``len(s)``.
Georg Brandl116aa622007-08-15 14:28:22 +00001516
Georg Brandl116aa622007-08-15 14:28:22 +00001517
1518.. method:: str.lower()
1519
Ezio Melotti0656a562011-08-15 14:27:19 +03001520 Return a copy of the string with all the cased characters [4]_ converted to
1521 lowercase.
Georg Brandl116aa622007-08-15 14:28:22 +00001522
Benjamin Peterson94303542012-01-18 23:09:32 -05001523 The lowercasing algorithm used is described in section 3.13 of the Unicode
1524 Standard.
1525
Georg Brandl116aa622007-08-15 14:28:22 +00001526
1527.. method:: str.lstrip([chars])
1528
1529 Return a copy of the string with leading characters removed. The *chars*
1530 argument is a string specifying the set of characters to be removed. If omitted
1531 or ``None``, the *chars* argument defaults to removing whitespace. The *chars*
Christian Heimesfe337bf2008-03-23 21:54:12 +00001532 argument is not a prefix; rather, all combinations of its values are stripped:
Georg Brandl116aa622007-08-15 14:28:22 +00001533
1534 >>> ' spacious '.lstrip()
1535 'spacious '
1536 >>> 'www.example.com'.lstrip('cmowz.')
1537 'example.com'
1538
Georg Brandl116aa622007-08-15 14:28:22 +00001539
Georg Brandlabc38772009-04-12 15:51:51 +00001540.. staticmethod:: str.maketrans(x[, y[, z]])
Georg Brandlceee0772007-11-27 23:48:05 +00001541
1542 This static method returns a translation table usable for :meth:`str.translate`.
1543
1544 If there is only one argument, it must be a dictionary mapping Unicode
1545 ordinals (integers) or characters (strings of length 1) to Unicode ordinals,
1546 strings (of arbitrary lengths) or None. Character keys will then be
1547 converted to ordinals.
1548
1549 If there are two arguments, they must be strings of equal length, and in the
1550 resulting dictionary, each character in x will be mapped to the character at
1551 the same position in y. If there is a third argument, it must be a string,
1552 whose characters will be mapped to None in the result.
1553
1554
Georg Brandl116aa622007-08-15 14:28:22 +00001555.. method:: str.partition(sep)
1556
1557 Split the string at the first occurrence of *sep*, and return a 3-tuple
1558 containing the part before the separator, the separator itself, and the part
1559 after the separator. If the separator is not found, return a 3-tuple containing
1560 the string itself, followed by two empty strings.
1561
Georg Brandl116aa622007-08-15 14:28:22 +00001562
1563.. method:: str.replace(old, new[, count])
1564
1565 Return a copy of the string with all occurrences of substring *old* replaced by
1566 *new*. If the optional argument *count* is given, only the first *count*
1567 occurrences are replaced.
1568
1569
Georg Brandl226878c2007-08-31 10:15:37 +00001570.. method:: str.rfind(sub[, start[, end]])
Georg Brandl116aa622007-08-15 14:28:22 +00001571
Benjamin Petersond99cd812010-04-27 22:58:50 +00001572 Return the highest index in the string where substring *sub* is found, such
1573 that *sub* is contained within ``s[start:end]``. Optional arguments *start*
1574 and *end* are interpreted as in slice notation. Return ``-1`` on failure.
Georg Brandl116aa622007-08-15 14:28:22 +00001575
1576
1577.. method:: str.rindex(sub[, start[, end]])
1578
1579 Like :meth:`rfind` but raises :exc:`ValueError` when the substring *sub* is not
1580 found.
1581
1582
1583.. method:: str.rjust(width[, fillchar])
1584
1585 Return the string right justified in a string of length *width*. Padding is done
1586 using the specified *fillchar* (default is a space). The original string is
Terry Jan Reedyf4ec3c52012-01-11 03:29:42 -05001587 returned if *width* is less than or equal to ``len(s)``.
Georg Brandl116aa622007-08-15 14:28:22 +00001588
Georg Brandl116aa622007-08-15 14:28:22 +00001589
1590.. method:: str.rpartition(sep)
1591
1592 Split the string at the last occurrence of *sep*, and return a 3-tuple
1593 containing the part before the separator, the separator itself, and the part
1594 after the separator. If the separator is not found, return a 3-tuple containing
1595 two empty strings, followed by the string itself.
1596
Georg Brandl116aa622007-08-15 14:28:22 +00001597
Ezio Melotticda6b6d2012-02-26 09:39:55 +02001598.. method:: str.rsplit(sep=None, maxsplit=-1)
Georg Brandl116aa622007-08-15 14:28:22 +00001599
1600 Return a list of the words in the string, using *sep* as the delimiter string.
1601 If *maxsplit* is given, at most *maxsplit* splits are done, the *rightmost*
1602 ones. If *sep* is not specified or ``None``, any whitespace string is a
1603 separator. Except for splitting from the right, :meth:`rsplit` behaves like
1604 :meth:`split` which is described in detail below.
1605
Georg Brandl116aa622007-08-15 14:28:22 +00001606
1607.. method:: str.rstrip([chars])
1608
1609 Return a copy of the string with trailing characters removed. The *chars*
1610 argument is a string specifying the set of characters to be removed. If omitted
1611 or ``None``, the *chars* argument defaults to removing whitespace. The *chars*
Christian Heimesfe337bf2008-03-23 21:54:12 +00001612 argument is not a suffix; rather, all combinations of its values are stripped:
Georg Brandl116aa622007-08-15 14:28:22 +00001613
1614 >>> ' spacious '.rstrip()
1615 ' spacious'
1616 >>> 'mississippi'.rstrip('ipz')
1617 'mississ'
1618
Georg Brandl116aa622007-08-15 14:28:22 +00001619
Ezio Melotticda6b6d2012-02-26 09:39:55 +02001620.. method:: str.split(sep=None, maxsplit=-1)
Georg Brandl116aa622007-08-15 14:28:22 +00001621
Georg Brandl226878c2007-08-31 10:15:37 +00001622 Return a list of the words in the string, using *sep* as the delimiter
1623 string. If *maxsplit* is given, at most *maxsplit* splits are done (thus,
1624 the list will have at most ``maxsplit+1`` elements). If *maxsplit* is not
Ezio Melottibf3165b2012-05-10 15:30:42 +03001625 specified or ``-1``, then there is no limit on the number of splits
1626 (all possible splits are made).
Georg Brandl9afde1c2007-11-01 20:32:30 +00001627
Guido van Rossum2cc30da2007-11-02 23:46:40 +00001628 If *sep* is given, consecutive delimiters are not grouped together and are
Georg Brandl226878c2007-08-31 10:15:37 +00001629 deemed to delimit empty strings (for example, ``'1,,2'.split(',')`` returns
1630 ``['1', '', '2']``). The *sep* argument may consist of multiple characters
Georg Brandl9afde1c2007-11-01 20:32:30 +00001631 (for example, ``'1<>2<>3'.split('<>')`` returns ``['1', '2', '3']``).
Georg Brandl226878c2007-08-31 10:15:37 +00001632 Splitting an empty string with a specified separator returns ``['']``.
Georg Brandl116aa622007-08-15 14:28:22 +00001633
1634 If *sep* is not specified or is ``None``, a different splitting algorithm is
Georg Brandl9afde1c2007-11-01 20:32:30 +00001635 applied: runs of consecutive whitespace are regarded as a single separator,
1636 and the result will contain no empty strings at the start or end if the
1637 string has leading or trailing whitespace. Consequently, splitting an empty
1638 string or a string consisting of just whitespace with a ``None`` separator
1639 returns ``[]``.
1640
1641 For example, ``' 1 2 3 '.split()`` returns ``['1', '2', '3']``, and
1642 ``' 1 2 3 '.split(None, 1)`` returns ``['1', '2 3 ']``.
Georg Brandl116aa622007-08-15 14:28:22 +00001643
1644
R David Murray1b00f252012-08-15 10:43:58 -04001645.. index::
1646 single: universal newlines; str.splitlines method
1647
Georg Brandl116aa622007-08-15 14:28:22 +00001648.. method:: str.splitlines([keepends])
1649
R David Murray05c35a62012-08-06 16:08:09 -04001650 Return a list of the lines in the string, breaking at line boundaries.
R David Murray1b00f252012-08-15 10:43:58 -04001651 This method uses the :term:`universal newlines` approach to splitting lines.
R David Murray05c35a62012-08-06 16:08:09 -04001652 Line breaks are not included in the resulting list unless *keepends* is
1653 given and true.
R David Murrayae1b94b2012-06-01 16:19:36 -04001654
1655 For example, ``'ab c\n\nde fg\rkl\r\n'.splitlines()`` returns
R David Murray554b3482012-06-02 11:20:29 -04001656 ``['ab c', '', 'de fg', 'kl']``, while the same call with ``splitlines(True)``
Sandro Tosi82a509c2012-08-12 12:35:14 +02001657 returns ``['ab c\n', '\n', 'de fg\r', 'kl\r\n']``.
Georg Brandl116aa622007-08-15 14:28:22 +00001658
R David Murray05c35a62012-08-06 16:08:09 -04001659 Unlike :meth:`~str.split` when a delimiter string *sep* is given, this
1660 method returns an empty list for the empty string, and a terminal line
1661 break does not result in an extra line.
1662
Georg Brandl116aa622007-08-15 14:28:22 +00001663
1664.. method:: str.startswith(prefix[, start[, end]])
1665
1666 Return ``True`` if string starts with the *prefix*, otherwise return ``False``.
1667 *prefix* can also be a tuple of prefixes to look for. With optional *start*,
1668 test string beginning at that position. With optional *end*, stop comparing
1669 string at that position.
1670
Georg Brandl116aa622007-08-15 14:28:22 +00001671
1672.. method:: str.strip([chars])
1673
1674 Return a copy of the string with the leading and trailing characters removed.
1675 The *chars* argument is a string specifying the set of characters to be removed.
1676 If omitted or ``None``, the *chars* argument defaults to removing whitespace.
1677 The *chars* argument is not a prefix or suffix; rather, all combinations of its
Christian Heimesfe337bf2008-03-23 21:54:12 +00001678 values are stripped:
Georg Brandl116aa622007-08-15 14:28:22 +00001679
1680 >>> ' spacious '.strip()
1681 'spacious'
1682 >>> 'www.example.com'.strip('cmowz.')
1683 'example'
1684
Georg Brandl116aa622007-08-15 14:28:22 +00001685
1686.. method:: str.swapcase()
1687
1688 Return a copy of the string with uppercase characters converted to lowercase and
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05001689 vice versa. Note that it is not necessarily true that
1690 ``s.swapcase().swapcase() == s``.
Georg Brandl116aa622007-08-15 14:28:22 +00001691
Georg Brandl116aa622007-08-15 14:28:22 +00001692
1693.. method:: str.title()
1694
Raymond Hettingerb8b0ba12009-09-29 06:22:28 +00001695 Return a titlecased version of the string where words start with an uppercase
1696 character and the remaining characters are lowercase.
1697
1698 The algorithm uses a simple language-independent definition of a word as
1699 groups of consecutive letters. The definition works in many contexts but
1700 it means that apostrophes in contractions and possessives form word
1701 boundaries, which may not be the desired result::
1702
1703 >>> "they're bill's friends from the UK".title()
1704 "They'Re Bill'S Friends From The Uk"
1705
1706 A workaround for apostrophes can be constructed using regular expressions::
1707
1708 >>> import re
1709 >>> def titlecase(s):
1710 return re.sub(r"[A-Za-z]+('[A-Za-z]+)?",
1711 lambda mo: mo.group(0)[0].upper() +
1712 mo.group(0)[1:].lower(),
1713 s)
1714
1715 >>> titlecase("they're bill's friends.")
1716 "They're Bill's Friends."
Georg Brandl116aa622007-08-15 14:28:22 +00001717
Georg Brandl116aa622007-08-15 14:28:22 +00001718
Georg Brandl4b491312007-08-31 09:22:56 +00001719.. method:: str.translate(map)
Georg Brandl116aa622007-08-15 14:28:22 +00001720
Georg Brandl226878c2007-08-31 10:15:37 +00001721 Return a copy of the *s* where all characters have been mapped through the
Georg Brandl454636f2008-12-27 23:33:20 +00001722 *map* which must be a dictionary of Unicode ordinals (integers) to Unicode
Georg Brandlceee0772007-11-27 23:48:05 +00001723 ordinals, strings or ``None``. Unmapped characters are left untouched.
1724 Characters mapped to ``None`` are deleted.
1725
Georg Brandl454636f2008-12-27 23:33:20 +00001726 You can use :meth:`str.maketrans` to create a translation map from
1727 character-to-character mappings in different formats.
Christian Heimesfe337bf2008-03-23 21:54:12 +00001728
Georg Brandl4b491312007-08-31 09:22:56 +00001729 .. note::
Georg Brandl116aa622007-08-15 14:28:22 +00001730
Georg Brandlceee0772007-11-27 23:48:05 +00001731 An even more flexible approach is to create a custom character mapping
1732 codec using the :mod:`codecs` module (see :mod:`encodings.cp1251` for an
Georg Brandl4b491312007-08-31 09:22:56 +00001733 example).
Georg Brandl116aa622007-08-15 14:28:22 +00001734
1735
1736.. method:: str.upper()
1737
Ezio Melotti0656a562011-08-15 14:27:19 +03001738 Return a copy of the string with all the cased characters [4]_ converted to
1739 uppercase. Note that ``str.upper().isupper()`` might be ``False`` if ``s``
1740 contains uncased characters or if the Unicode category of the resulting
Benjamin Peterson94303542012-01-18 23:09:32 -05001741 character(s) is not "Lu" (Letter, uppercase), but e.g. "Lt" (Letter,
1742 titlecase).
1743
1744 The uppercasing algorithm used is described in section 3.13 of the Unicode
1745 Standard.
Georg Brandl116aa622007-08-15 14:28:22 +00001746
Georg Brandl116aa622007-08-15 14:28:22 +00001747
1748.. method:: str.zfill(width)
1749
Georg Brandl9afde1c2007-11-01 20:32:30 +00001750 Return the numeric string left filled with zeros in a string of length
1751 *width*. A sign prefix is handled correctly. The original string is
Terry Jan Reedyf4ec3c52012-01-11 03:29:42 -05001752 returned if *width* is less than or equal to ``len(s)``.
Christian Heimesb186d002008-03-18 15:15:01 +00001753
1754
Georg Brandl116aa622007-08-15 14:28:22 +00001755
Georg Brandl4b491312007-08-31 09:22:56 +00001756.. _old-string-formatting:
Georg Brandl116aa622007-08-15 14:28:22 +00001757
Nick Coghlan273069c2012-08-20 17:14:07 +10001758``printf``-style String Formatting
1759----------------------------------
Georg Brandl116aa622007-08-15 14:28:22 +00001760
1761.. index::
1762 single: formatting, string (%)
1763 single: interpolation, string (%)
1764 single: string; formatting
1765 single: string; interpolation
1766 single: printf-style formatting
1767 single: sprintf-style formatting
1768 single: % formatting
1769 single: % interpolation
1770
Georg Brandl4b491312007-08-31 09:22:56 +00001771.. note::
1772
Nick Coghlan273069c2012-08-20 17:14:07 +10001773 The formatting operations described here exhibit a variety of quirks that
1774 lead to a number of common errors (such as failing to display tuples and
1775 dictionaries correctly). Using the newer :meth:`str.format` interface
1776 helps avoid these errors, and also provides a generally more powerful,
1777 flexible and extensible approach to formatting text.
Georg Brandl4b491312007-08-31 09:22:56 +00001778
1779String objects have one unique built-in operation: the ``%`` operator (modulo).
1780This is also known as the string *formatting* or *interpolation* operator.
1781Given ``format % values`` (where *format* is a string), ``%`` conversion
1782specifications in *format* are replaced with zero or more elements of *values*.
Nick Coghlan273069c2012-08-20 17:14:07 +10001783The effect is similar to using the :c:func:`sprintf` in the C language.
Georg Brandl116aa622007-08-15 14:28:22 +00001784
1785If *format* requires a single argument, *values* may be a single non-tuple
Ezio Melotti0656a562011-08-15 14:27:19 +03001786object. [5]_ Otherwise, *values* must be a tuple with exactly the number of
Georg Brandl116aa622007-08-15 14:28:22 +00001787items specified by the format string, or a single mapping object (for example, a
1788dictionary).
1789
1790A conversion specifier contains two or more characters and has the following
1791components, which must occur in this order:
1792
1793#. The ``'%'`` character, which marks the start of the specifier.
1794
1795#. Mapping key (optional), consisting of a parenthesised sequence of characters
1796 (for example, ``(somename)``).
1797
1798#. Conversion flags (optional), which affect the result of some conversion
1799 types.
1800
1801#. Minimum field width (optional). If specified as an ``'*'`` (asterisk), the
1802 actual width is read from the next element of the tuple in *values*, and the
1803 object to convert comes after the minimum field width and optional precision.
1804
1805#. Precision (optional), given as a ``'.'`` (dot) followed by the precision. If
Eli Benderskyef4902a2011-07-29 09:30:42 +03001806 specified as ``'*'`` (an asterisk), the actual precision is read from the next
Georg Brandl116aa622007-08-15 14:28:22 +00001807 element of the tuple in *values*, and the value to convert comes after the
1808 precision.
1809
1810#. Length modifier (optional).
1811
1812#. Conversion type.
1813
1814When the right argument is a dictionary (or other mapping type), then the
1815formats in the string *must* include a parenthesised mapping key into that
1816dictionary inserted immediately after the ``'%'`` character. The mapping key
Christian Heimesfe337bf2008-03-23 21:54:12 +00001817selects the value to be formatted from the mapping. For example:
Georg Brandl116aa622007-08-15 14:28:22 +00001818
Georg Brandledc9e7f2010-10-17 09:19:03 +00001819 >>> print('%(language)s has %(number)03d quote types.' %
1820 ... {'language': "Python", "number": 2})
Georg Brandl116aa622007-08-15 14:28:22 +00001821 Python has 002 quote types.
1822
1823In this case no ``*`` specifiers may occur in a format (since they require a
1824sequential parameter list).
1825
1826The conversion flag characters are:
1827
1828+---------+---------------------------------------------------------------------+
1829| Flag | Meaning |
1830+=========+=====================================================================+
1831| ``'#'`` | The value conversion will use the "alternate form" (where defined |
1832| | below). |
1833+---------+---------------------------------------------------------------------+
1834| ``'0'`` | The conversion will be zero padded for numeric values. |
1835+---------+---------------------------------------------------------------------+
1836| ``'-'`` | The converted value is left adjusted (overrides the ``'0'`` |
1837| | conversion if both are given). |
1838+---------+---------------------------------------------------------------------+
1839| ``' '`` | (a space) A blank should be left before a positive number (or empty |
1840| | string) produced by a signed conversion. |
1841+---------+---------------------------------------------------------------------+
1842| ``'+'`` | A sign character (``'+'`` or ``'-'``) will precede the conversion |
1843| | (overrides a "space" flag). |
1844+---------+---------------------------------------------------------------------+
1845
1846A length modifier (``h``, ``l``, or ``L``) may be present, but is ignored as it
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +00001847is not necessary for Python -- so e.g. ``%ld`` is identical to ``%d``.
Georg Brandl116aa622007-08-15 14:28:22 +00001848
1849The conversion types are:
1850
1851+------------+-----------------------------------------------------+-------+
1852| Conversion | Meaning | Notes |
1853+============+=====================================================+=======+
1854| ``'d'`` | Signed integer decimal. | |
1855+------------+-----------------------------------------------------+-------+
1856| ``'i'`` | Signed integer decimal. | |
1857+------------+-----------------------------------------------------+-------+
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +00001858| ``'o'`` | Signed octal value. | \(1) |
Georg Brandl116aa622007-08-15 14:28:22 +00001859+------------+-----------------------------------------------------+-------+
Benjamin Petersone0124bd2009-03-09 21:04:33 +00001860| ``'u'`` | Obsolete type -- it is identical to ``'d'``. | \(7) |
Georg Brandl116aa622007-08-15 14:28:22 +00001861+------------+-----------------------------------------------------+-------+
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +00001862| ``'x'`` | Signed hexadecimal (lowercase). | \(2) |
Georg Brandl116aa622007-08-15 14:28:22 +00001863+------------+-----------------------------------------------------+-------+
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +00001864| ``'X'`` | Signed hexadecimal (uppercase). | \(2) |
Georg Brandl116aa622007-08-15 14:28:22 +00001865+------------+-----------------------------------------------------+-------+
1866| ``'e'`` | Floating point exponential format (lowercase). | \(3) |
1867+------------+-----------------------------------------------------+-------+
1868| ``'E'`` | Floating point exponential format (uppercase). | \(3) |
1869+------------+-----------------------------------------------------+-------+
Eric Smith22b85b32008-07-17 19:18:29 +00001870| ``'f'`` | Floating point decimal format. | \(3) |
Georg Brandl116aa622007-08-15 14:28:22 +00001871+------------+-----------------------------------------------------+-------+
Eric Smith22b85b32008-07-17 19:18:29 +00001872| ``'F'`` | Floating point decimal format. | \(3) |
Georg Brandl116aa622007-08-15 14:28:22 +00001873+------------+-----------------------------------------------------+-------+
Christian Heimes8dc226f2008-05-06 23:45:46 +00001874| ``'g'`` | Floating point format. Uses lowercase exponential | \(4) |
1875| | format if exponent is less than -4 or not less than | |
1876| | precision, decimal format otherwise. | |
Georg Brandl116aa622007-08-15 14:28:22 +00001877+------------+-----------------------------------------------------+-------+
Christian Heimes8dc226f2008-05-06 23:45:46 +00001878| ``'G'`` | Floating point format. Uses uppercase exponential | \(4) |
1879| | format if exponent is less than -4 or not less than | |
1880| | precision, decimal format otherwise. | |
Georg Brandl116aa622007-08-15 14:28:22 +00001881+------------+-----------------------------------------------------+-------+
1882| ``'c'`` | Single character (accepts integer or single | |
1883| | character string). | |
1884+------------+-----------------------------------------------------+-------+
Ezio Melotti0639d5a2009-12-19 23:26:38 +00001885| ``'r'`` | String (converts any Python object using | \(5) |
Georg Brandl116aa622007-08-15 14:28:22 +00001886| | :func:`repr`). | |
1887+------------+-----------------------------------------------------+-------+
Eli Benderskyef4902a2011-07-29 09:30:42 +03001888| ``'s'`` | String (converts any Python object using | \(5) |
Georg Brandl116aa622007-08-15 14:28:22 +00001889| | :func:`str`). | |
1890+------------+-----------------------------------------------------+-------+
Eli Benderskyef4902a2011-07-29 09:30:42 +03001891| ``'a'`` | String (converts any Python object using | \(5) |
1892| | :func:`ascii`). | |
1893+------------+-----------------------------------------------------+-------+
Georg Brandl116aa622007-08-15 14:28:22 +00001894| ``'%'`` | No argument is converted, results in a ``'%'`` | |
1895| | character in the result. | |
1896+------------+-----------------------------------------------------+-------+
1897
1898Notes:
1899
1900(1)
1901 The alternate form causes a leading zero (``'0'``) to be inserted between
1902 left-hand padding and the formatting of the number if the leading character
1903 of the result is not already a zero.
1904
1905(2)
1906 The alternate form causes a leading ``'0x'`` or ``'0X'`` (depending on whether
1907 the ``'x'`` or ``'X'`` format was used) to be inserted between left-hand padding
1908 and the formatting of the number if the leading character of the result is not
1909 already a zero.
1910
1911(3)
1912 The alternate form causes the result to always contain a decimal point, even if
1913 no digits follow it.
1914
1915 The precision determines the number of digits after the decimal point and
1916 defaults to 6.
1917
1918(4)
1919 The alternate form causes the result to always contain a decimal point, and
1920 trailing zeroes are not removed as they would otherwise be.
1921
1922 The precision determines the number of significant digits before and after the
1923 decimal point and defaults to 6.
1924
1925(5)
Eli Benderskyef4902a2011-07-29 09:30:42 +03001926 If precision is ``N``, the output is truncated to ``N`` characters.
Georg Brandl116aa622007-08-15 14:28:22 +00001927
Georg Brandl116aa622007-08-15 14:28:22 +00001928
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +00001929(7)
1930 See :pep:`237`.
1931
Georg Brandl116aa622007-08-15 14:28:22 +00001932Since Python strings have an explicit length, ``%s`` conversions do not assume
1933that ``'\0'`` is the end of the string.
1934
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001935.. XXX Examples?
1936
Mark Dickinson33841c32009-05-01 15:37:04 +00001937.. versionchanged:: 3.1
1938 ``%f`` conversions for numbers whose absolute value is over 1e50 are no
1939 longer replaced by ``%g`` conversions.
Georg Brandl116aa622007-08-15 14:28:22 +00001940
Georg Brandl116aa622007-08-15 14:28:22 +00001941
Nick Coghlan273069c2012-08-20 17:14:07 +10001942.. _binaryseq:
Georg Brandl116aa622007-08-15 14:28:22 +00001943
Nick Coghlan273069c2012-08-20 17:14:07 +10001944Binary Sequence Types --- :class:`bytes`, :class:`bytearray`, :class:`memoryview`
1945=================================================================================
Georg Brandl116aa622007-08-15 14:28:22 +00001946
1947.. index::
Nick Coghlan273069c2012-08-20 17:14:07 +10001948 object: bytes
Georg Brandl95414632007-11-22 11:00:28 +00001949 object: bytearray
Nick Coghlan273069c2012-08-20 17:14:07 +10001950 object: memoryview
1951 module: array
Georg Brandl116aa622007-08-15 14:28:22 +00001952
Nick Coghlan273069c2012-08-20 17:14:07 +10001953The core built-in types for manipulating binary data are :class:`bytes` and
1954:class:`bytearray`. They are supported by :class:`memoryview` which uses
1955the buffer protocol to access the memory of other binary objects without
1956needing to make a copy.
Georg Brandl226878c2007-08-31 10:15:37 +00001957
Nick Coghlan273069c2012-08-20 17:14:07 +10001958The :mod:`array` module supports efficient storage of basic data types like
195932-bit integers and IEEE754 double-precision floating values.
Georg Brandl116aa622007-08-15 14:28:22 +00001960
Nick Coghlan273069c2012-08-20 17:14:07 +10001961.. _typebytes:
Senthil Kumaran7cafd262010-10-02 03:16:04 +00001962
Nick Coghlan273069c2012-08-20 17:14:07 +10001963Bytes
1964-----
1965
1966.. index:: object: bytes
1967
1968Bytes objects are immutable sequences of single bytes. Since many major
1969binary protocols are based on the ASCII text encoding, bytes objects offer
1970several methods that are only valid when working with ASCII compatible
1971data and are closely related to string objects in a variety of other ways.
1972
1973Firstly, the syntax for bytes literals is largely the same as that for string
1974literals, except that a ``b`` prefix is added:
1975
1976* Single quotes: ``b'still allows embedded "double" quotes'``
1977* Double quotes: ``b"still allows embedded 'single' quotes"``.
1978* Triple quoted: ``b'''3 single quotes'''``, ``b"""3 double quotes"""``
1979
1980Only ASCII characters are permitted in bytes literals (regardless of the
1981declared source code encoding). Any binary values over 127 must be entered
1982into bytes literals using the appropriate escape sequence.
1983
1984As with string literals, bytes literals may also use a ``r`` prefix to disable
1985processing of escape sequences. See :ref:`strings` for more about the various
1986forms of bytes literal, including supported escape sequences.
1987
1988While bytes literals and representations are based on ASCII text, bytes
1989objects actually behave like immutable sequences of integers, with each
1990value in the sequence restricted such that ``0 <= x < 256`` (attempts to
1991violate this restriction will trigger :exc:`ValueError`. This is done
1992deliberately to emphasise that while many binary formats include ASCII based
1993elements and can be usefully manipulated with some text-oriented algorithms,
1994this is not generally the case for arbitrary binary data (blindly applying
1995text processing algorithms to binary data formats that are not ASCII
1996compatible will usually lead to data corruption).
1997
1998In addition to the literal forms, bytes objects can be created in a number of
1999other ways:
2000
2001* A zero-filled bytes object of a specified length: ``bytes(10)``
2002* From an iterable of integers: ``bytes(range(20))``
2003* Copying existing binary data via the buffer protocol: ``bytes(obj)``
2004
2005Since bytes objects are sequences of integers, for a bytes object *b*,
2006``b[0]`` will be an integer, while ``b[0:1]`` will be a bytes object of
2007length 1. (This contrasts with text strings, where both indexing and
2008slicing will produce a string of length 1)
2009
2010The representation of bytes objects uses the literal format (``b'...'``)
2011since it is often more useful than e.g. ``bytes([46, 46, 46])``. You can
2012always convert a bytes object into a list of integers using ``list(b)``.
Georg Brandl116aa622007-08-15 14:28:22 +00002013
Georg Brandl116aa622007-08-15 14:28:22 +00002014
Nick Coghlan273069c2012-08-20 17:14:07 +10002015.. note::
2016 For Python 2.x users: In the Python 2.x series, a variety of implicit
2017 conversions between 8-bit strings (the closest thing 2.x offers to a
2018 built-in binary data type) and Unicode strings were permitted. This was a
2019 backwards compatibility workaround to account for the fact that Python
2020 originally only supported 8-bit text, and Unicode text was a later
2021 addition. In Python 3.x, those implicit conversions are gone - conversions
2022 between 8-bit binary data and Unicode text must be explicit, and bytes and
2023 string objects will always compare unequal.
Raymond Hettingerc50846a2010-04-05 18:56:31 +00002024
Georg Brandl116aa622007-08-15 14:28:22 +00002025
Nick Coghlan273069c2012-08-20 17:14:07 +10002026.. _typebytearray:
Georg Brandl116aa622007-08-15 14:28:22 +00002027
Nick Coghlan273069c2012-08-20 17:14:07 +10002028Bytearray Objects
2029-----------------
Georg Brandl116aa622007-08-15 14:28:22 +00002030
Nick Coghlan273069c2012-08-20 17:14:07 +10002031.. index:: object: bytearray
Georg Brandl495f7b52009-10-27 15:28:25 +00002032
Nick Coghlan273069c2012-08-20 17:14:07 +10002033:class:`bytearray` objects are a mutable counterpart to :class:`bytes`
2034objects. There is no dedicated literal syntax for bytearray objects, instead
2035they are always created by calling the constructor:
Georg Brandl116aa622007-08-15 14:28:22 +00002036
Nick Coghlan273069c2012-08-20 17:14:07 +10002037* Creating an empty instance: ``bytearray()``
2038* Creating a zero-filled instance with a given length: ``bytearray(10)``
2039* From an iterable of integers: ``bytearray(range(20))``
2040* Copying existing binary data via the buffer protocol: ``bytearray(b'Hi!)``
Eli Benderskycbbaa962011-02-25 05:47:53 +00002041
Nick Coghlan273069c2012-08-20 17:14:07 +10002042As bytearray objects are mutable, they support the
2043:ref:`mutable <typesseq-mutable>` sequence operations in addition to the
2044common bytes and bytearray operations described in :ref:`bytes-methods`.
Georg Brandl116aa622007-08-15 14:28:22 +00002045
Georg Brandl495f7b52009-10-27 15:28:25 +00002046
Georg Brandl226878c2007-08-31 10:15:37 +00002047.. _bytes-methods:
2048
Nick Coghlan273069c2012-08-20 17:14:07 +10002049Bytes and Bytearray Operations
2050------------------------------
Georg Brandl226878c2007-08-31 10:15:37 +00002051
2052.. index:: pair: bytes; methods
Georg Brandl95414632007-11-22 11:00:28 +00002053 pair: bytearray; methods
Georg Brandl226878c2007-08-31 10:15:37 +00002054
Nick Coghlan273069c2012-08-20 17:14:07 +10002055Both bytes and bytearray objects support the :ref:`common <typesseq-common>`
2056sequence operations. They interoperate not just with operands of the same
2057type, but with any object that supports the
2058:ref:`buffer protocol <bufferobjects>`. Due to this flexibility, they can be
2059freely mixed in operations without causing errors. However, the return type
2060of the result may depend on the order of operands.
Guido van Rossum98297ee2007-11-06 21:34:58 +00002061
Nick Coghlan273069c2012-08-20 17:14:07 +10002062Due to the common use of ASCII text as the basis for binary protocols, bytes
2063and bytearray objects provide almost all methods found on text strings, with
2064the exceptions of:
Georg Brandl226878c2007-08-31 10:15:37 +00002065
Nick Coghlan273069c2012-08-20 17:14:07 +10002066* :meth:`str.encode` (which converts text strings to bytes objects)
2067* :meth:`str.format` and :meth:`str.format_map` (which are used to format
2068 text for display to users)
2069* :meth:`str.isidentifier`, :meth:`str.isnumeric`, :meth:`str.isdecimal`,
2070 :meth:`str.isprintable` (which are used to check various properties of
2071 text strings which are not typically applicable to binary protocols).
2072
2073All other string methods are supported, although sometimes with slight
2074differences in functionality and semantics (as described below).
Antoine Pitrouac65d962011-10-20 23:54:17 +02002075
Georg Brandl7c676132007-10-23 18:17:00 +00002076.. note::
Georg Brandl226878c2007-08-31 10:15:37 +00002077
Georg Brandl95414632007-11-22 11:00:28 +00002078 The methods on bytes and bytearray objects don't accept strings as their
Georg Brandl7c676132007-10-23 18:17:00 +00002079 arguments, just as the methods on strings don't accept bytes as their
Nick Coghlan273069c2012-08-20 17:14:07 +10002080 arguments. For example, you have to write::
Georg Brandl226878c2007-08-31 10:15:37 +00002081
Georg Brandl7c676132007-10-23 18:17:00 +00002082 a = "abc"
2083 b = a.replace("a", "f")
2084
Nick Coghlan273069c2012-08-20 17:14:07 +10002085 and::
Georg Brandl7c676132007-10-23 18:17:00 +00002086
2087 a = b"abc"
2088 b = a.replace(b"a", b"f")
Georg Brandl226878c2007-08-31 10:15:37 +00002089
Nick Coghlan273069c2012-08-20 17:14:07 +10002090Whenever a bytes or bytearray method needs to interpret the bytes as
2091characters (e.g. the :meth:`is...` methods, :meth:`split`, :meth:`strip`),
2092the ASCII character set is assumed (text strings use Unicode semantics).
2093
2094.. note::
2095 Using these ASCII based methods to manipulate binary data that is not
2096 stored in an ASCII based format may lead to data corruption.
2097
2098The search operations (:keyword:`in`, :meth:`count`, :meth:`find`,
2099:meth:`index`, :meth:`rfind` and :meth:`rindex`) all accept both integers
2100in the range 0 to 255 as well as bytes and byte array sequences.
2101
2102.. versionchanged:: 3.3
2103 All of the search methods also accept an integer in range 0 to 255
2104 (a byte) as their first argument.
2105
2106
2107Each bytes and bytearray instance provides a :meth:`decode` convenience
2108method that is the inverse of "meth:`str.encode`:
Georg Brandl226878c2007-08-31 10:15:37 +00002109
Victor Stinnere14e2122010-11-07 18:41:46 +00002110.. method:: bytes.decode(encoding="utf-8", errors="strict")
2111 bytearray.decode(encoding="utf-8", errors="strict")
Georg Brandl4f5f98d2009-05-04 21:01:20 +00002112
Victor Stinnere14e2122010-11-07 18:41:46 +00002113 Return a string decoded from the given bytes. Default encoding is
2114 ``'utf-8'``. *errors* may be given to set a different
Georg Brandl4f5f98d2009-05-04 21:01:20 +00002115 error handling scheme. The default for *errors* is ``'strict'``, meaning
2116 that encoding errors raise a :exc:`UnicodeError`. Other possible values are
2117 ``'ignore'``, ``'replace'`` and any other name registered via
2118 :func:`codecs.register_error`, see section :ref:`codec-base-classes`. For a
2119 list of possible encodings, see section :ref:`standard-encodings`.
2120
Benjamin Peterson308d6372009-09-18 21:42:35 +00002121 .. versionchanged:: 3.1
2122 Added support for keyword arguments.
2123
Nick Coghlan273069c2012-08-20 17:14:07 +10002124Since 2 hexadecimal digits correspond precisely to a single byte, hexadecimal
2125numbers are a commonly used format for describing binary data. Accordingly,
2126the bytes and bytearray types have an additional class method to read data in
2127that format:
Georg Brandl226878c2007-08-31 10:15:37 +00002128
Georg Brandlabc38772009-04-12 15:51:51 +00002129.. classmethod:: bytes.fromhex(string)
2130 bytearray.fromhex(string)
Georg Brandl226878c2007-08-31 10:15:37 +00002131
Georg Brandl18da8f02008-07-01 20:08:02 +00002132 This :class:`bytes` class method returns a bytes or bytearray object,
2133 decoding the given string object. The string must contain two hexadecimal
2134 digits per byte, spaces are ignored.
Georg Brandl226878c2007-08-31 10:15:37 +00002135
Nick Coghlan273069c2012-08-20 17:14:07 +10002136 >>> bytes.fromhex('2Ef0 F1f2 ')
2137 b'.\xf0\xf1\xf2'
Georg Brandl226878c2007-08-31 10:15:37 +00002138
Georg Brandlabc38772009-04-12 15:51:51 +00002139
2140The maketrans and translate methods differ in semantics from the versions
2141available on strings:
Georg Brandl48310cd2009-01-03 21:18:54 +00002142
Georg Brandl454636f2008-12-27 23:33:20 +00002143.. method:: bytes.translate(table[, delete])
Georg Brandl751771b2009-05-31 21:38:37 +00002144 bytearray.translate(table[, delete])
Georg Brandl226878c2007-08-31 10:15:37 +00002145
Georg Brandl454636f2008-12-27 23:33:20 +00002146 Return a copy of the bytes or bytearray object where all bytes occurring in
2147 the optional argument *delete* are removed, and the remaining bytes have been
2148 mapped through the given translation table, which must be a bytes object of
2149 length 256.
Georg Brandl226878c2007-08-31 10:15:37 +00002150
Georg Brandlabc38772009-04-12 15:51:51 +00002151 You can use the :func:`bytes.maketrans` method to create a translation table.
Georg Brandl226878c2007-08-31 10:15:37 +00002152
Georg Brandl454636f2008-12-27 23:33:20 +00002153 Set the *table* argument to ``None`` for translations that only delete
2154 characters::
Georg Brandl226878c2007-08-31 10:15:37 +00002155
Georg Brandl454636f2008-12-27 23:33:20 +00002156 >>> b'read this short text'.translate(None, b'aeiou')
2157 b'rd ths shrt txt'
Georg Brandl226878c2007-08-31 10:15:37 +00002158
2159
Georg Brandlabc38772009-04-12 15:51:51 +00002160.. staticmethod:: bytes.maketrans(from, to)
Georg Brandl751771b2009-05-31 21:38:37 +00002161 bytearray.maketrans(from, to)
Georg Brandlabc38772009-04-12 15:51:51 +00002162
2163 This static method returns a translation table usable for
2164 :meth:`bytes.translate` that will map each character in *from* into the
2165 character at the same position in *to*; *from* and *to* must be bytes objects
2166 and have the same length.
2167
2168 .. versionadded:: 3.1
2169
2170
Nick Coghlan273069c2012-08-20 17:14:07 +10002171.. _typememoryview:
2172
2173Memory Views
2174------------
2175
2176:class:`memoryview` objects allow Python code to access the internal data
2177of an object that supports the :ref:`buffer protocol <bufferobjects>` without
2178copying.
2179
2180.. class:: memoryview(obj)
2181
2182 Create a :class:`memoryview` that references *obj*. *obj* must support the
2183 buffer protocol. Built-in objects that support the buffer protocol include
2184 :class:`bytes` and :class:`bytearray`.
2185
2186 A :class:`memoryview` has the notion of an *element*, which is the
2187 atomic memory unit handled by the originating object *obj*. For many
2188 simple types such as :class:`bytes` and :class:`bytearray`, an element
2189 is a single byte, but other types such as :class:`array.array` may have
2190 bigger elements.
2191
2192 ``len(view)`` is equal to the length of :class:`~memoryview.tolist`.
2193 If ``view.ndim = 0``, the length is 1. If ``view.ndim = 1``, the length
2194 is equal to the number of elements in the view. For higher dimensions,
2195 the length is equal to the length of the nested list representation of
2196 the view. The :class:`~memoryview.itemsize` attribute will give you the
2197 number of bytes in a single element.
2198
2199 A :class:`memoryview` supports slicing to expose its data. If
2200 :class:`~memoryview.format` is one of the native format specifiers
2201 from the :mod:`struct` module, indexing will return a single element
2202 with the correct type. Full slicing will result in a subview::
2203
2204 >>> v = memoryview(b'abcefg')
2205 >>> v[1]
2206 98
2207 >>> v[-1]
2208 103
2209 >>> v[1:4]
2210 <memory at 0x7f3ddc9f4350>
2211 >>> bytes(v[1:4])
2212 b'bce'
2213
2214 Other native formats::
2215
2216 >>> import array
2217 >>> a = array.array('l', [-11111111, 22222222, -33333333, 44444444])
2218 >>> a[0]
2219 -11111111
2220 >>> a[-1]
2221 44444444
2222 >>> a[2:3].tolist()
2223 [-33333333]
2224 >>> a[::2].tolist()
2225 [-11111111, -33333333]
2226 >>> a[::-1].tolist()
2227 [44444444, -33333333, 22222222, -11111111]
2228
2229 .. versionadded:: 3.3
2230
2231 If the underlying object is writable, the memoryview supports slice
2232 assignment. Resizing is not allowed::
2233
2234 >>> data = bytearray(b'abcefg')
2235 >>> v = memoryview(data)
2236 >>> v.readonly
2237 False
2238 >>> v[0] = ord(b'z')
2239 >>> data
2240 bytearray(b'zbcefg')
2241 >>> v[1:4] = b'123'
2242 >>> data
2243 bytearray(b'z123fg')
2244 >>> v[2:3] = b'spam'
2245 Traceback (most recent call last):
2246 File "<stdin>", line 1, in <module>
2247 ValueError: memoryview assignment: lvalue and rvalue have different structures
2248 >>> v[2:6] = b'spam'
2249 >>> data
2250 bytearray(b'z1spam')
2251
2252 Memoryviews of hashable (read-only) types are also hashable. The hash
2253 is defined as ``hash(m) == hash(m.tobytes())``::
2254
2255 >>> v = memoryview(b'abcefg')
2256 >>> hash(v) == hash(b'abcefg')
2257 True
2258 >>> hash(v[2:4]) == hash(b'ce')
2259 True
2260 >>> hash(v[::-2]) == hash(b'abcefg'[::-2])
2261 True
2262
2263 Hashing of multi-dimensional objects is supported::
2264
2265 >>> buf = bytes(list(range(12)))
2266 >>> x = memoryview(buf)
2267 >>> y = x.cast('B', shape=[2,2,3])
2268 >>> x.tolist()
2269 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
2270 >>> y.tolist()
2271 [[[0, 1, 2], [3, 4, 5]], [[6, 7, 8], [9, 10, 11]]]
2272 >>> hash(x) == hash(y) == hash(y.tobytes())
2273 True
2274
2275 .. versionchanged:: 3.3
2276 Memoryview objects are now hashable.
2277
2278
2279 :class:`memoryview` has several methods:
2280
2281 .. method:: tobytes()
2282
2283 Return the data in the buffer as a bytestring. This is equivalent to
2284 calling the :class:`bytes` constructor on the memoryview. ::
2285
2286 >>> m = memoryview(b"abc")
2287 >>> m.tobytes()
2288 b'abc'
2289 >>> bytes(m)
2290 b'abc'
2291
2292 For non-contiguous arrays the result is equal to the flattened list
2293 representation with all elements converted to bytes.
2294
2295 .. method:: tolist()
2296
2297 Return the data in the buffer as a list of elements. ::
2298
2299 >>> memoryview(b'abc').tolist()
2300 [97, 98, 99]
2301 >>> import array
2302 >>> a = array.array('d', [1.1, 2.2, 3.3])
2303 >>> m = memoryview(a)
2304 >>> m.tolist()
2305 [1.1, 2.2, 3.3]
2306
2307 .. method:: release()
2308
2309 Release the underlying buffer exposed by the memoryview object. Many
2310 objects take special actions when a view is held on them (for example,
2311 a :class:`bytearray` would temporarily forbid resizing); therefore,
2312 calling release() is handy to remove these restrictions (and free any
2313 dangling resources) as soon as possible.
2314
2315 After this method has been called, any further operation on the view
2316 raises a :class:`ValueError` (except :meth:`release()` itself which can
2317 be called multiple times)::
2318
2319 >>> m = memoryview(b'abc')
2320 >>> m.release()
2321 >>> m[0]
2322 Traceback (most recent call last):
2323 File "<stdin>", line 1, in <module>
2324 ValueError: operation forbidden on released memoryview object
2325
2326 The context management protocol can be used for a similar effect,
2327 using the ``with`` statement::
2328
2329 >>> with memoryview(b'abc') as m:
2330 ... m[0]
2331 ...
2332 97
2333 >>> m[0]
2334 Traceback (most recent call last):
2335 File "<stdin>", line 1, in <module>
2336 ValueError: operation forbidden on released memoryview object
2337
2338 .. versionadded:: 3.2
2339
2340 .. method:: cast(format[, shape])
2341
2342 Cast a memoryview to a new format or shape. *shape* defaults to
2343 ``[byte_length//new_itemsize]``, which means that the result view
2344 will be one-dimensional. The return value is a new memoryview, but
2345 the buffer itself is not copied. Supported casts are 1D -> C-contiguous
2346 and C-contiguous -> 1D. One of the formats must be a byte format
2347 ('B', 'b' or 'c'). The byte length of the result must be the same
2348 as the original length.
2349
2350 Cast 1D/long to 1D/unsigned bytes::
2351
2352 >>> import array
2353 >>> a = array.array('l', [1,2,3])
2354 >>> x = memoryview(a)
2355 >>> x.format
2356 'l'
2357 >>> x.itemsize
2358 8
2359 >>> len(x)
2360 3
2361 >>> x.nbytes
2362 24
2363 >>> y = x.cast('B')
2364 >>> y.format
2365 'B'
2366 >>> y.itemsize
2367 1
2368 >>> len(y)
2369 24
2370 >>> y.nbytes
2371 24
2372
2373 Cast 1D/unsigned bytes to 1D/char::
2374
2375 >>> b = bytearray(b'zyz')
2376 >>> x = memoryview(b)
2377 >>> x[0] = b'a'
2378 Traceback (most recent call last):
2379 File "<stdin>", line 1, in <module>
2380 ValueError: memoryview: invalid value for format "B"
2381 >>> y = x.cast('c')
2382 >>> y[0] = b'a'
2383 >>> b
2384 bytearray(b'ayz')
2385
2386 Cast 1D/bytes to 3D/ints to 1D/signed char::
2387
2388 >>> import struct
2389 >>> buf = struct.pack("i"*12, *list(range(12)))
2390 >>> x = memoryview(buf)
2391 >>> y = x.cast('i', shape=[2,2,3])
2392 >>> y.tolist()
2393 [[[0, 1, 2], [3, 4, 5]], [[6, 7, 8], [9, 10, 11]]]
2394 >>> y.format
2395 'i'
2396 >>> y.itemsize
2397 4
2398 >>> len(y)
2399 2
2400 >>> y.nbytes
2401 48
2402 >>> z = y.cast('b')
2403 >>> z.format
2404 'b'
2405 >>> z.itemsize
2406 1
2407 >>> len(z)
2408 48
2409 >>> z.nbytes
2410 48
2411
2412 Cast 1D/unsigned char to to 2D/unsigned long::
2413
2414 >>> buf = struct.pack("L"*6, *list(range(6)))
2415 >>> x = memoryview(buf)
2416 >>> y = x.cast('L', shape=[2,3])
2417 >>> len(y)
2418 2
2419 >>> y.nbytes
2420 48
2421 >>> y.tolist()
2422 [[0, 1, 2], [3, 4, 5]]
2423
2424 .. versionadded:: 3.3
2425
2426 There are also several readonly attributes available:
2427
2428 .. attribute:: obj
2429
2430 The underlying object of the memoryview::
2431
2432 >>> b = bytearray(b'xyz')
2433 >>> m = memoryview(b)
2434 >>> m.obj is b
2435 True
2436
2437 .. versionadded:: 3.3
2438
2439 .. attribute:: nbytes
2440
2441 ``nbytes == product(shape) * itemsize == len(m.tobytes())``. This is
2442 the amount of space in bytes that the array would use in a contiguous
2443 representation. It is not necessarily equal to len(m)::
2444
2445 >>> import array
2446 >>> a = array.array('i', [1,2,3,4,5])
2447 >>> m = memoryview(a)
2448 >>> len(m)
2449 5
2450 >>> m.nbytes
2451 20
2452 >>> y = m[::2]
2453 >>> len(y)
2454 3
2455 >>> y.nbytes
2456 12
2457 >>> len(y.tobytes())
2458 12
2459
2460 Multi-dimensional arrays::
2461
2462 >>> import struct
2463 >>> buf = struct.pack("d"*12, *[1.5*x for x in range(12)])
2464 >>> x = memoryview(buf)
2465 >>> y = x.cast('d', shape=[3,4])
2466 >>> y.tolist()
2467 [[0.0, 1.5, 3.0, 4.5], [6.0, 7.5, 9.0, 10.5], [12.0, 13.5, 15.0, 16.5]]
2468 >>> len(y)
2469 3
2470 >>> y.nbytes
2471 96
2472
2473 .. versionadded:: 3.3
2474
2475 .. attribute:: readonly
2476
2477 A bool indicating whether the memory is read only.
2478
2479 .. attribute:: format
2480
2481 A string containing the format (in :mod:`struct` module style) for each
2482 element in the view. A memoryview can be created from exporters with
2483 arbitrary format strings, but some methods (e.g. :meth:`tolist`) are
2484 restricted to native single element formats. Special care must be taken
2485 when comparing memoryviews. Since comparisons are required to return a
2486 value for ``==`` and ``!=``, two memoryviews referencing the same
2487 exporter can compare as not-equal if the exporter's format is not
2488 understood::
2489
2490 >>> from ctypes import BigEndianStructure, c_long
2491 >>> class BEPoint(BigEndianStructure):
2492 ... _fields_ = [("x", c_long), ("y", c_long)]
2493 ...
2494 >>> point = BEPoint(100, 200)
2495 >>> a = memoryview(point)
2496 >>> b = memoryview(point)
2497 >>> a == b
2498 False
2499 >>> a.tolist()
2500 Traceback (most recent call last):
2501 File "<stdin>", line 1, in <module>
2502 NotImplementedError: memoryview: unsupported format T{>l:x:>l:y:}
2503
2504 .. attribute:: itemsize
2505
2506 The size in bytes of each element of the memoryview::
2507
2508 >>> import array, struct
2509 >>> m = memoryview(array.array('H', [32000, 32001, 32002]))
2510 >>> m.itemsize
2511 2
2512 >>> m[0]
2513 32000
2514 >>> struct.calcsize('H') == m.itemsize
2515 True
2516
2517 .. attribute:: ndim
2518
2519 An integer indicating how many dimensions of a multi-dimensional array the
2520 memory represents.
2521
2522 .. attribute:: shape
2523
2524 A tuple of integers the length of :attr:`ndim` giving the shape of the
2525 memory as a N-dimensional array.
2526
2527 .. attribute:: strides
2528
2529 A tuple of integers the length of :attr:`ndim` giving the size in bytes to
2530 access each element for each dimension of the array.
2531
2532 .. attribute:: suboffsets
2533
2534 Used internally for PIL-style arrays. The value is informational only.
2535
2536 .. attribute:: c_contiguous
2537
2538 A bool indicating whether the memory is C-contiguous.
2539
2540 .. versionadded:: 3.3
2541
2542 .. attribute:: f_contiguous
2543
2544 A bool indicating whether the memory is Fortran contiguous.
2545
2546 .. versionadded:: 3.3
2547
2548 .. attribute:: contiguous
2549
2550 A bool indicating whether the memory is contiguous.
2551
2552 .. versionadded:: 3.3
2553
2554
Georg Brandl116aa622007-08-15 14:28:22 +00002555.. _types-set:
2556
2557Set Types --- :class:`set`, :class:`frozenset`
2558==============================================
2559
2560.. index:: object: set
2561
Guido van Rossum2cc30da2007-11-02 23:46:40 +00002562A :dfn:`set` object is an unordered collection of distinct :term:`hashable` objects.
Georg Brandl116aa622007-08-15 14:28:22 +00002563Common uses include membership testing, removing duplicates from a sequence, and
2564computing mathematical operations such as intersection, union, difference, and
2565symmetric difference.
2566(For other containers see the built in :class:`dict`, :class:`list`,
2567and :class:`tuple` classes, and the :mod:`collections` module.)
2568
Georg Brandl116aa622007-08-15 14:28:22 +00002569Like other collections, sets support ``x in set``, ``len(set)``, and ``for x in
2570set``. Being an unordered collection, sets do not record element position or
2571order of insertion. Accordingly, sets do not support indexing, slicing, or
2572other sequence-like behavior.
2573
Georg Brandl22b34312009-07-26 14:54:51 +00002574There are currently two built-in set types, :class:`set` and :class:`frozenset`.
Georg Brandl116aa622007-08-15 14:28:22 +00002575The :class:`set` type is mutable --- the contents can be changed using methods
2576like :meth:`add` and :meth:`remove`. Since it is mutable, it has no hash value
2577and cannot be used as either a dictionary key or as an element of another set.
Guido van Rossum2cc30da2007-11-02 23:46:40 +00002578The :class:`frozenset` type is immutable and :term:`hashable` --- its contents cannot be
Georg Brandl116aa622007-08-15 14:28:22 +00002579altered after it is created; it can therefore be used as a dictionary key or as
2580an element of another set.
2581
Georg Brandl99cd9572010-03-21 09:10:32 +00002582Non-empty sets (not frozensets) can be created by placing a comma-separated list
Georg Brandl53b95e72010-03-21 11:53:50 +00002583of elements within braces, for example: ``{'jack', 'sjoerd'}``, in addition to the
2584:class:`set` constructor.
Georg Brandl99cd9572010-03-21 09:10:32 +00002585
Georg Brandl116aa622007-08-15 14:28:22 +00002586The constructors for both classes work the same:
2587
2588.. class:: set([iterable])
2589 frozenset([iterable])
2590
2591 Return a new set or frozenset object whose elements are taken from
2592 *iterable*. The elements of a set must be hashable. To represent sets of
2593 sets, the inner sets must be :class:`frozenset` objects. If *iterable* is
2594 not specified, a new empty set is returned.
2595
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002596 Instances of :class:`set` and :class:`frozenset` provide the following
2597 operations:
Georg Brandl116aa622007-08-15 14:28:22 +00002598
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002599 .. describe:: len(s)
Georg Brandl116aa622007-08-15 14:28:22 +00002600
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002601 Return the cardinality of set *s*.
Georg Brandl116aa622007-08-15 14:28:22 +00002602
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002603 .. describe:: x in s
Georg Brandl116aa622007-08-15 14:28:22 +00002604
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002605 Test *x* for membership in *s*.
Georg Brandl116aa622007-08-15 14:28:22 +00002606
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002607 .. describe:: x not in s
Georg Brandl116aa622007-08-15 14:28:22 +00002608
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002609 Test *x* for non-membership in *s*.
Georg Brandl116aa622007-08-15 14:28:22 +00002610
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002611 .. method:: isdisjoint(other)
Guido van Rossum58da9312007-11-10 23:39:45 +00002612
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002613 Return True if the set has no elements in common with *other*. Sets are
Georg Brandl2ee470f2008-07-16 12:55:28 +00002614 disjoint if and only if their intersection is the empty set.
Guido van Rossum58da9312007-11-10 23:39:45 +00002615
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002616 .. method:: issubset(other)
2617 set <= other
Georg Brandl116aa622007-08-15 14:28:22 +00002618
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002619 Test whether every element in the set is in *other*.
Georg Brandl116aa622007-08-15 14:28:22 +00002620
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002621 .. method:: set < other
Georg Brandla6f52782007-09-01 15:49:30 +00002622
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002623 Test whether the set is a true subset of *other*, that is,
2624 ``set <= other and set != other``.
Georg Brandla6f52782007-09-01 15:49:30 +00002625
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002626 .. method:: issuperset(other)
2627 set >= other
Georg Brandl116aa622007-08-15 14:28:22 +00002628
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002629 Test whether every element in *other* is in the set.
Georg Brandl116aa622007-08-15 14:28:22 +00002630
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002631 .. method:: set > other
Georg Brandla6f52782007-09-01 15:49:30 +00002632
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002633 Test whether the set is a true superset of *other*, that is, ``set >=
2634 other and set != other``.
Georg Brandla6f52782007-09-01 15:49:30 +00002635
Georg Brandlc28e1fa2008-06-10 19:20:26 +00002636 .. method:: union(other, ...)
2637 set | other | ...
Georg Brandl116aa622007-08-15 14:28:22 +00002638
Benjamin Petersonb58dda72009-01-18 22:27:04 +00002639 Return a new set with elements from the set and all others.
Georg Brandl116aa622007-08-15 14:28:22 +00002640
Georg Brandlc28e1fa2008-06-10 19:20:26 +00002641 .. method:: intersection(other, ...)
2642 set & other & ...
Georg Brandl116aa622007-08-15 14:28:22 +00002643
Benjamin Petersonb58dda72009-01-18 22:27:04 +00002644 Return a new set with elements common to the set and all others.
Georg Brandl116aa622007-08-15 14:28:22 +00002645
Amaury Forgeot d'Arcfdfe62d2008-06-17 20:36:03 +00002646 .. method:: difference(other, ...)
2647 set - other - ...
Georg Brandlc28e1fa2008-06-10 19:20:26 +00002648
Amaury Forgeot d'Arcfdfe62d2008-06-17 20:36:03 +00002649 Return a new set with elements in the set that are not in the others.
Georg Brandl116aa622007-08-15 14:28:22 +00002650
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002651 .. method:: symmetric_difference(other)
2652 set ^ other
Georg Brandl116aa622007-08-15 14:28:22 +00002653
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002654 Return a new set with elements in either the set or *other* but not both.
Georg Brandl116aa622007-08-15 14:28:22 +00002655
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002656 .. method:: copy()
Georg Brandl116aa622007-08-15 14:28:22 +00002657
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002658 Return a new set with a shallow copy of *s*.
Georg Brandl116aa622007-08-15 14:28:22 +00002659
2660
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002661 Note, the non-operator versions of :meth:`union`, :meth:`intersection`,
2662 :meth:`difference`, and :meth:`symmetric_difference`, :meth:`issubset`, and
2663 :meth:`issuperset` methods will accept any iterable as an argument. In
2664 contrast, their operator based counterparts require their arguments to be
2665 sets. This precludes error-prone constructions like ``set('abc') & 'cbs'``
2666 in favor of the more readable ``set('abc').intersection('cbs')``.
Georg Brandl116aa622007-08-15 14:28:22 +00002667
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002668 Both :class:`set` and :class:`frozenset` support set to set comparisons. Two
2669 sets are equal if and only if every element of each set is contained in the
2670 other (each is a subset of the other). A set is less than another set if and
2671 only if the first set is a proper subset of the second set (is a subset, but
2672 is not equal). A set is greater than another set if and only if the first set
2673 is a proper superset of the second set (is a superset, but is not equal).
Georg Brandl116aa622007-08-15 14:28:22 +00002674
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002675 Instances of :class:`set` are compared to instances of :class:`frozenset`
2676 based on their members. For example, ``set('abc') == frozenset('abc')``
2677 returns ``True`` and so does ``set('abc') in set([frozenset('abc')])``.
Georg Brandl116aa622007-08-15 14:28:22 +00002678
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002679 The subset and equality comparisons do not generalize to a complete ordering
2680 function. For example, any two disjoint sets are not equal and are not
2681 subsets of each other, so *all* of the following return ``False``: ``a<b``,
Georg Brandl05f5ab72008-09-24 09:11:47 +00002682 ``a==b``, or ``a>b``.
Georg Brandl116aa622007-08-15 14:28:22 +00002683
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002684 Since sets only define partial ordering (subset relationships), the output of
2685 the :meth:`list.sort` method is undefined for lists of sets.
Georg Brandl116aa622007-08-15 14:28:22 +00002686
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002687 Set elements, like dictionary keys, must be :term:`hashable`.
Georg Brandl116aa622007-08-15 14:28:22 +00002688
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002689 Binary operations that mix :class:`set` instances with :class:`frozenset`
2690 return the type of the first operand. For example: ``frozenset('ab') |
2691 set('bc')`` returns an instance of :class:`frozenset`.
Georg Brandl116aa622007-08-15 14:28:22 +00002692
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002693 The following table lists operations available for :class:`set` that do not
2694 apply to immutable instances of :class:`frozenset`:
Georg Brandl116aa622007-08-15 14:28:22 +00002695
Georg Brandlc28e1fa2008-06-10 19:20:26 +00002696 .. method:: update(other, ...)
2697 set |= other | ...
Georg Brandl116aa622007-08-15 14:28:22 +00002698
Georg Brandla6053b42009-09-01 08:11:14 +00002699 Update the set, adding elements from all others.
Georg Brandl116aa622007-08-15 14:28:22 +00002700
Georg Brandlc28e1fa2008-06-10 19:20:26 +00002701 .. method:: intersection_update(other, ...)
2702 set &= other & ...
Georg Brandl116aa622007-08-15 14:28:22 +00002703
Georg Brandla6053b42009-09-01 08:11:14 +00002704 Update the set, keeping only elements found in it and all others.
Georg Brandl116aa622007-08-15 14:28:22 +00002705
Amaury Forgeot d'Arcfdfe62d2008-06-17 20:36:03 +00002706 .. method:: difference_update(other, ...)
2707 set -= other | ...
Georg Brandl116aa622007-08-15 14:28:22 +00002708
Amaury Forgeot d'Arcfdfe62d2008-06-17 20:36:03 +00002709 Update the set, removing elements found in others.
2710
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002711 .. method:: symmetric_difference_update(other)
2712 set ^= other
Georg Brandl116aa622007-08-15 14:28:22 +00002713
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002714 Update the set, keeping only elements found in either set, but not in both.
Georg Brandl116aa622007-08-15 14:28:22 +00002715
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002716 .. method:: add(elem)
Georg Brandl116aa622007-08-15 14:28:22 +00002717
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002718 Add element *elem* to the set.
Georg Brandl116aa622007-08-15 14:28:22 +00002719
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002720 .. method:: remove(elem)
Georg Brandl116aa622007-08-15 14:28:22 +00002721
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002722 Remove element *elem* from the set. Raises :exc:`KeyError` if *elem* is
2723 not contained in the set.
Georg Brandl116aa622007-08-15 14:28:22 +00002724
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002725 .. method:: discard(elem)
Georg Brandl116aa622007-08-15 14:28:22 +00002726
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002727 Remove element *elem* from the set if it is present.
Georg Brandl116aa622007-08-15 14:28:22 +00002728
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002729 .. method:: pop()
Georg Brandl116aa622007-08-15 14:28:22 +00002730
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002731 Remove and return an arbitrary element from the set. Raises
2732 :exc:`KeyError` if the set is empty.
Georg Brandl116aa622007-08-15 14:28:22 +00002733
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002734 .. method:: clear()
Georg Brandl116aa622007-08-15 14:28:22 +00002735
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002736 Remove all elements from the set.
Georg Brandl116aa622007-08-15 14:28:22 +00002737
2738
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002739 Note, the non-operator versions of the :meth:`update`,
2740 :meth:`intersection_update`, :meth:`difference_update`, and
2741 :meth:`symmetric_difference_update` methods will accept any iterable as an
2742 argument.
Georg Brandl116aa622007-08-15 14:28:22 +00002743
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002744 Note, the *elem* argument to the :meth:`__contains__`, :meth:`remove`, and
2745 :meth:`discard` methods may be a set. To support searching for an equivalent
2746 frozenset, the *elem* set is temporarily mutated during the search and then
2747 restored. During the search, the *elem* set should not be read or mutated
2748 since it does not have a meaningful value.
Benjamin Peterson699adb92008-05-08 22:27:58 +00002749
Georg Brandl116aa622007-08-15 14:28:22 +00002750
2751.. _typesmapping:
2752
2753Mapping Types --- :class:`dict`
2754===============================
2755
2756.. index::
2757 object: mapping
2758 object: dictionary
2759 triple: operations on; mapping; types
2760 triple: operations on; dictionary; type
2761 statement: del
2762 builtin: len
2763
Guido van Rossum2cc30da2007-11-02 23:46:40 +00002764A :dfn:`mapping` object maps :term:`hashable` values to arbitrary objects.
2765Mappings are mutable objects. There is currently only one standard mapping
2766type, the :dfn:`dictionary`. (For other containers see the built in
2767:class:`list`, :class:`set`, and :class:`tuple` classes, and the
2768:mod:`collections` module.)
Georg Brandl116aa622007-08-15 14:28:22 +00002769
Guido van Rossum2cc30da2007-11-02 23:46:40 +00002770A dictionary's keys are *almost* arbitrary values. Values that are not
2771:term:`hashable`, that is, values containing lists, dictionaries or other
2772mutable types (that are compared by value rather than by object identity) may
2773not be used as keys. Numeric types used for keys obey the normal rules for
2774numeric comparison: if two numbers compare equal (such as ``1`` and ``1.0``)
2775then they can be used interchangeably to index the same dictionary entry. (Note
2776however, that since computers store floating-point numbers as approximations it
2777is usually unwise to use them as dictionary keys.)
Georg Brandl116aa622007-08-15 14:28:22 +00002778
2779Dictionaries can be created by placing a comma-separated list of ``key: value``
2780pairs within braces, for example: ``{'jack': 4098, 'sjoerd': 4127}`` or ``{4098:
2781'jack', 4127: 'sjoerd'}``, or by the :class:`dict` constructor.
2782
2783.. class:: dict([arg])
2784
Georg Brandld22a8152007-09-04 17:43:37 +00002785 Return a new dictionary initialized from an optional positional argument or
2786 from a set of keyword arguments. If no arguments are given, return a new
2787 empty dictionary. If the positional argument *arg* is a mapping object,
2788 return a dictionary mapping the same keys to the same values as does the
2789 mapping object. Otherwise the positional argument must be a sequence, a
2790 container that supports iteration, or an iterator object. The elements of
2791 the argument must each also be of one of those kinds, and each must in turn
2792 contain exactly two objects. The first is used as a key in the new
2793 dictionary, and the second as the key's value. If a given key is seen more
2794 than once, the last value associated with it is retained in the new
2795 dictionary.
Georg Brandl116aa622007-08-15 14:28:22 +00002796
2797 If keyword arguments are given, the keywords themselves with their associated
Georg Brandld22a8152007-09-04 17:43:37 +00002798 values are added as items to the dictionary. If a key is specified both in
2799 the positional argument and as a keyword argument, the value associated with
2800 the keyword is retained in the dictionary. For example, these all return a
Georg Brandlc16e8f12010-10-17 11:23:56 +00002801 dictionary equal to ``{"one": 1, "two": 2}``:
Georg Brandl116aa622007-08-15 14:28:22 +00002802
Georg Brandlc16e8f12010-10-17 11:23:56 +00002803 * ``dict(one=1, two=2)``
2804 * ``dict({'one': 1, 'two': 2})``
2805 * ``dict(zip(('one', 'two'), (1, 2)))``
2806 * ``dict([['two', 2], ['one', 1]])``
Georg Brandl116aa622007-08-15 14:28:22 +00002807
Georg Brandld22a8152007-09-04 17:43:37 +00002808 The first example only works for keys that are valid Python identifiers; the
2809 others work with any valid keys.
Georg Brandl116aa622007-08-15 14:28:22 +00002810
Georg Brandl116aa622007-08-15 14:28:22 +00002811
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002812 These are the operations that dictionaries support (and therefore, custom
2813 mapping types should support too):
Georg Brandl116aa622007-08-15 14:28:22 +00002814
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002815 .. describe:: len(d)
Georg Brandl116aa622007-08-15 14:28:22 +00002816
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002817 Return the number of items in the dictionary *d*.
Georg Brandl116aa622007-08-15 14:28:22 +00002818
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002819 .. describe:: d[key]
Georg Brandl116aa622007-08-15 14:28:22 +00002820
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002821 Return the item of *d* with key *key*. Raises a :exc:`KeyError` if *key* is
2822 not in the map.
Georg Brandl48310cd2009-01-03 21:18:54 +00002823
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002824 If a subclass of dict defines a method :meth:`__missing__`, if the key *key*
2825 is not present, the ``d[key]`` operation calls that method with the key *key*
2826 as argument. The ``d[key]`` operation then returns or raises whatever is
2827 returned or raised by the ``__missing__(key)`` call if the key is not
2828 present. No other operations or methods invoke :meth:`__missing__`. If
2829 :meth:`__missing__` is not defined, :exc:`KeyError` is raised.
Raymond Hettinger5254e972011-01-08 09:35:38 +00002830 :meth:`__missing__` must be a method; it cannot be an instance variable::
2831
2832 >>> class Counter(dict):
2833 ... def __missing__(self, key):
2834 ... return 0
2835 >>> c = Counter()
2836 >>> c['red']
2837 0
2838 >>> c['red'] += 1
2839 >>> c['red']
2840 1
2841
2842 See :class:`collections.Counter` for a complete implementation including
2843 other methods helpful for accumulating and managing tallies.
Georg Brandl116aa622007-08-15 14:28:22 +00002844
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002845 .. describe:: d[key] = value
Georg Brandl116aa622007-08-15 14:28:22 +00002846
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002847 Set ``d[key]`` to *value*.
Georg Brandl116aa622007-08-15 14:28:22 +00002848
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002849 .. describe:: del d[key]
Georg Brandl116aa622007-08-15 14:28:22 +00002850
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002851 Remove ``d[key]`` from *d*. Raises a :exc:`KeyError` if *key* is not in the
2852 map.
Georg Brandl116aa622007-08-15 14:28:22 +00002853
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002854 .. describe:: key in d
Georg Brandl116aa622007-08-15 14:28:22 +00002855
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002856 Return ``True`` if *d* has a key *key*, else ``False``.
Georg Brandl116aa622007-08-15 14:28:22 +00002857
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002858 .. describe:: key not in d
Georg Brandl116aa622007-08-15 14:28:22 +00002859
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002860 Equivalent to ``not key in d``.
Georg Brandl116aa622007-08-15 14:28:22 +00002861
Benjamin Petersond23f8222009-04-05 19:13:16 +00002862 .. describe:: iter(d)
2863
2864 Return an iterator over the keys of the dictionary. This is a shortcut
Georg Brandlede6c2a2010-01-05 10:22:04 +00002865 for ``iter(d.keys())``.
Benjamin Petersond23f8222009-04-05 19:13:16 +00002866
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002867 .. method:: clear()
Georg Brandl116aa622007-08-15 14:28:22 +00002868
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002869 Remove all items from the dictionary.
Georg Brandl116aa622007-08-15 14:28:22 +00002870
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002871 .. method:: copy()
Georg Brandl116aa622007-08-15 14:28:22 +00002872
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002873 Return a shallow copy of the dictionary.
Georg Brandl116aa622007-08-15 14:28:22 +00002874
Georg Brandlabc38772009-04-12 15:51:51 +00002875 .. classmethod:: fromkeys(seq[, value])
Georg Brandl116aa622007-08-15 14:28:22 +00002876
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002877 Create a new dictionary with keys from *seq* and values set to *value*.
Georg Brandl116aa622007-08-15 14:28:22 +00002878
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002879 :meth:`fromkeys` is a class method that returns a new dictionary. *value*
2880 defaults to ``None``.
Georg Brandl116aa622007-08-15 14:28:22 +00002881
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002882 .. method:: get(key[, default])
Georg Brandl116aa622007-08-15 14:28:22 +00002883
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002884 Return the value for *key* if *key* is in the dictionary, else *default*.
2885 If *default* is not given, it defaults to ``None``, so that this method
2886 never raises a :exc:`KeyError`.
Georg Brandl116aa622007-08-15 14:28:22 +00002887
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002888 .. method:: items()
Georg Brandl116aa622007-08-15 14:28:22 +00002889
Victor Stinner0db176f2012-04-16 00:16:30 +02002890 Return a new view of the dictionary's items (``(key, value)`` pairs).
2891 See the :ref:`documentation of view objects <dict-views>`.
Georg Brandl116aa622007-08-15 14:28:22 +00002892
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002893 .. method:: keys()
Georg Brandl116aa622007-08-15 14:28:22 +00002894
Victor Stinner0db176f2012-04-16 00:16:30 +02002895 Return a new view of the dictionary's keys. See the :ref:`documentation
2896 of view objects <dict-views>`.
Georg Brandl116aa622007-08-15 14:28:22 +00002897
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002898 .. method:: pop(key[, default])
Georg Brandl116aa622007-08-15 14:28:22 +00002899
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002900 If *key* is in the dictionary, remove it and return its value, else return
2901 *default*. If *default* is not given and *key* is not in the dictionary,
2902 a :exc:`KeyError` is raised.
Georg Brandl116aa622007-08-15 14:28:22 +00002903
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002904 .. method:: popitem()
Georg Brandl116aa622007-08-15 14:28:22 +00002905
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002906 Remove and return an arbitrary ``(key, value)`` pair from the dictionary.
Georg Brandl116aa622007-08-15 14:28:22 +00002907
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002908 :meth:`popitem` is useful to destructively iterate over a dictionary, as
2909 often used in set algorithms. If the dictionary is empty, calling
2910 :meth:`popitem` raises a :exc:`KeyError`.
Georg Brandl116aa622007-08-15 14:28:22 +00002911
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002912 .. method:: setdefault(key[, default])
Georg Brandl116aa622007-08-15 14:28:22 +00002913
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002914 If *key* is in the dictionary, return its value. If not, insert *key*
2915 with a value of *default* and return *default*. *default* defaults to
2916 ``None``.
Georg Brandl116aa622007-08-15 14:28:22 +00002917
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002918 .. method:: update([other])
Georg Brandl116aa622007-08-15 14:28:22 +00002919
Éric Araujo0fc86b82010-08-18 22:29:54 +00002920 Update the dictionary with the key/value pairs from *other*, overwriting
2921 existing keys. Return ``None``.
Georg Brandl116aa622007-08-15 14:28:22 +00002922
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002923 :meth:`update` accepts either another dictionary object or an iterable of
Georg Brandlfda21062010-09-25 16:56:36 +00002924 key/value pairs (as tuples or other iterables of length two). If keyword
Benjamin Peterson8719ad52009-09-11 22:24:02 +00002925 arguments are specified, the dictionary is then updated with those
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002926 key/value pairs: ``d.update(red=1, blue=2)``.
Georg Brandl116aa622007-08-15 14:28:22 +00002927
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002928 .. method:: values()
Georg Brandl116aa622007-08-15 14:28:22 +00002929
Victor Stinner0db176f2012-04-16 00:16:30 +02002930 Return a new view of the dictionary's values. See the
2931 :ref:`documentation of view objects <dict-views>`.
2932
2933.. seealso::
2934 :class:`types.MappingProxyType` can be used to create a read-only view
2935 of a :class:`dict`.
Georg Brandld22a8152007-09-04 17:43:37 +00002936
2937
Benjamin Peterson44309e62008-11-22 00:41:45 +00002938.. _dict-views:
2939
Georg Brandld22a8152007-09-04 17:43:37 +00002940Dictionary view objects
2941-----------------------
2942
2943The objects returned by :meth:`dict.keys`, :meth:`dict.values` and
2944:meth:`dict.items` are *view objects*. They provide a dynamic view on the
2945dictionary's entries, which means that when the dictionary changes, the view
Benjamin Petersonce0506c2008-11-17 21:47:41 +00002946reflects these changes.
Georg Brandld22a8152007-09-04 17:43:37 +00002947
2948Dictionary views can be iterated over to yield their respective data, and
2949support membership tests:
2950
2951.. describe:: len(dictview)
2952
2953 Return the number of entries in the dictionary.
2954
2955.. describe:: iter(dictview)
2956
2957 Return an iterator over the keys, values or items (represented as tuples of
2958 ``(key, value)``) in the dictionary.
2959
2960 Keys and values are iterated over in an arbitrary order which is non-random,
2961 varies across Python implementations, and depends on the dictionary's history
2962 of insertions and deletions. If keys, values and items views are iterated
2963 over with no intervening modifications to the dictionary, the order of items
2964 will directly correspond. This allows the creation of ``(value, key)`` pairs
2965 using :func:`zip`: ``pairs = zip(d.values(), d.keys())``. Another way to
2966 create the same list is ``pairs = [(v, k) for (k, v) in d.items()]``.
2967
Georg Brandl81269142009-05-17 08:31:29 +00002968 Iterating views while adding or deleting entries in the dictionary may raise
2969 a :exc:`RuntimeError` or fail to iterate over all entries.
Benjamin Petersond23f8222009-04-05 19:13:16 +00002970
Georg Brandld22a8152007-09-04 17:43:37 +00002971.. describe:: x in dictview
2972
2973 Return ``True`` if *x* is in the underlying dictionary's keys, values or
2974 items (in the latter case, *x* should be a ``(key, value)`` tuple).
2975
2976
Benjamin Petersonce0506c2008-11-17 21:47:41 +00002977Keys views are set-like since their entries are unique and hashable. If all
Georg Brandlf74cf772010-10-15 16:03:02 +00002978values are hashable, so that ``(key, value)`` pairs are unique and hashable,
2979then the items view is also set-like. (Values views are not treated as set-like
2980since the entries are generally not unique.) For set-like views, all of the
Nick Coghlan273069c2012-08-20 17:14:07 +10002981operations defined for the abstract base class :class:`collections.abc.Set` are
Georg Brandlf74cf772010-10-15 16:03:02 +00002982available (for example, ``==``, ``<``, or ``^``).
Georg Brandl116aa622007-08-15 14:28:22 +00002983
Georg Brandlc53c9662007-09-04 17:58:02 +00002984An example of dictionary view usage::
2985
2986 >>> dishes = {'eggs': 2, 'sausage': 1, 'bacon': 1, 'spam': 500}
2987 >>> keys = dishes.keys()
2988 >>> values = dishes.values()
2989
2990 >>> # iteration
2991 >>> n = 0
2992 >>> for val in values:
2993 ... n += val
2994 >>> print(n)
2995 504
2996
2997 >>> # keys and values are iterated over in the same order
2998 >>> list(keys)
2999 ['eggs', 'bacon', 'sausage', 'spam']
3000 >>> list(values)
3001 [2, 1, 1, 500]
3002
3003 >>> # view objects are dynamic and reflect dict changes
3004 >>> del dishes['eggs']
3005 >>> del dishes['sausage']
3006 >>> list(keys)
3007 ['spam', 'bacon']
3008
3009 >>> # set operations
3010 >>> keys & {'eggs', 'bacon', 'salad'}
Gregory P. Smithe8388122008-09-04 04:18:09 +00003011 {'bacon'}
Georg Brandlf74cf772010-10-15 16:03:02 +00003012 >>> keys ^ {'sausage', 'juice'}
Sandro Tosi2a8d1952011-08-02 18:42:04 +02003013 {'juice', 'sausage', 'bacon', 'spam'}
Georg Brandlc53c9662007-09-04 17:58:02 +00003014
3015
Georg Brandl116aa622007-08-15 14:28:22 +00003016.. _typecontextmanager:
3017
3018Context Manager Types
3019=====================
3020
Georg Brandl116aa622007-08-15 14:28:22 +00003021.. index::
3022 single: context manager
3023 single: context management protocol
3024 single: protocol; context management
3025
3026Python's :keyword:`with` statement supports the concept of a runtime context
Antoine Pitroua6540902010-12-12 20:09:18 +00003027defined by a context manager. This is implemented using a pair of methods
Georg Brandl116aa622007-08-15 14:28:22 +00003028that allow user-defined classes to define a runtime context that is entered
Antoine Pitroua6540902010-12-12 20:09:18 +00003029before the statement body is executed and exited when the statement ends:
Georg Brandl116aa622007-08-15 14:28:22 +00003030
3031
3032.. method:: contextmanager.__enter__()
3033
3034 Enter the runtime context and return either this object or another object
3035 related to the runtime context. The value returned by this method is bound to
3036 the identifier in the :keyword:`as` clause of :keyword:`with` statements using
3037 this context manager.
3038
Antoine Pitrou11cb9612010-09-15 11:11:28 +00003039 An example of a context manager that returns itself is a :term:`file object`.
3040 File objects return themselves from __enter__() to allow :func:`open` to be
3041 used as the context expression in a :keyword:`with` statement.
Georg Brandl116aa622007-08-15 14:28:22 +00003042
3043 An example of a context manager that returns a related object is the one
Christian Heimesfaf2f632008-01-06 16:59:19 +00003044 returned by :func:`decimal.localcontext`. These managers set the active
Georg Brandl116aa622007-08-15 14:28:22 +00003045 decimal context to a copy of the original decimal context and then return the
3046 copy. This allows changes to be made to the current decimal context in the body
3047 of the :keyword:`with` statement without affecting code outside the
3048 :keyword:`with` statement.
3049
3050
3051.. method:: contextmanager.__exit__(exc_type, exc_val, exc_tb)
3052
Georg Brandl9afde1c2007-11-01 20:32:30 +00003053 Exit the runtime context and return a Boolean flag indicating if any exception
Georg Brandl116aa622007-08-15 14:28:22 +00003054 that occurred should be suppressed. If an exception occurred while executing the
3055 body of the :keyword:`with` statement, the arguments contain the exception type,
3056 value and traceback information. Otherwise, all three arguments are ``None``.
3057
3058 Returning a true value from this method will cause the :keyword:`with` statement
3059 to suppress the exception and continue execution with the statement immediately
3060 following the :keyword:`with` statement. Otherwise the exception continues
3061 propagating after this method has finished executing. Exceptions that occur
3062 during execution of this method will replace any exception that occurred in the
3063 body of the :keyword:`with` statement.
3064
3065 The exception passed in should never be reraised explicitly - instead, this
3066 method should return a false value to indicate that the method completed
3067 successfully and does not want to suppress the raised exception. This allows
3068 context management code (such as ``contextlib.nested``) to easily detect whether
3069 or not an :meth:`__exit__` method has actually failed.
3070
3071Python defines several context managers to support easy thread synchronisation,
3072prompt closure of files or other objects, and simpler manipulation of the active
3073decimal arithmetic context. The specific types are not treated specially beyond
3074their implementation of the context management protocol. See the
3075:mod:`contextlib` module for some examples.
3076
Antoine Pitroua6540902010-12-12 20:09:18 +00003077Python's :term:`generator`\s and the :class:`contextlib.contextmanager` decorator
Christian Heimesd8654cf2007-12-02 15:22:16 +00003078provide a convenient way to implement these protocols. If a generator function is
Antoine Pitroua6540902010-12-12 20:09:18 +00003079decorated with the :class:`contextlib.contextmanager` decorator, it will return a
Georg Brandl116aa622007-08-15 14:28:22 +00003080context manager implementing the necessary :meth:`__enter__` and
3081:meth:`__exit__` methods, rather than the iterator produced by an undecorated
3082generator function.
3083
3084Note that there is no specific slot for any of these methods in the type
3085structure for Python objects in the Python/C API. Extension types wanting to
3086define these methods must provide them as a normal Python accessible method.
3087Compared to the overhead of setting up the runtime context, the overhead of a
3088single class dictionary lookup is negligible.
3089
3090
3091.. _typesother:
3092
3093Other Built-in Types
3094====================
3095
3096The interpreter supports several other kinds of objects. Most of these support
3097only one or two operations.
3098
3099
3100.. _typesmodules:
3101
3102Modules
3103-------
3104
3105The only special operation on a module is attribute access: ``m.name``, where
3106*m* is a module and *name* accesses a name defined in *m*'s symbol table.
3107Module attributes can be assigned to. (Note that the :keyword:`import`
3108statement is not, strictly speaking, an operation on a module object; ``import
3109foo`` does not require a module object named *foo* to exist, rather it requires
3110an (external) *definition* for a module named *foo* somewhere.)
3111
Senthil Kumarana6bac952011-07-04 11:28:30 -07003112A special attribute of every module is :attr:`__dict__`. This is the dictionary
Georg Brandl116aa622007-08-15 14:28:22 +00003113containing the module's symbol table. Modifying this dictionary will actually
3114change the module's symbol table, but direct assignment to the :attr:`__dict__`
3115attribute is not possible (you can write ``m.__dict__['a'] = 1``, which defines
3116``m.a`` to be ``1``, but you can't write ``m.__dict__ = {}``). Modifying
3117:attr:`__dict__` directly is not recommended.
3118
3119Modules built into the interpreter are written like this: ``<module 'sys'
3120(built-in)>``. If loaded from a file, they are written as ``<module 'os' from
3121'/usr/local/lib/pythonX.Y/os.pyc'>``.
3122
3123
3124.. _typesobjects:
3125
3126Classes and Class Instances
3127---------------------------
3128
3129See :ref:`objects` and :ref:`class` for these.
3130
3131
3132.. _typesfunctions:
3133
3134Functions
3135---------
3136
3137Function objects are created by function definitions. The only operation on a
3138function object is to call it: ``func(argument-list)``.
3139
3140There are really two flavors of function objects: built-in functions and
3141user-defined functions. Both support the same operation (to call the function),
3142but the implementation is different, hence the different object types.
3143
3144See :ref:`function` for more information.
3145
3146
3147.. _typesmethods:
3148
3149Methods
3150-------
3151
3152.. index:: object: method
3153
3154Methods are functions that are called using the attribute notation. There are
3155two flavors: built-in methods (such as :meth:`append` on lists) and class
3156instance methods. Built-in methods are described with the types that support
3157them.
3158
Georg Brandl2e0b7552007-11-27 12:43:08 +00003159If you access a method (a function defined in a class namespace) through an
3160instance, you get a special object: a :dfn:`bound method` (also called
3161:dfn:`instance method`) object. When called, it will add the ``self`` argument
3162to the argument list. Bound methods have two special read-only attributes:
3163``m.__self__`` is the object on which the method operates, and ``m.__func__`` is
3164the function implementing the method. Calling ``m(arg-1, arg-2, ..., arg-n)``
3165is completely equivalent to calling ``m.__func__(m.__self__, arg-1, arg-2, ...,
3166arg-n)``.
Georg Brandl116aa622007-08-15 14:28:22 +00003167
Georg Brandl2e0b7552007-11-27 12:43:08 +00003168Like function objects, bound method objects support getting arbitrary
3169attributes. However, since method attributes are actually stored on the
3170underlying function object (``meth.__func__``), setting method attributes on
3171bound methods is disallowed. Attempting to set a method attribute results in a
Georg Brandl116aa622007-08-15 14:28:22 +00003172:exc:`TypeError` being raised. In order to set a method attribute, you need to
3173explicitly set it on the underlying function object::
3174
3175 class C:
3176 def method(self):
3177 pass
3178
3179 c = C()
Christian Heimesff737952007-11-27 10:40:20 +00003180 c.method.__func__.whoami = 'my name is c'
Georg Brandl116aa622007-08-15 14:28:22 +00003181
3182See :ref:`types` for more information.
3183
3184
3185.. _bltin-code-objects:
3186
3187Code Objects
3188------------
3189
3190.. index:: object: code
3191
3192.. index::
3193 builtin: compile
3194 single: __code__ (function object attribute)
3195
3196Code objects are used by the implementation to represent "pseudo-compiled"
3197executable Python code such as a function body. They differ from function
3198objects because they don't contain a reference to their global execution
3199environment. Code objects are returned by the built-in :func:`compile` function
3200and can be extracted from function objects through their :attr:`__code__`
3201attribute. See also the :mod:`code` module.
3202
3203.. index::
3204 builtin: exec
3205 builtin: eval
3206
3207A code object can be executed or evaluated by passing it (instead of a source
3208string) to the :func:`exec` or :func:`eval` built-in functions.
3209
3210See :ref:`types` for more information.
3211
3212
3213.. _bltin-type-objects:
3214
3215Type Objects
3216------------
3217
3218.. index::
3219 builtin: type
3220 module: types
3221
3222Type objects represent the various object types. An object's type is accessed
3223by the built-in function :func:`type`. There are no special operations on
3224types. The standard module :mod:`types` defines names for all standard built-in
3225types.
3226
Martin v. Löwis250ad612008-04-07 05:43:42 +00003227Types are written like this: ``<class 'int'>``.
Georg Brandl116aa622007-08-15 14:28:22 +00003228
3229
3230.. _bltin-null-object:
3231
3232The Null Object
3233---------------
3234
3235This object is returned by functions that don't explicitly return a value. It
3236supports no special operations. There is exactly one null object, named
Benjamin Peterson98f2b9b2011-07-30 12:26:27 -05003237``None`` (a built-in name). ``type(None)()`` produces the same singleton.
Georg Brandl116aa622007-08-15 14:28:22 +00003238
3239It is written as ``None``.
3240
3241
3242.. _bltin-ellipsis-object:
3243
3244The Ellipsis Object
3245-------------------
3246
Benjamin Petersond5a1c442012-05-14 22:09:31 -07003247This object is commonly used by slicing (see :ref:`slicings`). It supports no
3248special operations. There is exactly one ellipsis object, named
3249:const:`Ellipsis` (a built-in name). ``type(Ellipsis)()`` produces the
3250:const:`Ellipsis` singleton.
Georg Brandl116aa622007-08-15 14:28:22 +00003251
3252It is written as ``Ellipsis`` or ``...``.
3253
3254
Éric Araujo18ddf822011-09-01 23:10:36 +02003255.. _bltin-notimplemented-object:
3256
Benjamin Peterson50211fa2011-07-30 09:57:24 -05003257The NotImplemented Object
3258-------------------------
3259
3260This object is returned from comparisons and binary operations when they are
3261asked to operate on types they don't support. See :ref:`comparisons` for more
Benjamin Peterson98f2b9b2011-07-30 12:26:27 -05003262information. There is exactly one ``NotImplemented`` object.
3263``type(NotImplemented)()`` produces the singleton instance.
Benjamin Peterson50211fa2011-07-30 09:57:24 -05003264
3265It is written as ``NotImplemented``.
3266
Georg Brandl116aa622007-08-15 14:28:22 +00003267
Éric Araujo18ddf822011-09-01 23:10:36 +02003268.. _bltin-boolean-values:
3269
Georg Brandl116aa622007-08-15 14:28:22 +00003270Boolean Values
3271--------------
3272
3273Boolean values are the two constant objects ``False`` and ``True``. They are
3274used to represent truth values (although other values can also be considered
3275false or true). In numeric contexts (for example when used as the argument to
3276an arithmetic operator), they behave like the integers 0 and 1, respectively.
Ezio Melottic1f26f62011-12-02 19:47:24 +02003277The built-in function :func:`bool` can be used to convert any value to a
3278Boolean, if the value can be interpreted as a truth value (see section
3279:ref:`truth` above).
Georg Brandl116aa622007-08-15 14:28:22 +00003280
3281.. index::
3282 single: False
3283 single: True
3284 pair: Boolean; values
3285
3286They are written as ``False`` and ``True``, respectively.
3287
3288
3289.. _typesinternal:
3290
3291Internal Objects
3292----------------
3293
3294See :ref:`types` for this information. It describes stack frame objects,
3295traceback objects, and slice objects.
3296
3297
3298.. _specialattrs:
3299
3300Special Attributes
3301==================
3302
3303The implementation adds a few special read-only attributes to several object
3304types, where they are relevant. Some of these are not reported by the
3305:func:`dir` built-in function.
3306
3307
3308.. attribute:: object.__dict__
3309
3310 A dictionary or other mapping object used to store an object's (writable)
3311 attributes.
3312
3313
3314.. attribute:: instance.__class__
3315
3316 The class to which a class instance belongs.
3317
3318
3319.. attribute:: class.__bases__
3320
Benjamin Peterson1baf4652009-12-31 03:11:23 +00003321 The tuple of base classes of a class object.
Georg Brandl116aa622007-08-15 14:28:22 +00003322
3323
3324.. attribute:: class.__name__
3325
3326 The name of the class or type.
3327
Georg Brandl7a51e582009-03-28 19:13:21 +00003328
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003329.. attribute:: class.__qualname__
3330
3331 The :term:`qualified name` of the class or type.
3332
3333 .. versionadded:: 3.3
3334
3335
Benjamin Petersond23f8222009-04-05 19:13:16 +00003336.. attribute:: class.__mro__
3337
3338 This attribute is a tuple of classes that are considered when looking for
3339 base classes during method resolution.
3340
3341
3342.. method:: class.mro()
3343
3344 This method can be overridden by a metaclass to customize the method
3345 resolution order for its instances. It is called at class instantiation, and
3346 its result is stored in :attr:`__mro__`.
3347
3348
Georg Brandl7a51e582009-03-28 19:13:21 +00003349.. method:: class.__subclasses__
3350
Florent Xicluna74e64952011-10-28 11:21:19 +02003351 Each class keeps a list of weak references to its immediate subclasses. This
3352 method returns a list of all those references still alive.
Benjamin Petersond23f8222009-04-05 19:13:16 +00003353 Example::
Georg Brandl7a51e582009-03-28 19:13:21 +00003354
3355 >>> int.__subclasses__()
Florent Xicluna74e64952011-10-28 11:21:19 +02003356 [<class 'bool'>]
Georg Brandl7a51e582009-03-28 19:13:21 +00003357
3358
Georg Brandl116aa622007-08-15 14:28:22 +00003359.. rubric:: Footnotes
3360
Ezio Melotti0656a562011-08-15 14:27:19 +03003361.. [1] Additional information on these special methods may be found in the Python
Georg Brandl116aa622007-08-15 14:28:22 +00003362 Reference Manual (:ref:`customization`).
3363
Ezio Melotti0656a562011-08-15 14:27:19 +03003364.. [2] As a consequence, the list ``[1, 2]`` is considered equal to ``[1.0, 2.0]``, and
Georg Brandl116aa622007-08-15 14:28:22 +00003365 similarly for tuples.
3366
Ezio Melotti0656a562011-08-15 14:27:19 +03003367.. [3] They must have since the parser can't tell the type of the operands.
Georg Brandl116aa622007-08-15 14:28:22 +00003368
Ezio Melotti0656a562011-08-15 14:27:19 +03003369.. [4] Cased characters are those with general category property being one of
3370 "Lu" (Letter, uppercase), "Ll" (Letter, lowercase), or "Lt" (Letter, titlecase).
3371
3372.. [5] To format only a tuple you should therefore provide a singleton tuple whose only
Georg Brandl116aa622007-08-15 14:28:22 +00003373 element is the tuple to be formatted.