1 .. XXX: reference/datamodel and this have quite a few overlaps!
10 The following sections describe the standard types that are built into the
15 Historically (until release 2.2), Python's built-in types have differed from
16 user-defined types because it was not possible to use the built-in types as the
17 basis for object-oriented inheritance. This limitation no longer
20 .. index:: pair: built-in; types
22 The principal built-in types are numerics, sequences, mappings, files, classes,
23 instances and exceptions.
25 .. index:: statement: print
27 Some operations are supported by several object types; in particular,
28 practically all objects can be compared, tested for truth value, and converted
29 to a string (with the :func:`repr` function or the slightly different
30 :func:`str` function). The latter function is implicitly used when an object is
31 written by the :func:`print` function.
43 pair: Boolean; operations
46 Any object can be tested for truth value, for use in an :keyword:`if` or
47 :keyword:`while` condition or as operand of the Boolean operations below. The
48 following values are considered false:
50 .. index:: single: None (Built-in object)
54 .. index:: single: False (Built-in object)
58 * zero of any numeric type, for example, ``0``, ``0L``, ``0.0``, ``0j``.
60 * any empty sequence, for example, ``''``, ``()``, ``[]``.
62 * any empty mapping, for example, ``{}``.
64 * instances of user-defined classes, if the class defines a :meth:`__nonzero__`
65 or :meth:`__len__` method, when that method returns the integer zero or
66 :class:`bool` value ``False``. [#]_
68 .. index:: single: true
70 All other values are considered true --- so objects of many types are always
79 Operations and built-in functions that have a Boolean result always return ``0``
80 or ``False`` for false and ``1`` or ``True`` for true, unless otherwise stated.
81 (Important exception: the Boolean operations ``or`` and ``and`` always return
82 one of their operands.)
87 Boolean Operations --- :keyword:`and`, :keyword:`or`, :keyword:`not`
88 ====================================================================
90 .. index:: pair: Boolean; operations
92 These are the Boolean operations, ordered by ascending priority:
94 +-------------+---------------------------------+-------+
95 | Operation | Result | Notes |
96 +=============+=================================+=======+
97 | ``x or y`` | if *x* is false, then *y*, else | \(1) |
99 +-------------+---------------------------------+-------+
100 | ``x and y`` | if *x* is false, then *x*, else | \(2) |
102 +-------------+---------------------------------+-------+
103 | ``not x`` | if *x* is false, then ``True``, | \(3) |
104 | | else ``False`` | |
105 +-------------+---------------------------------+-------+
115 This is a short-circuit operator, so it only evaluates the second
116 argument if the first one is :const:`False`.
119 This is a short-circuit operator, so it only evaluates the second
120 argument if the first one is :const:`True`.
123 ``not`` has a lower priority than non-Boolean operators, so ``not a == b`` is
124 interpreted as ``not (a == b)``, and ``a == not b`` is a syntax error.
132 .. index:: pair: chaining; comparisons
134 Comparison operations are supported by all objects. They all have the same
135 priority (which is higher than that of the Boolean operations). Comparisons can
136 be chained arbitrarily; for example, ``x < y <= z`` is equivalent to ``x < y and
137 y <= z``, except that *y* is evaluated only once (but in both cases *z* is not
138 evaluated at all when ``x < y`` is found to be false).
140 This table summarizes the comparison operations:
142 +------------+-------------------------+-------+
143 | Operation | Meaning | Notes |
144 +============+=========================+=======+
145 | ``<`` | strictly less than | |
146 +------------+-------------------------+-------+
147 | ``<=`` | less than or equal | |
148 +------------+-------------------------+-------+
149 | ``>`` | strictly greater than | |
150 +------------+-------------------------+-------+
151 | ``>=`` | greater than or equal | |
152 +------------+-------------------------+-------+
154 +------------+-------------------------+-------+
155 | ``!=`` | not equal | \(1) |
156 +------------+-------------------------+-------+
157 | ``is`` | object identity | |
158 +------------+-------------------------+-------+
159 | ``is not`` | negated object identity | |
160 +------------+-------------------------+-------+
163 pair: operator; comparison
176 ``!=`` can also be written ``<>``, but this is an obsolete usage
177 kept for backwards compatibility only. New code should always use
181 pair: object; numeric
182 pair: objects; comparing
184 Objects of different types, except different numeric types and different string
185 types, never compare equal; such objects are ordered consistently but
186 arbitrarily (so that sorting a heterogeneous array yields a consistent result).
187 Furthermore, some types (for example, file objects) support only a degenerate
188 notion of comparison where any two objects of that type are unequal. Again,
189 such objects are ordered arbitrarily but consistently. The ``<``, ``<=``, ``>``
190 and ``>=`` operators will raise a :exc:`TypeError` exception when any operand is
193 .. index:: single: __cmp__() (instance method)
195 Instances of a class normally compare as non-equal unless the class defines the
196 :meth:`__cmp__` method. Refer to :ref:`customization`) for information on the
197 use of this method to effect object comparisons.
199 **Implementation note:** Objects of different types except numbers are ordered
200 by their type names; objects of the same types that don't support proper
201 comparison are ordered by their address.
207 Two more operations with the same syntactic priority, ``in`` and ``not in``, are
208 supported only by sequence types (below).
213 Numeric Types --- :class:`int`, :class:`float`, :class:`long`, :class:`complex`
214 ===============================================================================
221 object: floating point
222 object: complex number
225 There are four distinct numeric types: :dfn:`plain integers`, :dfn:`long
226 integers`, :dfn:`floating point numbers`, and :dfn:`complex numbers`. In
227 addition, Booleans are a subtype of plain integers. Plain integers (also just
228 called :dfn:`integers`) are implemented using :ctype:`long` in C, which gives
229 them at least 32 bits of precision (``sys.maxint`` is always set to the maximum
230 plain integer value for the current platform, the minimum value is
231 ``-sys.maxint - 1``). Long integers have unlimited precision. Floating point
232 numbers are implemented using :ctype:`double` in C. All bets on their precision
233 are off unless you happen to know the machine you are working with.
235 Complex numbers have a real and imaginary part, which are each implemented using
236 :ctype:`double` in C. To extract these parts from a complex number *z*, use
237 ``z.real`` and ``z.imag``.
240 pair: numeric; literals
241 pair: integer; literals
242 triple: long; integer; literals
243 pair: floating point; literals
244 pair: complex number; literals
245 pair: hexadecimal; literals
246 pair: octal; literals
248 Numbers are created by numeric literals or as the result of built-in functions
249 and operators. Unadorned integer literals (including binary, hex, and octal
250 numbers) yield plain integers unless the value they denote is too large to be
251 represented as a plain integer, in which case they yield a long integer.
252 Integer literals with an ``'L'`` or ``'l'`` suffix yield long integers (``'L'``
253 is preferred because ``1l`` looks too much like eleven!). Numeric literals
254 containing a decimal point or an exponent sign yield floating point numbers.
255 Appending ``'j'`` or ``'J'`` to a numeric literal yields a complex number with a
256 zero real part. A complex numeric literal is the sum of a real and an imaginary
266 Python fully supports mixed arithmetic: when a binary arithmetic operator has
267 operands of different numeric types, the operand with the "narrower" type is
268 widened to that of the other, where plain integer is narrower than long integer
269 is narrower than floating point is narrower than complex. Comparisons between
270 numbers of mixed type use the same rule. [#]_ The constructors :func:`int`,
271 :func:`long`, :func:`float`, and :func:`complex` can be used to produce numbers
274 All builtin numeric types support the following operations. See
275 :ref:`power` and later sections for the operators' priorities.
277 +--------------------+---------------------------------+--------+
278 | Operation | Result | Notes |
279 +====================+=================================+========+
280 | ``x + y`` | sum of *x* and *y* | |
281 +--------------------+---------------------------------+--------+
282 | ``x - y`` | difference of *x* and *y* | |
283 +--------------------+---------------------------------+--------+
284 | ``x * y`` | product of *x* and *y* | |
285 +--------------------+---------------------------------+--------+
286 | ``x / y`` | quotient of *x* and *y* | \(1) |
287 +--------------------+---------------------------------+--------+
288 | ``x // y`` | (floored) quotient of *x* and | (4)(5) |
290 +--------------------+---------------------------------+--------+
291 | ``x % y`` | remainder of ``x / y`` | \(4) |
292 +--------------------+---------------------------------+--------+
293 | ``-x`` | *x* negated | |
294 +--------------------+---------------------------------+--------+
295 | ``+x`` | *x* unchanged | |
296 +--------------------+---------------------------------+--------+
297 | ``abs(x)`` | absolute value or magnitude of | \(3) |
299 +--------------------+---------------------------------+--------+
300 | ``int(x)`` | *x* converted to integer | \(2) |
301 +--------------------+---------------------------------+--------+
302 | ``long(x)`` | *x* converted to long integer | \(2) |
303 +--------------------+---------------------------------+--------+
304 | ``float(x)`` | *x* converted to floating point | \(6) |
305 +--------------------+---------------------------------+--------+
306 | ``complex(re,im)`` | a complex number with real part | |
307 | | *re*, imaginary part *im*. | |
308 | | *im* defaults to zero. | |
309 +--------------------+---------------------------------+--------+
310 | ``c.conjugate()`` | conjugate of the complex number | |
311 | | *c*. (Identity on real numbers) | |
312 +--------------------+---------------------------------+--------+
313 | ``divmod(x, y)`` | the pair ``(x // y, x % y)`` | (3)(4) |
314 +--------------------+---------------------------------+--------+
315 | ``pow(x, y)`` | *x* to the power *y* | (3)(7) |
316 +--------------------+---------------------------------+--------+
317 | ``x ** y`` | *x* to the power *y* | \(7) |
318 +--------------------+---------------------------------+--------+
321 triple: operations on; numeric; types
322 single: conjugate() (complex number method)
328 pair: integer; division
329 triple: long; integer; division
331 For (plain or long) integer division, the result is an integer. The result is
332 always rounded towards minus infinity: 1/2 is 0, (-1)/2 is -1, 1/(-2) is -1, and
333 (-1)/(-2) is 0. Note that the result is a long integer if either operand is a
334 long integer, regardless of the numeric value.
339 single: floor() (in module math)
340 single: ceil() (in module math)
341 single: trunc() (in module math)
342 pair: numeric; conversions
344 Conversion from floats using :func:`int` or :func:`long` truncates toward
345 zero like the related function, :func:`math.trunc`. Use the function
346 :func:`math.floor` to round downward and :func:`math.ceil` to round
350 See :ref:`built-in-funcs` for a full description.
353 Complex floor division operator, modulo operator, and :func:`divmod`.
356 Instead convert to float using :func:`abs` if appropriate.
359 Also referred to as integer division. The resultant value is a whole integer,
360 though the result's type is not necessarily int.
363 float also accepts the strings "nan" and "inf" with an optional prefix "+"
364 or "-" for Not a Number (NaN) and positive or negative infinity.
366 .. versionadded:: 2.6
369 Python defines ``pow(0, 0)`` and ``0 ** 0`` to be ``1``, as is common for
370 programming languages.
372 All :class:`numbers.Real` types (:class:`int`, :class:`long`, and
373 :class:`float`) also include the following operations:
375 +--------------------+------------------------------------+--------+
376 | Operation | Result | Notes |
377 +====================+====================================+========+
378 | ``math.trunc(x)`` | *x* truncated to Integral | |
379 +--------------------+------------------------------------+--------+
380 | ``round(x[, n])`` | *x* rounded to n digits, | |
381 | | rounding half to even. If n is | |
382 | | omitted, it defaults to 0. | |
383 +--------------------+------------------------------------+--------+
384 | ``math.floor(x)`` | the greatest integral float <= *x* | |
385 +--------------------+------------------------------------+--------+
386 | ``math.ceil(x)`` | the least integral float >= *x* | |
387 +--------------------+------------------------------------+--------+
389 .. XXXJH exceptions: overflow (when? what operations?) zerodivision
394 Bit-string Operations on Integer Types
395 --------------------------------------
397 .. _bit-string-operations:
399 Plain and long integer types support additional operations that make sense only
400 for bit-strings. Negative numbers are treated as their 2's complement value
401 (for long integers, this assumes a sufficiently large number of bits that no
402 overflow occurs during the operation).
404 The priorities of the binary bitwise operations are all lower than the numeric
405 operations and higher than the comparisons; the unary operation ``~`` has the
406 same priority as the other unary numeric operations (``+`` and ``-``).
408 This table lists the bit-string operations sorted in ascending priority:
410 +------------+--------------------------------+----------+
411 | Operation | Result | Notes |
412 +============+================================+==========+
413 | ``x | y`` | bitwise :dfn:`or` of *x* and | |
415 +------------+--------------------------------+----------+
416 | ``x ^ y`` | bitwise :dfn:`exclusive or` of | |
418 +------------+--------------------------------+----------+
419 | ``x & y`` | bitwise :dfn:`and` of *x* and | |
421 +------------+--------------------------------+----------+
422 | ``x << n`` | *x* shifted left by *n* bits | (1)(2) |
423 +------------+--------------------------------+----------+
424 | ``x >> n`` | *x* shifted right by *n* bits | (1)(3) |
425 +------------+--------------------------------+----------+
426 | ``~x`` | the bits of *x* inverted | |
427 +------------+--------------------------------+----------+
430 triple: operations on; integer; types
431 pair: bit-string; operations
432 pair: shifting; operations
433 pair: masking; operations
438 Negative shift counts are illegal and cause a :exc:`ValueError` to be raised.
441 A left shift by *n* bits is equivalent to multiplication by ``pow(2, n)``. A
442 long integer is returned if the result exceeds the range of plain integers.
445 A right shift by *n* bits is equivalent to division by ``pow(2, n)``.
448 Additional Methods on Integer Types
449 -----------------------------------
451 .. method:: int.bit_length()
452 .. method:: long.bit_length()
454 Return the number of bits necessary to represent an integer in binary,
455 excluding the sign and leading zeros::
463 More precisely, if ``x`` is nonzero, then ``x.bit_length()`` is the
464 unique positive integer ``k`` such that ``2**(k-1) <= abs(x) < 2**k``.
465 Equivalently, when ``abs(x)`` is small enough to have a correctly
466 rounded logarithm, then ``k = 1 + int(log(abs(x), 2))``.
467 If ``x`` is zero, then ``x.bit_length()`` returns ``0``.
471 def bit_length(self):
472 s = bin(self) # binary representation: bin(-37) --> '-0b100101'
473 s = s.lstrip('-0b') # remove leading zeros and minus sign
474 return len(s) # len('100101') --> 6
476 .. versionadded:: 2.7
479 Additional Methods on Float
480 ---------------------------
482 The float type has some additional methods.
484 .. method:: float.as_integer_ratio()
486 Return a pair of integers whose ratio is exactly equal to the
487 original float and with a positive denominator. Raises
488 :exc:`OverflowError` on infinities and a :exc:`ValueError` on
491 .. versionadded:: 2.6
493 Two methods support conversion to
494 and from hexadecimal strings. Since Python's floats are stored
495 internally as binary numbers, converting a float to or from a
496 *decimal* string usually involves a small rounding error. In
497 contrast, hexadecimal strings allow exact representation and
498 specification of floating-point numbers. This can be useful when
499 debugging, and in numerical work.
502 .. method:: float.hex()
504 Return a representation of a floating-point number as a hexadecimal
505 string. For finite floating-point numbers, this representation
506 will always include a leading ``0x`` and a trailing ``p`` and
509 .. versionadded:: 2.6
512 .. method:: float.fromhex(s)
514 Class method to return the float represented by a hexadecimal
515 string *s*. The string *s* may have leading and trailing
518 .. versionadded:: 2.6
521 Note that :meth:`float.hex` is an instance method, while
522 :meth:`float.fromhex` is a class method.
524 A hexadecimal string takes the form::
526 [sign] ['0x'] integer ['.' fraction] ['p' exponent]
528 where the optional ``sign`` may by either ``+`` or ``-``, ``integer``
529 and ``fraction`` are strings of hexadecimal digits, and ``exponent``
530 is a decimal integer with an optional leading sign. Case is not
531 significant, and there must be at least one hexadecimal digit in
532 either the integer or the fraction. This syntax is similar to the
533 syntax specified in section 6.4.4.2 of the C99 standard, and also to
534 the syntax used in Java 1.5 onwards. In particular, the output of
535 :meth:`float.hex` is usable as a hexadecimal floating-point literal in
536 C or Java code, and hexadecimal strings produced by C's ``%a`` format
537 character or Java's ``Double.toHexString`` are accepted by
538 :meth:`float.fromhex`.
541 Note that the exponent is written in decimal rather than hexadecimal,
542 and that it gives the power of 2 by which to multiply the coefficient.
543 For example, the hexadecimal string ``0x3.a7p10`` represents the
544 floating-point number ``(3 + 10./16 + 7./16**2) * 2.0**10``, or
547 >>> float.fromhex('0x3.a7p10')
551 Applying the reverse conversion to ``3740.0`` gives a different
552 hexadecimal string representing the same number::
554 >>> float.hex(3740.0)
555 '0x1.d380000000000p+11'
563 .. versionadded:: 2.2
566 single: iterator protocol
567 single: protocol; iterator
568 single: sequence; iteration
569 single: container; iteration over
571 Python supports a concept of iteration over containers. This is implemented
572 using two distinct methods; these are used to allow user-defined classes to
573 support iteration. Sequences, described below in more detail, always support
574 the iteration methods.
576 One method needs to be defined for container objects to provide iteration
579 .. XXX duplicated in reference/datamodel!
581 .. method:: container.__iter__()
583 Return an iterator object. The object is required to support the iterator
584 protocol described below. If a container supports different types of
585 iteration, additional methods can be provided to specifically request
586 iterators for those iteration types. (An example of an object supporting
587 multiple forms of iteration would be a tree structure which supports both
588 breadth-first and depth-first traversal.) This method corresponds to the
589 :attr:`tp_iter` slot of the type structure for Python objects in the Python/C
592 The iterator objects themselves are required to support the following two
593 methods, which together form the :dfn:`iterator protocol`:
596 .. method:: iterator.__iter__()
598 Return the iterator object itself. This is required to allow both containers
599 and iterators to be used with the :keyword:`for` and :keyword:`in` statements.
600 This method corresponds to the :attr:`tp_iter` slot of the type structure for
601 Python objects in the Python/C API.
604 .. method:: iterator.next()
606 Return the next item from the container. If there are no further items, raise
607 the :exc:`StopIteration` exception. This method corresponds to the
608 :attr:`tp_iternext` slot of the type structure for Python objects in the
611 Python defines several iterator objects to support iteration over general and
612 specific sequence types, dictionaries, and other more specialized forms. The
613 specific types are not important beyond their implementation of the iterator
616 The intention of the protocol is that once an iterator's :meth:`next` method
617 raises :exc:`StopIteration`, it will continue to do so on subsequent calls.
618 Implementations that do not obey this property are deemed broken. (This
619 constraint was added in Python 2.3; in Python 2.2, various iterators are broken
620 according to this rule.)
622 Python's :term:`generator`\s provide a convenient way to implement the iterator
623 protocol. If a container object's :meth:`__iter__` method is implemented as a
624 generator, it will automatically return an iterator object (technically, a
625 generator object) supplying the :meth:`__iter__` and :meth:`next` methods.
630 Sequence Types --- :class:`str`, :class:`unicode`, :class:`list`, :class:`tuple`, :class:`buffer`, :class:`xrange`
631 ==================================================================================================================
633 There are six sequence types: strings, Unicode strings, lists, tuples, buffers,
636 For other containers see the built in :class:`dict` and :class:`set` classes,
637 and the :mod:`collections` module.
649 String literals are written in single or double quotes: ``'xyzzy'``,
650 ``"frobozz"``. See :ref:`strings` for more about string literals.
651 Unicode strings are much like strings, but are specified in the syntax
652 using a preceding ``'u'`` character: ``u'abc'``, ``u"def"``. In addition
653 to the functionality described here, there are also string-specific
654 methods described in the :ref:`string-methods` section. Lists are
655 constructed with square brackets, separating items with commas: ``[a, b, c]``.
656 Tuples are constructed by the comma operator (not within square
657 brackets), with or without enclosing parentheses, but an empty tuple
658 must have the enclosing parentheses, such as ``a, b, c`` or ``()``. A
659 single item tuple must have a trailing comma, such as ``(d,)``.
661 Buffer objects are not directly supported by Python syntax, but can be created
662 by calling the builtin function :func:`buffer`. They don't support
663 concatenation or repetition.
665 Objects of type xrange are similar to buffers in that there is no specific syntax to
666 create them, but they are created using the :func:`xrange` function. They don't
667 support slicing, concatenation or repetition, and using ``in``, ``not in``,
668 :func:`min` or :func:`max` on them is inefficient.
670 Most sequence types support the following operations. The ``in`` and ``not in``
671 operations have the same priorities as the comparison operations. The ``+`` and
672 ``*`` operations have the same priority as the corresponding numeric operations.
673 [#]_ Additional methods are provided for :ref:`typesseq-mutable`.
675 This table lists the sequence operations sorted in ascending priority
676 (operations in the same box have the same priority). In the table, *s* and *t*
677 are sequences of the same type; *n*, *i* and *j* are integers:
679 +------------------+--------------------------------+----------+
680 | Operation | Result | Notes |
681 +==================+================================+==========+
682 | ``x in s`` | ``True`` if an item of *s* is | \(1) |
683 | | equal to *x*, else ``False`` | |
684 +------------------+--------------------------------+----------+
685 | ``x not in s`` | ``False`` if an item of *s* is | \(1) |
686 | | equal to *x*, else ``True`` | |
687 +------------------+--------------------------------+----------+
688 | ``s + t`` | the concatenation of *s* and | \(6) |
690 +------------------+--------------------------------+----------+
691 | ``s * n, n * s`` | *n* shallow copies of *s* | \(2) |
693 +------------------+--------------------------------+----------+
694 | ``s[i]`` | *i*'th item of *s*, origin 0 | \(3) |
695 +------------------+--------------------------------+----------+
696 | ``s[i:j]`` | slice of *s* from *i* to *j* | (3)(4) |
697 +------------------+--------------------------------+----------+
698 | ``s[i:j:k]`` | slice of *s* from *i* to *j* | (3)(5) |
699 | | with step *k* | |
700 +------------------+--------------------------------+----------+
701 | ``len(s)`` | length of *s* | |
702 +------------------+--------------------------------+----------+
703 | ``min(s)`` | smallest item of *s* | |
704 +------------------+--------------------------------+----------+
705 | ``max(s)`` | largest item of *s* | |
706 +------------------+--------------------------------+----------+
708 Sequence types also support comparisons. In particular, tuples and lists
709 are compared lexicographically by comparing corresponding
710 elements. This means that to compare equal, every element must compare
711 equal and the two sequences must be of the same type and have the same
712 length. (For full details see :ref:`comparisons` in the language
716 triple: operations on; sequence; types
720 pair: concatenation; operation
721 pair: repetition; operation
722 pair: subscript; operation
723 pair: slice; operation
724 pair: extended slice; operation
731 When *s* is a string or Unicode string object the ``in`` and ``not in``
732 operations act like a substring test. In Python versions before 2.3, *x* had to
733 be a string of length 1. In Python 2.3 and beyond, *x* may be a string of any
737 Values of *n* less than ``0`` are treated as ``0`` (which yields an empty
738 sequence of the same type as *s*). Note also that the copies are shallow;
739 nested structures are not copied. This often haunts new Python programmers;
745 >>> lists[0].append(3)
749 What has happened is that ``[[]]`` is a one-element list containing an empty
750 list, so all three elements of ``[[]] * 3`` are (pointers to) this single empty
751 list. Modifying any of the elements of ``lists`` modifies this single list.
752 You can create a list of different lists this way:
754 >>> lists = [[] for i in range(3)]
755 >>> lists[0].append(3)
756 >>> lists[1].append(5)
757 >>> lists[2].append(7)
762 If *i* or *j* is negative, the index is relative to the end of the string:
763 ``len(s) + i`` or ``len(s) + j`` is substituted. But note that ``-0`` is still
767 The slice of *s* from *i* to *j* is defined as the sequence of items with index
768 *k* such that ``i <= k < j``. If *i* or *j* is greater than ``len(s)``, use
769 ``len(s)``. If *i* is omitted or ``None``, use ``0``. If *j* is omitted or
770 ``None``, use ``len(s)``. If *i* is greater than or equal to *j*, the slice is
774 The slice of *s* from *i* to *j* with step *k* is defined as the sequence of
775 items with index ``x = i + n*k`` such that ``0 <= n < (j-i)/k``. In other words,
776 the indices are ``i``, ``i+k``, ``i+2*k``, ``i+3*k`` and so on, stopping when
777 *j* is reached (but never including *j*). If *i* or *j* is greater than
778 ``len(s)``, use ``len(s)``. If *i* or *j* are omitted or ``None``, they become
779 "end" values (which end depends on the sign of *k*). Note, *k* cannot be zero.
780 If *k* is ``None``, it is treated like ``1``.
783 If *s* and *t* are both strings, some Python implementations such as CPython can
784 usually perform an in-place optimization for assignments of the form ``s=s+t``
785 or ``s+=t``. When applicable, this optimization makes quadratic run-time much
786 less likely. This optimization is both version and implementation dependent.
787 For performance sensitive code, it is preferable to use the :meth:`str.join`
788 method which assures consistent linear concatenation performance across versions
791 .. versionchanged:: 2.4
792 Formerly, string concatenation never occurred in-place.
800 .. index:: pair: string; methods
802 Below are listed the string methods which both 8-bit strings and Unicode objects
803 support. Note that none of these methods take keyword arguments.
805 In addition, Python's strings support the sequence type methods
806 described in the :ref:`typesseq` section. To output formatted strings
807 use template strings or the ``%`` operator described in the
808 :ref:`string-formatting` section. Also, see the :mod:`re` module for
809 string functions based on regular expressions.
811 .. method:: str.capitalize()
813 Return a copy of the string with only its first character capitalized.
815 For 8-bit strings, this method is locale-dependent.
818 .. method:: str.center(width[, fillchar])
820 Return centered in a string of length *width*. Padding is done using the
821 specified *fillchar* (default is a space).
823 .. versionchanged:: 2.4
824 Support for the *fillchar* argument.
827 .. method:: str.count(sub[, start[, end]])
829 Return the number of non-overlapping occurrences of substring *sub* in the
830 range [*start*, *end*]. Optional arguments *start* and *end* are
831 interpreted as in slice notation.
834 .. method:: str.decode([encoding[, errors]])
836 Decodes the string using the codec registered for *encoding*. *encoding*
837 defaults to the default string encoding. *errors* may be given to set a
838 different error handling scheme. The default is ``'strict'``, meaning that
839 encoding errors raise :exc:`UnicodeError`. Other possible values are
840 ``'ignore'``, ``'replace'`` and any other name registered via
841 :func:`codecs.register_error`, see section :ref:`codec-base-classes`.
843 .. versionadded:: 2.2
845 .. versionchanged:: 2.3
846 Support for other error handling schemes added.
849 .. method:: str.encode([encoding[,errors]])
851 Return an encoded version of the string. Default encoding is the current
852 default string encoding. *errors* may be given to set a different error
853 handling scheme. The default for *errors* is ``'strict'``, meaning that
854 encoding errors raise a :exc:`UnicodeError`. Other possible values are
855 ``'ignore'``, ``'replace'``, ``'xmlcharrefreplace'``, ``'backslashreplace'`` and
856 any other name registered via :func:`codecs.register_error`, see section
857 :ref:`codec-base-classes`. For a list of possible encodings, see section
858 :ref:`standard-encodings`.
860 .. versionadded:: 2.0
862 .. versionchanged:: 2.3
863 Support for ``'xmlcharrefreplace'`` and ``'backslashreplace'`` and other error
864 handling schemes added.
867 .. method:: str.endswith(suffix[, start[, end]])
869 Return ``True`` if the string ends with the specified *suffix*, otherwise return
870 ``False``. *suffix* can also be a tuple of suffixes to look for. With optional
871 *start*, test beginning at that position. With optional *end*, stop comparing
874 .. versionchanged:: 2.5
875 Accept tuples as *suffix*.
878 .. method:: str.expandtabs([tabsize])
880 Return a copy of the string where all tab characters are replaced by one or
881 more spaces, depending on the current column and the given tab size. The
882 column number is reset to zero after each newline occurring in the string.
883 If *tabsize* is not given, a tab size of ``8`` characters is assumed. This
884 doesn't understand other non-printing characters or escape sequences.
887 .. method:: str.find(sub[, start[, end]])
889 Return the lowest index in the string where substring *sub* is found, such that
890 *sub* is contained in the range [*start*, *end*]. Optional arguments *start*
891 and *end* are interpreted as in slice notation. Return ``-1`` if *sub* is not
895 .. method:: str.format(*args, **kwargs)
897 Perform a string formatting operation. The *format_string* argument can
898 contain literal text or replacement fields delimited by braces ``{}``. Each
899 replacement field contains either the numeric index of a positional argument,
900 or the name of a keyword argument. Returns a copy of *format_string* where
901 each replacement field is replaced with the string value of the corresponding
904 >>> "The sum of 1 + 2 is {0}".format(1+2)
905 'The sum of 1 + 2 is 3'
907 See :ref:`formatstrings` for a description of the various formatting options
908 that can be specified in format strings.
910 This method of string formatting is the new standard in Python 3.0, and
911 should be preferred to the ``%`` formatting described in
912 :ref:`string-formatting` in new code.
914 .. versionadded:: 2.6
917 .. method:: str.index(sub[, start[, end]])
919 Like :meth:`find`, but raise :exc:`ValueError` when the substring is not found.
922 .. method:: str.isalnum()
924 Return true if all characters in the string are alphanumeric and there is at
925 least one character, false otherwise.
927 For 8-bit strings, this method is locale-dependent.
930 .. method:: str.isalpha()
932 Return true if all characters in the string are alphabetic and there is at least
933 one character, false otherwise.
935 For 8-bit strings, this method is locale-dependent.
938 .. method:: str.isdigit()
940 Return true if all characters in the string are digits and there is at least one
941 character, false otherwise.
943 For 8-bit strings, this method is locale-dependent.
946 .. method:: str.islower()
948 Return true if all cased characters in the string are lowercase and there is at
949 least one cased character, false otherwise.
951 For 8-bit strings, this method is locale-dependent.
954 .. method:: str.isspace()
956 Return true if there are only whitespace characters in the string and there is
957 at least one character, false otherwise.
959 For 8-bit strings, this method is locale-dependent.
962 .. method:: str.istitle()
964 Return true if the string is a titlecased string and there is at least one
965 character, for example uppercase characters may only follow uncased characters
966 and lowercase characters only cased ones. Return false otherwise.
968 For 8-bit strings, this method is locale-dependent.
971 .. method:: str.isupper()
973 Return true if all cased characters in the string are uppercase and there is at
974 least one cased character, false otherwise.
976 For 8-bit strings, this method is locale-dependent.
979 .. method:: str.join(seq)
981 Return a string which is the concatenation of the strings in the sequence *seq*.
982 The separator between elements is the string providing this method.
985 .. method:: str.ljust(width[, fillchar])
987 Return the string left justified in a string of length *width*. Padding is done
988 using the specified *fillchar* (default is a space). The original string is
989 returned if *width* is less than ``len(s)``.
991 .. versionchanged:: 2.4
992 Support for the *fillchar* argument.
995 .. method:: str.lower()
997 Return a copy of the string converted to lowercase.
999 For 8-bit strings, this method is locale-dependent.
1002 .. method:: str.lstrip([chars])
1004 Return a copy of the string with leading characters removed. The *chars*
1005 argument is a string specifying the set of characters to be removed. If omitted
1006 or ``None``, the *chars* argument defaults to removing whitespace. The *chars*
1007 argument is not a prefix; rather, all combinations of its values are stripped:
1009 >>> ' spacious '.lstrip()
1011 >>> 'www.example.com'.lstrip('cmowz.')
1014 .. versionchanged:: 2.2.2
1015 Support for the *chars* argument.
1018 .. method:: str.partition(sep)
1020 Split the string at the first occurrence of *sep*, and return a 3-tuple
1021 containing the part before the separator, the separator itself, and the part
1022 after the separator. If the separator is not found, return a 3-tuple containing
1023 the string itself, followed by two empty strings.
1025 .. versionadded:: 2.5
1028 .. method:: str.replace(old, new[, count])
1030 Return a copy of the string with all occurrences of substring *old* replaced by
1031 *new*. If the optional argument *count* is given, only the first *count*
1032 occurrences are replaced.
1035 .. method:: str.rfind(sub [,start [,end]])
1037 Return the highest index in the string where substring *sub* is found, such that
1038 *sub* is contained within s[start,end]. Optional arguments *start* and *end*
1039 are interpreted as in slice notation. Return ``-1`` on failure.
1042 .. method:: str.rindex(sub[, start[, end]])
1044 Like :meth:`rfind` but raises :exc:`ValueError` when the substring *sub* is not
1048 .. method:: str.rjust(width[, fillchar])
1050 Return the string right justified in a string of length *width*. Padding is done
1051 using the specified *fillchar* (default is a space). The original string is
1052 returned if *width* is less than ``len(s)``.
1054 .. versionchanged:: 2.4
1055 Support for the *fillchar* argument.
1058 .. method:: str.rpartition(sep)
1060 Split the string at the last occurrence of *sep*, and return a 3-tuple
1061 containing the part before the separator, the separator itself, and the part
1062 after the separator. If the separator is not found, return a 3-tuple containing
1063 two empty strings, followed by the string itself.
1065 .. versionadded:: 2.5
1068 .. method:: str.rsplit([sep [,maxsplit]])
1070 Return a list of the words in the string, using *sep* as the delimiter string.
1071 If *maxsplit* is given, at most *maxsplit* splits are done, the *rightmost*
1072 ones. If *sep* is not specified or ``None``, any whitespace string is a
1073 separator. Except for splitting from the right, :meth:`rsplit` behaves like
1074 :meth:`split` which is described in detail below.
1076 .. versionadded:: 2.4
1079 .. method:: str.rstrip([chars])
1081 Return a copy of the string with trailing characters removed. The *chars*
1082 argument is a string specifying the set of characters to be removed. If omitted
1083 or ``None``, the *chars* argument defaults to removing whitespace. The *chars*
1084 argument is not a suffix; rather, all combinations of its values are stripped:
1086 >>> ' spacious '.rstrip()
1088 >>> 'mississippi'.rstrip('ipz')
1091 .. versionchanged:: 2.2.2
1092 Support for the *chars* argument.
1095 .. method:: str.split([sep[, maxsplit]])
1097 Return a list of the words in the string, using *sep* as the delimiter
1098 string. If *maxsplit* is given, at most *maxsplit* splits are done (thus,
1099 the list will have at most ``maxsplit+1`` elements). If *maxsplit* is not
1100 specified, then there is no limit on the number of splits (all possible
1103 If *sep* is given, consecutive delimiters are not grouped together and are
1104 deemed to delimit empty strings (for example, ``'1,,2'.split(',')`` returns
1105 ``['1', '', '2']``). The *sep* argument may consist of multiple characters
1106 (for example, ``'1<>2<>3'.split('<>')`` returns ``['1', '2', '3']``).
1107 Splitting an empty string with a specified separator returns ``['']``.
1109 If *sep* is not specified or is ``None``, a different splitting algorithm is
1110 applied: runs of consecutive whitespace are regarded as a single separator,
1111 and the result will contain no empty strings at the start or end if the
1112 string has leading or trailing whitespace. Consequently, splitting an empty
1113 string or a string consisting of just whitespace with a ``None`` separator
1116 For example, ``' 1 2 3 '.split()`` returns ``['1', '2', '3']``, and
1117 ``' 1 2 3 '.split(None, 1)`` returns ``['1', '2 3 ']``.
1120 .. method:: str.splitlines([keepends])
1122 Return a list of the lines in the string, breaking at line boundaries. Line
1123 breaks are not included in the resulting list unless *keepends* is given and
1127 .. method:: str.startswith(prefix[, start[, end]])
1129 Return ``True`` if string starts with the *prefix*, otherwise return ``False``.
1130 *prefix* can also be a tuple of prefixes to look for. With optional *start*,
1131 test string beginning at that position. With optional *end*, stop comparing
1132 string at that position.
1134 .. versionchanged:: 2.5
1135 Accept tuples as *prefix*.
1138 .. method:: str.strip([chars])
1140 Return a copy of the string with the leading and trailing characters removed.
1141 The *chars* argument is a string specifying the set of characters to be removed.
1142 If omitted or ``None``, the *chars* argument defaults to removing whitespace.
1143 The *chars* argument is not a prefix or suffix; rather, all combinations of its
1144 values are stripped:
1146 >>> ' spacious '.strip()
1148 >>> 'www.example.com'.strip('cmowz.')
1151 .. versionchanged:: 2.2.2
1152 Support for the *chars* argument.
1155 .. method:: str.swapcase()
1157 Return a copy of the string with uppercase characters converted to lowercase and
1160 For 8-bit strings, this method is locale-dependent.
1163 .. method:: str.title()
1165 Return a titlecased version of the string: words start with uppercase
1166 characters, all remaining cased characters are lowercase.
1168 For 8-bit strings, this method is locale-dependent.
1171 .. method:: str.translate(table[, deletechars])
1173 Return a copy of the string where all characters occurring in the optional
1174 argument *deletechars* are removed, and the remaining characters have been
1175 mapped through the given translation table, which must be a string of length
1178 You can use the :func:`maketrans` helper function in the :mod:`string` module to
1179 create a translation table. For string objects, set the *table* argument to
1180 ``None`` for translations that only delete characters:
1182 >>> 'read this short text'.translate(None, 'aeiou')
1185 .. versionadded:: 2.6
1186 Support for a ``None`` *table* argument.
1188 For Unicode objects, the :meth:`translate` method does not accept the optional
1189 *deletechars* argument. Instead, it returns a copy of the *s* where all
1190 characters have been mapped through the given translation table which must be a
1191 mapping of Unicode ordinals to Unicode ordinals, Unicode strings or ``None``.
1192 Unmapped characters are left untouched. Characters mapped to ``None`` are
1193 deleted. Note, a more flexible approach is to create a custom character mapping
1194 codec using the :mod:`codecs` module (see :mod:`encodings.cp1251` for an
1198 .. method:: str.upper()
1200 Return a copy of the string converted to uppercase.
1202 For 8-bit strings, this method is locale-dependent.
1205 .. method:: str.zfill(width)
1207 Return the numeric string left filled with zeros in a string of length
1208 *width*. A sign prefix is handled correctly. The original string is
1209 returned if *width* is less than ``len(s)``.
1212 .. versionadded:: 2.2.2
1214 The following methods are present only on unicode objects:
1216 .. method:: unicode.isnumeric()
1218 Return ``True`` if there are only numeric characters in S, ``False``
1219 otherwise. Numeric characters include digit characters, and all characters
1220 that have the Unicode numeric value property, e.g. U+2155,
1221 VULGAR FRACTION ONE FIFTH.
1223 .. method:: unicode.isdecimal()
1225 Return ``True`` if there are only decimal characters in S, ``False``
1226 otherwise. Decimal characters include digit characters, and all characters
1227 that that can be used to form decimal-radix numbers, e.g. U+0660,
1228 ARABIC-INDIC DIGIT ZERO.
1231 .. _string-formatting:
1233 String Formatting Operations
1234 ----------------------------
1237 single: formatting, string (%)
1238 single: interpolation, string (%)
1239 single: string; formatting
1240 single: string; interpolation
1241 single: printf-style formatting
1242 single: sprintf-style formatting
1243 single: % formatting
1244 single: % interpolation
1246 String and Unicode objects have one unique built-in operation: the ``%``
1247 operator (modulo). This is also known as the string *formatting* or
1248 *interpolation* operator. Given ``format % values`` (where *format* is a string
1249 or Unicode object), ``%`` conversion specifications in *format* are replaced
1250 with zero or more elements of *values*. The effect is similar to the using
1251 :cfunc:`sprintf` in the C language. If *format* is a Unicode object, or if any
1252 of the objects being converted using the ``%s`` conversion are Unicode objects,
1253 the result will also be a Unicode object.
1255 If *format* requires a single argument, *values* may be a single non-tuple
1256 object. [#]_ Otherwise, *values* must be a tuple with exactly the number of
1257 items specified by the format string, or a single mapping object (for example, a
1260 A conversion specifier contains two or more characters and has the following
1261 components, which must occur in this order:
1263 #. The ``'%'`` character, which marks the start of the specifier.
1265 #. Mapping key (optional), consisting of a parenthesised sequence of characters
1266 (for example, ``(somename)``).
1268 #. Conversion flags (optional), which affect the result of some conversion
1271 #. Minimum field width (optional). If specified as an ``'*'`` (asterisk), the
1272 actual width is read from the next element of the tuple in *values*, and the
1273 object to convert comes after the minimum field width and optional precision.
1275 #. Precision (optional), given as a ``'.'`` (dot) followed by the precision. If
1276 specified as ``'*'`` (an asterisk), the actual width is read from the next
1277 element of the tuple in *values*, and the value to convert comes after the
1280 #. Length modifier (optional).
1284 When the right argument is a dictionary (or other mapping type), then the
1285 formats in the string *must* include a parenthesised mapping key into that
1286 dictionary inserted immediately after the ``'%'`` character. The mapping key
1287 selects the value to be formatted from the mapping. For example:
1289 >>> print '%(language)s has %(#)03d quote types.' % \
1290 ... {'language': "Python", "#": 2}
1291 Python has 002 quote types.
1293 In this case no ``*`` specifiers may occur in a format (since they require a
1294 sequential parameter list).
1296 The conversion flag characters are:
1298 +---------+---------------------------------------------------------------------+
1300 +=========+=====================================================================+
1301 | ``'#'`` | The value conversion will use the "alternate form" (where defined |
1303 +---------+---------------------------------------------------------------------+
1304 | ``'0'`` | The conversion will be zero padded for numeric values. |
1305 +---------+---------------------------------------------------------------------+
1306 | ``'-'`` | The converted value is left adjusted (overrides the ``'0'`` |
1307 | | conversion if both are given). |
1308 +---------+---------------------------------------------------------------------+
1309 | ``' '`` | (a space) A blank should be left before a positive number (or empty |
1310 | | string) produced by a signed conversion. |
1311 +---------+---------------------------------------------------------------------+
1312 | ``'+'`` | A sign character (``'+'`` or ``'-'``) will precede the conversion |
1313 | | (overrides a "space" flag). |
1314 +---------+---------------------------------------------------------------------+
1316 A length modifier (``h``, ``l``, or ``L``) may be present, but is ignored as it
1317 is not necessary for Python -- so e.g. ``%ld`` is identical to ``%d``.
1319 The conversion types are:
1321 +------------+-----------------------------------------------------+-------+
1322 | Conversion | Meaning | Notes |
1323 +============+=====================================================+=======+
1324 | ``'d'`` | Signed integer decimal. | |
1325 +------------+-----------------------------------------------------+-------+
1326 | ``'i'`` | Signed integer decimal. | |
1327 +------------+-----------------------------------------------------+-------+
1328 | ``'o'`` | Signed octal value. | \(1) |
1329 +------------+-----------------------------------------------------+-------+
1330 | ``'u'`` | Obsolete type -- it is identical to ``'d'``. | \(7) |
1331 +------------+-----------------------------------------------------+-------+
1332 | ``'x'`` | Signed hexadecimal (lowercase). | \(2) |
1333 +------------+-----------------------------------------------------+-------+
1334 | ``'X'`` | Signed hexadecimal (uppercase). | \(2) |
1335 +------------+-----------------------------------------------------+-------+
1336 | ``'e'`` | Floating point exponential format (lowercase). | \(3) |
1337 +------------+-----------------------------------------------------+-------+
1338 | ``'E'`` | Floating point exponential format (uppercase). | \(3) |
1339 +------------+-----------------------------------------------------+-------+
1340 | ``'f'`` | Floating point decimal format. | \(3) |
1341 +------------+-----------------------------------------------------+-------+
1342 | ``'F'`` | Floating point decimal format. | \(3) |
1343 +------------+-----------------------------------------------------+-------+
1344 | ``'g'`` | Floating point format. Uses lowercase exponential | \(4) |
1345 | | format if exponent is less than -4 or not less than | |
1346 | | precision, decimal format otherwise. | |
1347 +------------+-----------------------------------------------------+-------+
1348 | ``'G'`` | Floating point format. Uses uppercase exponential | \(4) |
1349 | | format if exponent is less than -4 or not less than | |
1350 | | precision, decimal format otherwise. | |
1351 +------------+-----------------------------------------------------+-------+
1352 | ``'c'`` | Single character (accepts integer or single | |
1353 | | character string). | |
1354 +------------+-----------------------------------------------------+-------+
1355 | ``'r'`` | String (converts any python object using | \(5) |
1356 | | :func:`repr`). | |
1357 +------------+-----------------------------------------------------+-------+
1358 | ``'s'`` | String (converts any python object using | \(6) |
1359 | | :func:`str`). | |
1360 +------------+-----------------------------------------------------+-------+
1361 | ``'%'`` | No argument is converted, results in a ``'%'`` | |
1362 | | character in the result. | |
1363 +------------+-----------------------------------------------------+-------+
1368 The alternate form causes a leading zero (``'0'``) to be inserted between
1369 left-hand padding and the formatting of the number if the leading character
1370 of the result is not already a zero.
1373 The alternate form causes a leading ``'0x'`` or ``'0X'`` (depending on whether
1374 the ``'x'`` or ``'X'`` format was used) to be inserted between left-hand padding
1375 and the formatting of the number if the leading character of the result is not
1379 The alternate form causes the result to always contain a decimal point, even if
1380 no digits follow it.
1382 The precision determines the number of digits after the decimal point and
1386 The alternate form causes the result to always contain a decimal point, and
1387 trailing zeroes are not removed as they would otherwise be.
1389 The precision determines the number of significant digits before and after the
1390 decimal point and defaults to 6.
1393 The ``%r`` conversion was added in Python 2.0.
1395 The precision determines the maximal number of characters used.
1398 If the object or format provided is a :class:`unicode` string, the resulting
1399 string will also be :class:`unicode`.
1401 The precision determines the maximal number of characters used.
1406 Since Python strings have an explicit length, ``%s`` conversions do not assume
1407 that ``'\0'`` is the end of the string.
1411 For safety reasons, floating point precisions are clipped to 50; ``%f``
1412 conversions for numbers whose absolute value is over 1e50 are replaced by ``%g``
1413 conversions. [#]_ All other errors raise exceptions.
1419 Additional string operations are defined in standard modules :mod:`string` and
1423 .. _typesseq-xrange:
1428 .. index:: object: xrange
1430 The :class:`xrange` type is an immutable sequence which is commonly used for
1431 looping. The advantage of the :class:`xrange` type is that an :class:`xrange`
1432 object will always take the same amount of memory, no matter the size of the
1433 range it represents. There are no consistent performance advantages.
1435 XRange objects have very little behavior: they only support indexing, iteration,
1436 and the :func:`len` function.
1439 .. _typesseq-mutable:
1441 Mutable Sequence Types
1442 ----------------------
1445 triple: mutable; sequence; types
1448 List objects support additional operations that allow in-place modification of
1449 the object. Other mutable sequence types (when added to the language) should
1450 also support these operations. Strings and tuples are immutable sequence types:
1451 such objects cannot be modified once created. The following operations are
1452 defined on mutable sequence types (where *x* is an arbitrary object):
1454 +------------------------------+--------------------------------+---------------------+
1455 | Operation | Result | Notes |
1456 +==============================+================================+=====================+
1457 | ``s[i] = x`` | item *i* of *s* is replaced by | |
1459 +------------------------------+--------------------------------+---------------------+
1460 | ``s[i:j] = t`` | slice of *s* from *i* to *j* | |
1461 | | is replaced by the contents of | |
1462 | | the iterable *t* | |
1463 +------------------------------+--------------------------------+---------------------+
1464 | ``del s[i:j]`` | same as ``s[i:j] = []`` | |
1465 +------------------------------+--------------------------------+---------------------+
1466 | ``s[i:j:k] = t`` | the elements of ``s[i:j:k]`` | \(1) |
1467 | | are replaced by those of *t* | |
1468 +------------------------------+--------------------------------+---------------------+
1469 | ``del s[i:j:k]`` | removes the elements of | |
1470 | | ``s[i:j:k]`` from the list | |
1471 +------------------------------+--------------------------------+---------------------+
1472 | ``s.append(x)`` | same as ``s[len(s):len(s)] = | \(2) |
1474 +------------------------------+--------------------------------+---------------------+
1475 | ``s.extend(x)`` | same as ``s[len(s):len(s)] = | \(3) |
1477 +------------------------------+--------------------------------+---------------------+
1478 | ``s.count(x)`` | return number of *i*'s for | |
1479 | | which ``s[i] == x`` | |
1480 +------------------------------+--------------------------------+---------------------+
1481 | ``s.index(x[, i[, j]])`` | return smallest *k* such that | \(4) |
1482 | | ``s[k] == x`` and ``i <= k < | |
1484 +------------------------------+--------------------------------+---------------------+
1485 | ``s.insert(i, x)`` | same as ``s[i:i] = [x]`` | \(5) |
1486 +------------------------------+--------------------------------+---------------------+
1487 | ``s.pop([i])`` | same as ``x = s[i]; del s[i]; | \(6) |
1489 +------------------------------+--------------------------------+---------------------+
1490 | ``s.remove(x)`` | same as ``del s[s.index(x)]`` | \(4) |
1491 +------------------------------+--------------------------------+---------------------+
1492 | ``s.reverse()`` | reverses the items of *s* in | \(7) |
1494 +------------------------------+--------------------------------+---------------------+
1495 | ``s.sort([cmp[, key[, | sort the items of *s* in place | (7)(8)(9)(10) |
1496 | reverse]]])`` | | |
1497 +------------------------------+--------------------------------+---------------------+
1500 triple: operations on; sequence; types
1501 triple: operations on; list; type
1502 pair: subscript; assignment
1503 pair: slice; assignment
1504 pair: extended slice; assignment
1506 single: append() (list method)
1507 single: extend() (list method)
1508 single: count() (list method)
1509 single: index() (list method)
1510 single: insert() (list method)
1511 single: pop() (list method)
1512 single: remove() (list method)
1513 single: reverse() (list method)
1514 single: sort() (list method)
1519 *t* must have the same length as the slice it is replacing.
1522 The C implementation of Python has historically accepted multiple parameters and
1523 implicitly joined them into a tuple; this no longer works in Python 2.0. Use of
1524 this misfeature has been deprecated since Python 1.4.
1527 *x* can be any iterable object.
1530 Raises :exc:`ValueError` when *x* is not found in *s*. When a negative index is
1531 passed as the second or third parameter to the :meth:`index` method, the list
1532 length is added, as for slice indices. If it is still negative, it is truncated
1533 to zero, as for slice indices.
1535 .. versionchanged:: 2.3
1536 Previously, :meth:`index` didn't have arguments for specifying start and stop
1540 When a negative index is passed as the first parameter to the :meth:`insert`
1541 method, the list length is added, as for slice indices. If it is still
1542 negative, it is truncated to zero, as for slice indices.
1544 .. versionchanged:: 2.3
1545 Previously, all negative indices were truncated to zero.
1548 The :meth:`pop` method is only supported by the list and array types. The
1549 optional argument *i* defaults to ``-1``, so that by default the last item is
1550 removed and returned.
1553 The :meth:`sort` and :meth:`reverse` methods modify the list in place for
1554 economy of space when sorting or reversing a large list. To remind you that
1555 they operate by side effect, they don't return the sorted or reversed list.
1558 The :meth:`sort` method takes optional arguments for controlling the
1561 *cmp* specifies a custom comparison function of two arguments (list items) which
1562 should return a negative, zero or positive number depending on whether the first
1563 argument is considered smaller than, equal to, or larger than the second
1564 argument: ``cmp=lambda x,y: cmp(x.lower(), y.lower())``. The default value
1567 *key* specifies a function of one argument that is used to extract a comparison
1568 key from each list element: ``key=str.lower``. The default value is ``None``.
1570 *reverse* is a boolean value. If set to ``True``, then the list elements are
1571 sorted as if each comparison were reversed.
1573 In general, the *key* and *reverse* conversion processes are much faster than
1574 specifying an equivalent *cmp* function. This is because *cmp* is called
1575 multiple times for each list element while *key* and *reverse* touch each
1578 .. versionchanged:: 2.3
1579 Support for ``None`` as an equivalent to omitting *cmp* was added.
1581 .. versionchanged:: 2.4
1582 Support for *key* and *reverse* was added.
1585 Starting with Python 2.3, the :meth:`sort` method is guaranteed to be stable. A
1586 sort is stable if it guarantees not to change the relative order of elements
1587 that compare equal --- this is helpful for sorting in multiple passes (for
1588 example, sort by department, then by salary grade).
1591 While a list is being sorted, the effect of attempting to mutate, or even
1592 inspect, the list is undefined. The C implementation of Python 2.3 and newer
1593 makes the list appear empty for the duration, and raises :exc:`ValueError` if it
1594 can detect that the list has been mutated during a sort.
1599 Set Types --- :class:`set`, :class:`frozenset`
1600 ==============================================
1602 .. index:: object: set
1604 A :dfn:`set` object is an unordered collection of distinct :term:`hashable` objects.
1605 Common uses include membership testing, removing duplicates from a sequence, and
1606 computing mathematical operations such as intersection, union, difference, and
1607 symmetric difference.
1608 (For other containers see the built in :class:`dict`, :class:`list`,
1609 and :class:`tuple` classes, and the :mod:`collections` module.)
1612 .. versionadded:: 2.4
1614 Like other collections, sets support ``x in set``, ``len(set)``, and ``for x in
1615 set``. Being an unordered collection, sets do not record element position or
1616 order of insertion. Accordingly, sets do not support indexing, slicing, or
1617 other sequence-like behavior.
1619 There are currently two builtin set types, :class:`set` and :class:`frozenset`.
1620 The :class:`set` type is mutable --- the contents can be changed using methods
1621 like :meth:`add` and :meth:`remove`. Since it is mutable, it has no hash value
1622 and cannot be used as either a dictionary key or as an element of another set.
1623 The :class:`frozenset` type is immutable and :term:`hashable` --- its contents cannot be
1624 altered after it is created; it can therefore be used as a dictionary key or as
1625 an element of another set.
1627 The constructors for both classes work the same:
1629 .. class:: set([iterable])
1630 frozenset([iterable])
1632 Return a new set or frozenset object whose elements are taken from
1633 *iterable*. The elements of a set must be hashable. To represent sets of
1634 sets, the inner sets must be :class:`frozenset` objects. If *iterable* is
1635 not specified, a new empty set is returned.
1637 Instances of :class:`set` and :class:`frozenset` provide the following
1640 .. describe:: len(s)
1642 Return the cardinality of set *s*.
1644 .. describe:: x in s
1646 Test *x* for membership in *s*.
1648 .. describe:: x not in s
1650 Test *x* for non-membership in *s*.
1652 .. method:: isdisjoint(other)
1654 Return True if the set has no elements in common with *other*. Sets are
1655 disjoint if and only if their intersection is the empty set.
1657 .. versionadded:: 2.6
1659 .. method:: issubset(other)
1662 Test whether every element in the set is in *other*.
1664 .. method:: set < other
1666 Test whether the set is a true subset of *other*, that is,
1667 ``set <= other and set != other``.
1669 .. method:: issuperset(other)
1672 Test whether every element in *other* is in the set.
1674 .. method:: set > other
1676 Test whether the set is a true superset of *other*, that is, ``set >=
1677 other and set != other``.
1679 .. method:: union(other, ...)
1682 Return a new set with elements from the set and all others.
1684 .. versionchanged:: 2.6
1685 Accepts multiple input iterables.
1687 .. method:: intersection(other, ...)
1690 Return a new set with elements common to the set and all others.
1692 .. versionchanged:: 2.6
1693 Accepts multiple input iterables.
1695 .. method:: difference(other, ...)
1698 Return a new set with elements in the set that are not in the others.
1700 .. versionchanged:: 2.6
1701 Accepts multiple input iterables.
1703 .. method:: symmetric_difference(other)
1706 Return a new set with elements in either the set or *other* but not both.
1710 Return a new set with a shallow copy of *s*.
1713 Note, the non-operator versions of :meth:`union`, :meth:`intersection`,
1714 :meth:`difference`, and :meth:`symmetric_difference`, :meth:`issubset`, and
1715 :meth:`issuperset` methods will accept any iterable as an argument. In
1716 contrast, their operator based counterparts require their arguments to be
1717 sets. This precludes error-prone constructions like ``set('abc') & 'cbs'``
1718 in favor of the more readable ``set('abc').intersection('cbs')``.
1720 Both :class:`set` and :class:`frozenset` support set to set comparisons. Two
1721 sets are equal if and only if every element of each set is contained in the
1722 other (each is a subset of the other). A set is less than another set if and
1723 only if the first set is a proper subset of the second set (is a subset, but
1724 is not equal). A set is greater than another set if and only if the first set
1725 is a proper superset of the second set (is a superset, but is not equal).
1727 Instances of :class:`set` are compared to instances of :class:`frozenset`
1728 based on their members. For example, ``set('abc') == frozenset('abc')``
1729 returns ``True`` and so does ``set('abc') in set([frozenset('abc')])``.
1731 The subset and equality comparisons do not generalize to a complete ordering
1732 function. For example, any two disjoint sets are not equal and are not
1733 subsets of each other, so *all* of the following return ``False``: ``a<b``,
1734 ``a==b``, or ``a>b``. Accordingly, sets do not implement the :meth:`__cmp__`
1737 Since sets only define partial ordering (subset relationships), the output of
1738 the :meth:`list.sort` method is undefined for lists of sets.
1740 Set elements, like dictionary keys, must be :term:`hashable`.
1742 Binary operations that mix :class:`set` instances with :class:`frozenset`
1743 return the type of the first operand. For example: ``frozenset('ab') |
1744 set('bc')`` returns an instance of :class:`frozenset`.
1746 The following table lists operations available for :class:`set` that do not
1747 apply to immutable instances of :class:`frozenset`:
1749 .. method:: update(other, ...)
1752 Update the set, adding elements from *other*.
1754 .. versionchanged:: 2.6
1755 Accepts multiple input iterables.
1757 .. method:: intersection_update(other, ...)
1760 Update the set, keeping only elements found in it and *other*.
1762 .. versionchanged:: 2.6
1763 Accepts multiple input iterables.
1765 .. method:: difference_update(other, ...)
1768 Update the set, removing elements found in others.
1770 .. versionchanged:: 2.6
1771 Accepts multiple input iterables.
1773 .. method:: symmetric_difference_update(other)
1776 Update the set, keeping only elements found in either set, but not in both.
1778 .. method:: add(elem)
1780 Add element *elem* to the set.
1782 .. method:: remove(elem)
1784 Remove element *elem* from the set. Raises :exc:`KeyError` if *elem* is
1785 not contained in the set.
1787 .. method:: discard(elem)
1789 Remove element *elem* from the set if it is present.
1793 Remove and return an arbitrary element from the set. Raises
1794 :exc:`KeyError` if the set is empty.
1798 Remove all elements from the set.
1801 Note, the non-operator versions of the :meth:`update`,
1802 :meth:`intersection_update`, :meth:`difference_update`, and
1803 :meth:`symmetric_difference_update` methods will accept any iterable as an
1806 Note, the *elem* argument to the :meth:`__contains__`, :meth:`remove`, and
1807 :meth:`discard` methods may be a set. To support searching for an equivalent
1808 frozenset, the *elem* set is temporarily mutated during the search and then
1809 restored. During the search, the *elem* set should not be read or mutated
1810 since it does not have a meaningful value.
1815 :ref:`comparison-to-builtin-set`
1816 Differences between the :mod:`sets` module and the built-in set types.
1821 Mapping Types --- :class:`dict`
1822 ===============================
1827 triple: operations on; mapping; types
1828 triple: operations on; dictionary; type
1832 A :dfn:`mapping` object maps :term:`hashable` values to arbitrary objects.
1833 Mappings are mutable objects. There is currently only one standard mapping
1834 type, the :dfn:`dictionary`. (For other containers see the built in
1835 :class:`list`, :class:`set`, and :class:`tuple` classes, and the
1836 :mod:`collections` module.)
1838 A dictionary's keys are *almost* arbitrary values. Values that are not
1839 :term:`hashable`, that is, values containing lists, dictionaries or other
1840 mutable types (that are compared by value rather than by object identity) may
1841 not be used as keys. Numeric types used for keys obey the normal rules for
1842 numeric comparison: if two numbers compare equal (such as ``1`` and ``1.0``)
1843 then they can be used interchangeably to index the same dictionary entry. (Note
1844 however, that since computers store floating-point numbers as approximations it
1845 is usually unwise to use them as dictionary keys.)
1847 Dictionaries can be created by placing a comma-separated list of ``key: value``
1848 pairs within braces, for example: ``{'jack': 4098, 'sjoerd': 4127}`` or ``{4098:
1849 'jack', 4127: 'sjoerd'}``, or by the :class:`dict` constructor.
1851 .. class:: dict([arg])
1853 Return a new dictionary initialized from an optional positional argument or from
1854 a set of keyword arguments. If no arguments are given, return a new empty
1855 dictionary. If the positional argument *arg* is a mapping object, return a
1856 dictionary mapping the same keys to the same values as does the mapping object.
1857 Otherwise the positional argument must be a sequence, a container that supports
1858 iteration, or an iterator object. The elements of the argument must each also
1859 be of one of those kinds, and each must in turn contain exactly two objects.
1860 The first is used as a key in the new dictionary, and the second as the key's
1861 value. If a given key is seen more than once, the last value associated with it
1862 is retained in the new dictionary.
1864 If keyword arguments are given, the keywords themselves with their associated
1865 values are added as items to the dictionary. If a key is specified both in the
1866 positional argument and as a keyword argument, the value associated with the
1867 keyword is retained in the dictionary. For example, these all return a
1868 dictionary equal to ``{"one": 2, "two": 3}``:
1870 * ``dict(one=2, two=3)``
1872 * ``dict({'one': 2, 'two': 3})``
1874 * ``dict(zip(('one', 'two'), (2, 3)))``
1876 * ``dict([['two', 3], ['one', 2]])``
1878 The first example only works for keys that are valid Python
1879 identifiers; the others work with any valid keys.
1881 .. versionadded:: 2.2
1883 .. versionchanged:: 2.3
1884 Support for building a dictionary from keyword arguments added.
1887 These are the operations that dictionaries support (and therefore, custom
1888 mapping types should support too):
1890 .. describe:: len(d)
1892 Return the number of items in the dictionary *d*.
1894 .. describe:: d[key]
1896 Return the item of *d* with key *key*. Raises a :exc:`KeyError` if *key*
1899 .. versionadded:: 2.5
1900 If a subclass of dict defines a method :meth:`__missing__`, if the key
1901 *key* is not present, the ``d[key]`` operation calls that method with
1902 the key *key* as argument. The ``d[key]`` operation then returns or
1903 raises whatever is returned or raised by the ``__missing__(key)`` call
1904 if the key is not present. No other operations or methods invoke
1905 :meth:`__missing__`. If :meth:`__missing__` is not defined,
1906 :exc:`KeyError` is raised. :meth:`__missing__` must be a method; it
1907 cannot be an instance variable. For an example, see
1908 :class:`collections.defaultdict`.
1910 .. describe:: d[key] = value
1912 Set ``d[key]`` to *value*.
1914 .. describe:: del d[key]
1916 Remove ``d[key]`` from *d*. Raises a :exc:`KeyError` if *key* is not in the
1919 .. describe:: key in d
1921 Return ``True`` if *d* has a key *key*, else ``False``.
1923 .. versionadded:: 2.2
1925 .. describe:: key not in d
1927 Equivalent to ``not key in d``.
1929 .. versionadded:: 2.2
1931 .. describe:: iter(d)
1933 Return an iterator over the keys of the dictionary. This is a shortcut
1934 for :meth:`iterkeys`.
1938 Remove all items from the dictionary.
1942 Return a shallow copy of the dictionary.
1944 .. method:: fromkeys(seq[, value])
1946 Create a new dictionary with keys from *seq* and values set to *value*.
1948 :func:`fromkeys` is a class method that returns a new dictionary. *value*
1949 defaults to ``None``.
1951 .. versionadded:: 2.3
1953 .. method:: get(key[, default])
1955 Return the value for *key* if *key* is in the dictionary, else *default*.
1956 If *default* is not given, it defaults to ``None``, so that this method
1957 never raises a :exc:`KeyError`.
1959 .. method:: has_key(key)
1961 Test for the presence of *key* in the dictionary. :meth:`has_key` is
1962 deprecated in favor of ``key in d``.
1966 Return a copy of the dictionary's list of ``(key, value)`` pairs.
1970 Keys and values are listed in an arbitrary order which is non-random,
1971 varies across Python implementations, and depends on the dictionary's
1972 history of insertions and deletions. If :meth:`items`, :meth:`keys`,
1973 :meth:`values`, :meth:`iteritems`, :meth:`iterkeys`, and
1974 :meth:`itervalues` are called with no intervening modifications to the
1975 dictionary, the lists will directly correspond. This allows the
1976 creation of ``(value, key)`` pairs using :func:`zip`: ``pairs =
1977 zip(d.values(), d.keys())``. The same relationship holds for the
1978 :meth:`iterkeys` and :meth:`itervalues` methods: ``pairs =
1979 zip(d.itervalues(), d.iterkeys())`` provides the same value for
1980 ``pairs``. Another way to create the same list is ``pairs = [(v, k) for
1981 (k, v) in d.iteritems()]``.
1983 .. method:: iteritems()
1985 Return an iterator over the dictionary's ``(key, value)`` pairs. See the
1986 note for :meth:`dict.items`.
1988 Using :meth:`iteritems` while adding or deleting entries in the dictionary
1989 may raise a :exc:`RuntimeError` or fail to iterate over all entries.
1991 .. versionadded:: 2.2
1993 .. method:: iterkeys()
1995 Return an iterator over the dictionary's keys. See the note for
1998 Using :meth:`iterkeys` while adding or deleting entries in the dictionary
1999 may raise a :exc:`RuntimeError` or fail to iterate over all entries.
2001 .. versionadded:: 2.2
2003 .. method:: itervalues()
2005 Return an iterator over the dictionary's values. See the note for
2008 Using :meth:`itervalues` while adding or deleting entries in the
2009 dictionary may raise a :exc:`RuntimeError` or fail to iterate over all
2012 .. versionadded:: 2.2
2016 Return a copy of the dictionary's list of keys. See the note for
2019 .. method:: pop(key[, default])
2021 If *key* is in the dictionary, remove it and return its value, else return
2022 *default*. If *default* is not given and *key* is not in the dictionary,
2023 a :exc:`KeyError` is raised.
2025 .. versionadded:: 2.3
2027 .. method:: popitem()
2029 Remove and return an arbitrary ``(key, value)`` pair from the dictionary.
2031 :func:`popitem` is useful to destructively iterate over a dictionary, as
2032 often used in set algorithms. If the dictionary is empty, calling
2033 :func:`popitem` raises a :exc:`KeyError`.
2035 .. method:: setdefault(key[, default])
2037 If *key* is in the dictionary, return its value. If not, insert *key*
2038 with a value of *default* and return *default*. *default* defaults to
2041 .. method:: update([other])
2043 Update the dictionary with the key/value pairs from *other*, overwriting
2044 existing keys. Return ``None``.
2046 :func:`update` accepts either another dictionary object or an iterable of
2047 key/value pairs (as a tuple or other iterable of length two). If keyword
2048 arguments are specified, the dictionary is then is updated with those
2049 key/value pairs: ``d.update(red=1, blue=2)``.
2051 .. versionchanged:: 2.4
2052 Allowed the argument to be an iterable of key/value pairs and allowed
2055 .. method:: values()
2057 Return a copy of the dictionary's list of values. See the note for
2061 .. _bltin-file-objects:
2072 File objects are implemented using C's ``stdio`` package and can be
2073 created with the built-in :func:`open` function. File
2074 objects are also returned by some other built-in functions and methods,
2075 such as :func:`os.popen` and :func:`os.fdopen` and the :meth:`makefile`
2076 method of socket objects. Temporary files can be created using the
2077 :mod:`tempfile` module, and high-level file operations such as copying,
2078 moving, and deleting files and directories can be achieved with the
2079 :mod:`shutil` module.
2081 When a file operation fails for an I/O-related reason, the exception
2082 :exc:`IOError` is raised. This includes situations where the operation is not
2083 defined for some reason, like :meth:`seek` on a tty device or writing a file
2086 Files have the following methods:
2089 .. method:: file.close()
2091 Close the file. A closed file cannot be read or written any more. Any operation
2092 which requires that the file be open will raise a :exc:`ValueError` after the
2093 file has been closed. Calling :meth:`close` more than once is allowed.
2095 As of Python 2.5, you can avoid having to call this method explicitly if you use
2096 the :keyword:`with` statement. For example, the following code will
2097 automatically close *f* when the :keyword:`with` block is exited::
2099 from __future__ import with_statement # This isn't required in Python 2.6
2101 with open("hello.txt") as f:
2105 In older versions of Python, you would have needed to do this to get the same
2108 f = open("hello.txt")
2117 Not all "file-like" types in Python support use as a context manager for the
2118 :keyword:`with` statement. If your code is intended to work with any file-like
2119 object, you can use the function :func:`contextlib.closing` instead of using
2120 the object directly.
2123 .. method:: file.flush()
2125 Flush the internal buffer, like ``stdio``'s :cfunc:`fflush`. This may be a
2126 no-op on some file-like objects.
2130 :meth:`flush` does not necessarily write the file's data to disk. Use
2131 :meth:`flush` followed by :func:`os.fsync` to ensure this behavior.
2134 .. method:: file.fileno()
2137 pair: file; descriptor
2140 Return the integer "file descriptor" that is used by the underlying
2141 implementation to request I/O operations from the operating system. This can be
2142 useful for other, lower level interfaces that use file descriptors, such as the
2143 :mod:`fcntl` module or :func:`os.read` and friends.
2147 File-like objects which do not have a real file descriptor should *not* provide
2151 .. method:: file.isatty()
2153 Return ``True`` if the file is connected to a tty(-like) device, else ``False``.
2157 If a file-like object is not associated with a real file, this method should
2158 *not* be implemented.
2161 .. method:: file.next()
2163 A file object is its own iterator, for example ``iter(f)`` returns *f* (unless
2164 *f* is closed). When a file is used as an iterator, typically in a
2165 :keyword:`for` loop (for example, ``for line in f: print line``), the
2166 :meth:`next` method is called repeatedly. This method returns the next input
2167 line, or raises :exc:`StopIteration` when EOF is hit when the file is open for
2168 reading (behavior is undefined when the file is open for writing). In order to
2169 make a :keyword:`for` loop the most efficient way of looping over the lines of a
2170 file (a very common operation), the :meth:`next` method uses a hidden read-ahead
2171 buffer. As a consequence of using a read-ahead buffer, combining :meth:`next`
2172 with other file methods (like :meth:`readline`) does not work right. However,
2173 using :meth:`seek` to reposition the file to an absolute position will flush the
2176 .. versionadded:: 2.3
2179 .. method:: file.read([size])
2181 Read at most *size* bytes from the file (less if the read hits EOF before
2182 obtaining *size* bytes). If the *size* argument is negative or omitted, read
2183 all data until EOF is reached. The bytes are returned as a string object. An
2184 empty string is returned when EOF is encountered immediately. (For certain
2185 files, like ttys, it makes sense to continue reading after an EOF is hit.) Note
2186 that this method may call the underlying C function :cfunc:`fread` more than
2187 once in an effort to acquire as close to *size* bytes as possible. Also note
2188 that when in non-blocking mode, less data than was requested may be
2189 returned, even if no *size* parameter was given.
2192 This function is simply a wrapper for the underlying
2193 :cfunc:`fread` C function, and will behave the same in corner cases,
2194 such as whether the EOF value is cached.
2197 .. method:: file.readline([size])
2199 Read one entire line from the file. A trailing newline character is kept in the
2200 string (but may be absent when a file ends with an incomplete line). [#]_ If
2201 the *size* argument is present and non-negative, it is a maximum byte count
2202 (including the trailing newline) and an incomplete line may be returned. An
2203 empty string is returned *only* when EOF is encountered immediately.
2207 Unlike ``stdio``'s :cfunc:`fgets`, the returned string contains null characters
2208 (``'\0'``) if they occurred in the input.
2211 .. method:: file.readlines([sizehint])
2213 Read until EOF using :meth:`readline` and return a list containing the lines
2214 thus read. If the optional *sizehint* argument is present, instead of
2215 reading up to EOF, whole lines totalling approximately *sizehint* bytes
2216 (possibly after rounding up to an internal buffer size) are read. Objects
2217 implementing a file-like interface may choose to ignore *sizehint* if it
2218 cannot be implemented, or cannot be implemented efficiently.
2221 .. method:: file.xreadlines()
2223 This method returns the same thing as ``iter(f)``.
2225 .. versionadded:: 2.1
2228 Use ``for line in file`` instead.
2231 .. method:: file.seek(offset[, whence])
2233 Set the file's current position, like ``stdio``'s :cfunc:`fseek`. The *whence*
2234 argument is optional and defaults to ``os.SEEK_SET`` or ``0`` (absolute file
2235 positioning); other values are ``os.SEEK_CUR`` or ``1`` (seek relative to the
2236 current position) and ``os.SEEK_END`` or ``2`` (seek relative to the file's
2237 end). There is no return value.
2239 For example, ``f.seek(2, os.SEEK_CUR)`` advances the position by two and
2240 ``f.seek(-3, os.SEEK_END)`` sets the position to the third to last.
2242 Note that if the file is opened for appending
2243 (mode ``'a'`` or ``'a+'``), any :meth:`seek` operations will be undone at the
2244 next write. If the file is only opened for writing in append mode (mode
2245 ``'a'``), this method is essentially a no-op, but it remains useful for files
2246 opened in append mode with reading enabled (mode ``'a+'``). If the file is
2247 opened in text mode (without ``'b'``), only offsets returned by :meth:`tell` are
2248 legal. Use of other offsets causes undefined behavior.
2250 Note that not all file objects are seekable.
2252 .. versionchanged:: 2.6
2253 Passing float values as offset has been deprecated.
2256 .. method:: file.tell()
2258 Return the file's current position, like ``stdio``'s :cfunc:`ftell`.
2262 On Windows, :meth:`tell` can return illegal values (after an :cfunc:`fgets`)
2263 when reading files with Unix-style line-endings. Use binary mode (``'rb'``) to
2264 circumvent this problem.
2267 .. method:: file.truncate([size])
2269 Truncate the file's size. If the optional *size* argument is present, the file
2270 is truncated to (at most) that size. The size defaults to the current position.
2271 The current file position is not changed. Note that if a specified size exceeds
2272 the file's current size, the result is platform-dependent: possibilities
2273 include that the file may remain unchanged, increase to the specified size as if
2274 zero-filled, or increase to the specified size with undefined new content.
2275 Availability: Windows, many Unix variants.
2278 .. method:: file.write(str)
2280 Write a string to the file. There is no return value. Due to buffering, the
2281 string may not actually show up in the file until the :meth:`flush` or
2282 :meth:`close` method is called.
2285 .. method:: file.writelines(sequence)
2287 Write a sequence of strings to the file. The sequence can be any iterable
2288 object producing strings, typically a list of strings. There is no return value.
2289 (The name is intended to match :meth:`readlines`; :meth:`writelines` does not
2290 add line separators.)
2292 Files support the iterator protocol. Each iteration returns the same result as
2293 ``file.readline()``, and iteration ends when the :meth:`readline` method returns
2296 File objects also offer a number of other interesting attributes. These are not
2297 required for file-like objects, but should be implemented if they make sense for
2298 the particular object.
2301 .. attribute:: file.closed
2303 bool indicating the current state of the file object. This is a read-only
2304 attribute; the :meth:`close` method changes the value. It may not be available
2305 on all file-like objects.
2308 .. attribute:: file.encoding
2310 The encoding that this file uses. When Unicode strings are written to a file,
2311 they will be converted to byte strings using this encoding. In addition, when
2312 the file is connected to a terminal, the attribute gives the encoding that the
2313 terminal is likely to use (that information might be incorrect if the user has
2314 misconfigured the terminal). The attribute is read-only and may not be present
2315 on all file-like objects. It may also be ``None``, in which case the file uses
2316 the system default encoding for converting Unicode strings.
2318 .. versionadded:: 2.3
2321 .. attribute:: file.errors
2323 The Unicode error handler used along with the encoding.
2325 .. versionadded:: 2.6
2328 .. attribute:: file.mode
2330 The I/O mode for the file. If the file was created using the :func:`open`
2331 built-in function, this will be the value of the *mode* parameter. This is a
2332 read-only attribute and may not be present on all file-like objects.
2335 .. attribute:: file.name
2337 If the file object was created using :func:`open`, the name of the file.
2338 Otherwise, some string that indicates the source of the file object, of the
2339 form ``<...>``. This is a read-only attribute and may not be present on all
2343 .. attribute:: file.newlines
2345 If Python was built with the :option:`--with-universal-newlines` option to
2346 :program:`configure` (the default) this read-only attribute exists, and for
2347 files opened in universal newline read mode it keeps track of the types of
2348 newlines encountered while reading the file. The values it can take are
2349 ``'\r'``, ``'\n'``, ``'\r\n'``, ``None`` (unknown, no newlines read yet) or a
2350 tuple containing all the newline types seen, to indicate that multiple newline
2351 conventions were encountered. For files not opened in universal newline read
2352 mode the value of this attribute will be ``None``.
2355 .. attribute:: file.softspace
2357 Boolean that indicates whether a space character needs to be printed before
2358 another value when using the :keyword:`print` statement. Classes that are trying
2359 to simulate a file object should also have a writable :attr:`softspace`
2360 attribute, which should be initialized to zero. This will be automatic for most
2361 classes implemented in Python (care may be needed for objects that override
2362 attribute access); types implemented in C will have to provide a writable
2363 :attr:`softspace` attribute.
2367 This attribute is not used to control the :keyword:`print` statement, but to
2368 allow the implementation of :keyword:`print` to keep track of its internal
2377 :class:`memoryview`\s allow Python code to access the internal data of an object
2378 that supports the buffer protocol without copying. Memory can be interpreted as
2379 simple bytes or complex data structures.
2381 .. class:: memoryview(obj)
2383 Create a :class:`memoryview` that references *obj*. *obj* must support the
2384 buffer protocol. Builtin objects that support the buffer protocol include
2385 :class:`str` and :class:`bytearray` (but not :class:`unicode`).
2387 ``len(view)`` returns the total number of bytes in the memoryview, *view*.
2389 A :class:`memoryview` supports slicing to expose its data. Taking a single
2390 index will return a single byte. Full slicing will result in a subview::
2392 >>> v = memoryview('abcefg')
2398 <memory at 0x77ab28>
2402 <memory at 0x744f18>
2406 If the object the memory view is over supports changing its data, the
2407 memoryview supports slice assignment::
2409 >>> data = bytearray('abcefg')
2410 >>> v = memoryview(data)
2415 bytearray(b'zbcefg')
2418 bytearray(b'z123fg')
2420 Traceback (most recent call last):
2421 File "<stdin>", line 1, in <module>
2422 ValueError: cannot modify size of memoryview object
2424 Notice how the size of the memoryview object can not be changed.
2427 :class:`memoryview` has two methods:
2429 .. method:: tobytes()
2431 Return the data in the buffer as a bytestring (an object of class
2434 .. method:: tolist()
2436 Return the data in the buffer as a list of integers. ::
2438 >>> memoryview(b'abc').tolist()
2441 There are also several readonly attributes available:
2443 .. attribute:: format
2445 A string containing the format (in :mod:`struct` module style) for each
2446 element in the view. This defaults to ``'B'``, a simple bytestring.
2448 .. attribute:: itemsize
2450 The size in bytes of each element of the memoryview.
2452 .. attribute:: shape
2454 A tuple of integers the length of :attr:`ndim` giving the shape of the
2455 memory as a N-dimensional array.
2459 An integer indicating how many dimensions of a multi-dimensional array the
2462 .. attribute:: strides
2464 A tuple of integers the length of :attr:`ndim` giving the size in bytes to
2465 access each element for each dimension of the array.
2467 .. memoryview.suboffsets isn't documented because it only seems useful for C
2470 .. _typecontextmanager:
2472 Context Manager Types
2473 =====================
2475 .. versionadded:: 2.5
2478 single: context manager
2479 single: context management protocol
2480 single: protocol; context management
2482 Python's :keyword:`with` statement supports the concept of a runtime context
2483 defined by a context manager. This is implemented using two separate methods
2484 that allow user-defined classes to define a runtime context that is entered
2485 before the statement body is executed and exited when the statement ends.
2487 The :dfn:`context management protocol` consists of a pair of methods that need
2488 to be provided for a context manager object to define a runtime context:
2491 .. method:: contextmanager.__enter__()
2493 Enter the runtime context and return either this object or another object
2494 related to the runtime context. The value returned by this method is bound to
2495 the identifier in the :keyword:`as` clause of :keyword:`with` statements using
2496 this context manager.
2498 An example of a context manager that returns itself is a file object. File
2499 objects return themselves from __enter__() to allow :func:`open` to be used as
2500 the context expression in a :keyword:`with` statement.
2502 An example of a context manager that returns a related object is the one
2503 returned by :func:`decimal.localcontext`. These managers set the active
2504 decimal context to a copy of the original decimal context and then return the
2505 copy. This allows changes to be made to the current decimal context in the body
2506 of the :keyword:`with` statement without affecting code outside the
2507 :keyword:`with` statement.
2510 .. method:: contextmanager.__exit__(exc_type, exc_val, exc_tb)
2512 Exit the runtime context and return a Boolean flag indicating if any exception
2513 that occurred should be suppressed. If an exception occurred while executing the
2514 body of the :keyword:`with` statement, the arguments contain the exception type,
2515 value and traceback information. Otherwise, all three arguments are ``None``.
2517 Returning a true value from this method will cause the :keyword:`with` statement
2518 to suppress the exception and continue execution with the statement immediately
2519 following the :keyword:`with` statement. Otherwise the exception continues
2520 propagating after this method has finished executing. Exceptions that occur
2521 during execution of this method will replace any exception that occurred in the
2522 body of the :keyword:`with` statement.
2524 The exception passed in should never be reraised explicitly - instead, this
2525 method should return a false value to indicate that the method completed
2526 successfully and does not want to suppress the raised exception. This allows
2527 context management code (such as ``contextlib.nested``) to easily detect whether
2528 or not an :meth:`__exit__` method has actually failed.
2530 Python defines several context managers to support easy thread synchronisation,
2531 prompt closure of files or other objects, and simpler manipulation of the active
2532 decimal arithmetic context. The specific types are not treated specially beyond
2533 their implementation of the context management protocol. See the
2534 :mod:`contextlib` module for some examples.
2536 Python's :term:`generator`\s and the ``contextlib.contextfactory`` :term:`decorator`
2537 provide a convenient way to implement these protocols. If a generator function is
2538 decorated with the ``contextlib.contextfactory`` decorator, it will return a
2539 context manager implementing the necessary :meth:`__enter__` and
2540 :meth:`__exit__` methods, rather than the iterator produced by an undecorated
2543 Note that there is no specific slot for any of these methods in the type
2544 structure for Python objects in the Python/C API. Extension types wanting to
2545 define these methods must provide them as a normal Python accessible method.
2546 Compared to the overhead of setting up the runtime context, the overhead of a
2547 single class dictionary lookup is negligible.
2552 Other Built-in Types
2553 ====================
2555 The interpreter supports several other kinds of objects. Most of these support
2556 only one or two operations.
2564 The only special operation on a module is attribute access: ``m.name``, where
2565 *m* is a module and *name* accesses a name defined in *m*'s symbol table.
2566 Module attributes can be assigned to. (Note that the :keyword:`import`
2567 statement is not, strictly speaking, an operation on a module object; ``import
2568 foo`` does not require a module object named *foo* to exist, rather it requires
2569 an (external) *definition* for a module named *foo* somewhere.)
2571 A special member of every module is :attr:`__dict__`. This is the dictionary
2572 containing the module's symbol table. Modifying this dictionary will actually
2573 change the module's symbol table, but direct assignment to the :attr:`__dict__`
2574 attribute is not possible (you can write ``m.__dict__['a'] = 1``, which defines
2575 ``m.a`` to be ``1``, but you can't write ``m.__dict__ = {}``). Modifying
2576 :attr:`__dict__` directly is not recommended.
2578 Modules built into the interpreter are written like this: ``<module 'sys'
2579 (built-in)>``. If loaded from a file, they are written as ``<module 'os' from
2580 '/usr/local/lib/pythonX.Y/os.pyc'>``.
2585 Classes and Class Instances
2586 ---------------------------
2588 See :ref:`objects` and :ref:`class` for these.
2596 Function objects are created by function definitions. The only operation on a
2597 function object is to call it: ``func(argument-list)``.
2599 There are really two flavors of function objects: built-in functions and
2600 user-defined functions. Both support the same operation (to call the function),
2601 but the implementation is different, hence the different object types.
2603 See :ref:`function` for more information.
2611 .. index:: object: method
2613 Methods are functions that are called using the attribute notation. There are
2614 two flavors: built-in methods (such as :meth:`append` on lists) and class
2615 instance methods. Built-in methods are described with the types that support
2618 The implementation adds two special read-only attributes to class instance
2619 methods: ``m.im_self`` is the object on which the method operates, and
2620 ``m.im_func`` is the function implementing the method. Calling ``m(arg-1,
2621 arg-2, ..., arg-n)`` is completely equivalent to calling ``m.im_func(m.im_self,
2622 arg-1, arg-2, ..., arg-n)``.
2624 Class instance methods are either *bound* or *unbound*, referring to whether the
2625 method was accessed through an instance or a class, respectively. When a method
2626 is unbound, its ``im_self`` attribute will be ``None`` and if called, an
2627 explicit ``self`` object must be passed as the first argument. In this case,
2628 ``self`` must be an instance of the unbound method's class (or a subclass of
2629 that class), otherwise a :exc:`TypeError` is raised.
2631 Like function objects, methods objects support getting arbitrary attributes.
2632 However, since method attributes are actually stored on the underlying function
2633 object (``meth.im_func``), setting method attributes on either bound or unbound
2634 methods is disallowed. Attempting to set a method attribute results in a
2635 :exc:`TypeError` being raised. In order to set a method attribute, you need to
2636 explicitly set it on the underlying function object::
2643 c.method.im_func.whoami = 'my name is c'
2645 See :ref:`types` for more information.
2648 .. _bltin-code-objects:
2653 .. index:: object: code
2657 single: func_code (function object attribute)
2659 Code objects are used by the implementation to represent "pseudo-compiled"
2660 executable Python code such as a function body. They differ from function
2661 objects because they don't contain a reference to their global execution
2662 environment. Code objects are returned by the built-in :func:`compile` function
2663 and can be extracted from function objects through their :attr:`func_code`
2664 attribute. See also the :mod:`code` module.
2670 A code object can be executed or evaluated by passing it (instead of a source
2671 string) to the :keyword:`exec` statement or the built-in :func:`eval` function.
2673 See :ref:`types` for more information.
2676 .. _bltin-type-objects:
2685 Type objects represent the various object types. An object's type is accessed
2686 by the built-in function :func:`type`. There are no special operations on
2687 types. The standard module :mod:`types` defines names for all standard built-in
2690 Types are written like this: ``<type 'int'>``.
2693 .. _bltin-null-object:
2698 This object is returned by functions that don't explicitly return a value. It
2699 supports no special operations. There is exactly one null object, named
2700 ``None`` (a built-in name).
2702 It is written as ``None``.
2705 .. _bltin-ellipsis-object:
2710 This object is used by extended slice notation (see :ref:`slicings`). It
2711 supports no special operations. There is exactly one ellipsis object, named
2712 :const:`Ellipsis` (a built-in name).
2714 It is written as ``Ellipsis``.
2720 Boolean values are the two constant objects ``False`` and ``True``. They are
2721 used to represent truth values (although other values can also be considered
2722 false or true). In numeric contexts (for example when used as the argument to
2723 an arithmetic operator), they behave like the integers 0 and 1, respectively.
2724 The built-in function :func:`bool` can be used to cast any value to a Boolean,
2725 if the value can be interpreted as a truth value (see section Truth Value
2731 pair: Boolean; values
2733 They are written as ``False`` and ``True``, respectively.
2741 See :ref:`types` for this information. It describes stack frame objects,
2742 traceback objects, and slice objects.
2750 The implementation adds a few special read-only attributes to several object
2751 types, where they are relevant. Some of these are not reported by the
2752 :func:`dir` built-in function.
2755 .. attribute:: object.__dict__
2757 A dictionary or other mapping object used to store an object's (writable)
2761 .. attribute:: object.__methods__
2764 Use the built-in function :func:`dir` to get a list of an object's attributes.
2765 This attribute is no longer available.
2768 .. attribute:: object.__members__
2771 Use the built-in function :func:`dir` to get a list of an object's attributes.
2772 This attribute is no longer available.
2775 .. attribute:: instance.__class__
2777 The class to which a class instance belongs.
2780 .. attribute:: class.__bases__
2782 The tuple of base classes of a class object. If there are no base classes, this
2783 will be an empty tuple.
2786 .. attribute:: class.__name__
2788 The name of the class or type.
2791 The following attributes are only supported by :term:`new-style class`\ es.
2793 .. attribute:: class.__mro__
2795 This attribute is a tuple of classes that are considered when looking for
2796 base classes during method resolution.
2799 .. method:: class.mro()
2801 This method can be overridden by a metaclass to customize the method
2802 resolution order for its instances. It is called at class instantiation, and
2803 its result is stored in :attr:`__mro__`.
2806 .. method:: class.__subclasses__
2808 Each new-style class keeps a list of weak references to its immediate
2809 subclasses. This method returns a list of all those references still alive.
2812 >>> int.__subclasses__()
2816 .. rubric:: Footnotes
2818 .. [#] Additional information on these special methods may be found in the Python
2819 Reference Manual (:ref:`customization`).
2821 .. [#] As a consequence, the list ``[1, 2]`` is considered equal to ``[1.0, 2.0]``, and
2822 similarly for tuples.
2824 .. [#] They must have since the parser can't tell the type of the operands.
2826 .. [#] To format only a tuple you should therefore provide a singleton tuple whose only
2827 element is the tuple to be formatted.
2829 .. [#] These numbers are fairly arbitrary. They are intended to avoid printing endless
2830 strings of meaningless digits without hampering correct use and without having
2831 to know the exact precision of floating point values on a particular machine.
2833 .. [#] The advantage of leaving the newline on is that returning an empty string is
2834 then an unambiguous EOF indication. It is also possible (in cases where it
2835 might matter, for example, if you want to make an exact copy of a file while
2836 scanning its lines) to tell whether the last line of a file ended in a newline
2837 or not (yes this happens!).