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.
133 pair: chaining; comparisons
134 pair: operator; comparison
144 Comparison operations are supported by all objects. They all have the same
145 priority (which is higher than that of the Boolean operations). Comparisons can
146 be chained arbitrarily; for example, ``x < y <= z`` is equivalent to ``x < y and
147 y <= z``, except that *y* is evaluated only once (but in both cases *z* is not
148 evaluated at all when ``x < y`` is found to be false).
150 This table summarizes the comparison operations:
152 +------------+-------------------------+-------+
153 | Operation | Meaning | Notes |
154 +============+=========================+=======+
155 | ``<`` | strictly less than | |
156 +------------+-------------------------+-------+
157 | ``<=`` | less than or equal | |
158 +------------+-------------------------+-------+
159 | ``>`` | strictly greater than | |
160 +------------+-------------------------+-------+
161 | ``>=`` | greater than or equal | |
162 +------------+-------------------------+-------+
164 +------------+-------------------------+-------+
165 | ``!=`` | not equal | \(1) |
166 +------------+-------------------------+-------+
167 | ``is`` | object identity | |
168 +------------+-------------------------+-------+
169 | ``is not`` | negated object identity | |
170 +------------+-------------------------+-------+
175 ``!=`` can also be written ``<>``, but this is an obsolete usage
176 kept for backwards compatibility only. New code should always use
180 pair: object; numeric
181 pair: objects; comparing
183 Objects of different types, except different numeric types and different string
184 types, never compare equal; such objects are ordered consistently but
185 arbitrarily (so that sorting a heterogeneous array yields a consistent result).
186 Furthermore, some types (for example, file objects) support only a degenerate
187 notion of comparison where any two objects of that type are unequal. Again,
188 such objects are ordered arbitrarily but consistently. The ``<``, ``<=``, ``>``
189 and ``>=`` operators will raise a :exc:`TypeError` exception when any operand is
192 .. index:: single: __cmp__() (instance method)
194 Instances of a class normally compare as non-equal unless the class defines the
195 :meth:`__cmp__` method. Refer to :ref:`customization`) for information on the
196 use of this method to effect object comparisons.
200 Objects of different types except numbers are ordered by their type names;
201 objects of the same types that don't support proper comparison are ordered by
208 Two more operations with the same syntactic priority, ``in`` and ``not in``, are
209 supported only by sequence types (below).
214 Numeric Types --- :class:`int`, :class:`float`, :class:`long`, :class:`complex`
215 ===============================================================================
222 object: floating point
223 object: complex number
226 There are four distinct numeric types: :dfn:`plain integers`, :dfn:`long
227 integers`, :dfn:`floating point numbers`, and :dfn:`complex numbers`. In
228 addition, Booleans are a subtype of plain integers. Plain integers (also just
229 called :dfn:`integers`) are implemented using :ctype:`long` in C, which gives
230 them at least 32 bits of precision (``sys.maxint`` is always set to the maximum
231 plain integer value for the current platform, the minimum value is
232 ``-sys.maxint - 1``). Long integers have unlimited precision. Floating point
233 numbers are implemented using :ctype:`double` in C. All bets on their precision
234 are off unless you happen to know the machine you are working with.
236 Complex numbers have a real and imaginary part, which are each implemented using
237 :ctype:`double` in C. To extract these parts from a complex number *z*, use
238 ``z.real`` and ``z.imag``.
241 pair: numeric; literals
242 pair: integer; literals
243 triple: long; integer; literals
244 pair: floating point; literals
245 pair: complex number; literals
246 pair: hexadecimal; literals
247 pair: octal; literals
249 Numbers are created by numeric literals or as the result of built-in functions
250 and operators. Unadorned integer literals (including binary, hex, and octal
251 numbers) yield plain integers unless the value they denote is too large to be
252 represented as a plain integer, in which case they yield a long integer.
253 Integer literals with an ``'L'`` or ``'l'`` suffix yield long integers (``'L'``
254 is preferred because ``1l`` looks too much like eleven!). Numeric literals
255 containing a decimal point or an exponent sign yield floating point numbers.
256 Appending ``'j'`` or ``'J'`` to a numeric literal yields a complex number with a
257 zero real part. A complex numeric literal is the sum of a real and an imaginary
274 Python fully supports mixed arithmetic: when a binary arithmetic operator has
275 operands of different numeric types, the operand with the "narrower" type is
276 widened to that of the other, where plain integer is narrower than long integer
277 is narrower than floating point is narrower than complex. Comparisons between
278 numbers of mixed type use the same rule. [#]_ The constructors :func:`int`,
279 :func:`long`, :func:`float`, and :func:`complex` can be used to produce numbers
282 All built-in numeric types support the following operations. See
283 :ref:`power` and later sections for the operators' priorities.
285 +--------------------+---------------------------------+--------+
286 | Operation | Result | Notes |
287 +====================+=================================+========+
288 | ``x + y`` | sum of *x* and *y* | |
289 +--------------------+---------------------------------+--------+
290 | ``x - y`` | difference of *x* and *y* | |
291 +--------------------+---------------------------------+--------+
292 | ``x * y`` | product of *x* and *y* | |
293 +--------------------+---------------------------------+--------+
294 | ``x / y`` | quotient of *x* and *y* | \(1) |
295 +--------------------+---------------------------------+--------+
296 | ``x // y`` | (floored) quotient of *x* and | (4)(5) |
298 +--------------------+---------------------------------+--------+
299 | ``x % y`` | remainder of ``x / y`` | \(4) |
300 +--------------------+---------------------------------+--------+
301 | ``-x`` | *x* negated | |
302 +--------------------+---------------------------------+--------+
303 | ``+x`` | *x* unchanged | |
304 +--------------------+---------------------------------+--------+
305 | ``abs(x)`` | absolute value or magnitude of | \(3) |
307 +--------------------+---------------------------------+--------+
308 | ``int(x)`` | *x* converted to integer | \(2) |
309 +--------------------+---------------------------------+--------+
310 | ``long(x)`` | *x* converted to long integer | \(2) |
311 +--------------------+---------------------------------+--------+
312 | ``float(x)`` | *x* converted to floating point | \(6) |
313 +--------------------+---------------------------------+--------+
314 | ``complex(re,im)`` | a complex number with real part | |
315 | | *re*, imaginary part *im*. | |
316 | | *im* defaults to zero. | |
317 +--------------------+---------------------------------+--------+
318 | ``c.conjugate()`` | conjugate of the complex number | |
319 | | *c*. (Identity on real numbers) | |
320 +--------------------+---------------------------------+--------+
321 | ``divmod(x, y)`` | the pair ``(x // y, x % y)`` | (3)(4) |
322 +--------------------+---------------------------------+--------+
323 | ``pow(x, y)`` | *x* to the power *y* | (3)(7) |
324 +--------------------+---------------------------------+--------+
325 | ``x ** y`` | *x* to the power *y* | \(7) |
326 +--------------------+---------------------------------+--------+
329 triple: operations on; numeric; types
330 single: conjugate() (complex number method)
336 pair: integer; division
337 triple: long; integer; division
339 For (plain or long) integer division, the result is an integer. The result is
340 always rounded towards minus infinity: 1/2 is 0, (-1)/2 is -1, 1/(-2) is -1, and
341 (-1)/(-2) is 0. Note that the result is a long integer if either operand is a
342 long integer, regardless of the numeric value.
347 single: floor() (in module math)
348 single: ceil() (in module math)
349 single: trunc() (in module math)
350 pair: numeric; conversions
352 Conversion from floats using :func:`int` or :func:`long` truncates toward
353 zero like the related function, :func:`math.trunc`. Use the function
354 :func:`math.floor` to round downward and :func:`math.ceil` to round
358 See :ref:`built-in-funcs` for a full description.
361 Complex floor division operator, modulo operator, and :func:`divmod`.
364 Instead convert to float using :func:`abs` if appropriate.
367 Also referred to as integer division. The resultant value is a whole integer,
368 though the result's type is not necessarily int.
371 float also accepts the strings "nan" and "inf" with an optional prefix "+"
372 or "-" for Not a Number (NaN) and positive or negative infinity.
374 .. versionadded:: 2.6
377 Python defines ``pow(0, 0)`` and ``0 ** 0`` to be ``1``, as is common for
378 programming languages.
380 All :class:`numbers.Real` types (:class:`int`, :class:`long`, and
381 :class:`float`) also include the following operations:
383 +--------------------+------------------------------------+--------+
384 | Operation | Result | Notes |
385 +====================+====================================+========+
386 | ``math.trunc(x)`` | *x* truncated to Integral | |
387 +--------------------+------------------------------------+--------+
388 | ``round(x[, n])`` | *x* rounded to n digits, | |
389 | | rounding half to even. If n is | |
390 | | omitted, it defaults to 0. | |
391 +--------------------+------------------------------------+--------+
392 | ``math.floor(x)`` | the greatest integral float <= *x* | |
393 +--------------------+------------------------------------+--------+
394 | ``math.ceil(x)`` | the least integral float >= *x* | |
395 +--------------------+------------------------------------+--------+
397 .. XXXJH exceptions: overflow (when? what operations?) zerodivision
402 Bit-string Operations on Integer Types
403 --------------------------------------
406 triple: operations on; integer; types
407 pair: bit-string; operations
408 pair: shifting; operations
409 pair: masking; operations
415 Plain and long integer types support additional operations that make sense only
416 for bit-strings. Negative numbers are treated as their 2's complement value
417 (for long integers, this assumes a sufficiently large number of bits that no
418 overflow occurs during the operation).
420 The priorities of the binary bitwise operations are all lower than the numeric
421 operations and higher than the comparisons; the unary operation ``~`` has the
422 same priority as the other unary numeric operations (``+`` and ``-``).
424 This table lists the bit-string operations sorted in ascending priority:
426 +------------+--------------------------------+----------+
427 | Operation | Result | Notes |
428 +============+================================+==========+
429 | ``x | y`` | bitwise :dfn:`or` of *x* and | |
431 +------------+--------------------------------+----------+
432 | ``x ^ y`` | bitwise :dfn:`exclusive or` of | |
434 +------------+--------------------------------+----------+
435 | ``x & y`` | bitwise :dfn:`and` of *x* and | |
437 +------------+--------------------------------+----------+
438 | ``x << n`` | *x* shifted left by *n* bits | (1)(2) |
439 +------------+--------------------------------+----------+
440 | ``x >> n`` | *x* shifted right by *n* bits | (1)(3) |
441 +------------+--------------------------------+----------+
442 | ``~x`` | the bits of *x* inverted | |
443 +------------+--------------------------------+----------+
448 Negative shift counts are illegal and cause a :exc:`ValueError` to be raised.
451 A left shift by *n* bits is equivalent to multiplication by ``pow(2, n)``. A
452 long integer is returned if the result exceeds the range of plain integers.
455 A right shift by *n* bits is equivalent to division by ``pow(2, n)``.
458 Additional Methods on Integer Types
459 -----------------------------------
461 .. method:: int.bit_length()
462 .. method:: long.bit_length()
464 Return the number of bits necessary to represent an integer in binary,
465 excluding the sign and leading zeros::
473 More precisely, if ``x`` is nonzero, then ``x.bit_length()`` is the
474 unique positive integer ``k`` such that ``2**(k-1) <= abs(x) < 2**k``.
475 Equivalently, when ``abs(x)`` is small enough to have a correctly
476 rounded logarithm, then ``k = 1 + int(log(abs(x), 2))``.
477 If ``x`` is zero, then ``x.bit_length()`` returns ``0``.
481 def bit_length(self):
482 s = bin(self) # binary representation: bin(-37) --> '-0b100101'
483 s = s.lstrip('-0b') # remove leading zeros and minus sign
484 return len(s) # len('100101') --> 6
486 .. versionadded:: 2.7
489 Additional Methods on Float
490 ---------------------------
492 The float type has some additional methods.
494 .. method:: float.as_integer_ratio()
496 Return a pair of integers whose ratio is exactly equal to the
497 original float and with a positive denominator. Raises
498 :exc:`OverflowError` on infinities and a :exc:`ValueError` on
501 .. versionadded:: 2.6
503 Two methods support conversion to
504 and from hexadecimal strings. Since Python's floats are stored
505 internally as binary numbers, converting a float to or from a
506 *decimal* string usually involves a small rounding error. In
507 contrast, hexadecimal strings allow exact representation and
508 specification of floating-point numbers. This can be useful when
509 debugging, and in numerical work.
512 .. method:: float.hex()
514 Return a representation of a floating-point number as a hexadecimal
515 string. For finite floating-point numbers, this representation
516 will always include a leading ``0x`` and a trailing ``p`` and
519 .. versionadded:: 2.6
522 .. method:: float.fromhex(s)
524 Class method to return the float represented by a hexadecimal
525 string *s*. The string *s* may have leading and trailing
528 .. versionadded:: 2.6
531 Note that :meth:`float.hex` is an instance method, while
532 :meth:`float.fromhex` is a class method.
534 A hexadecimal string takes the form::
536 [sign] ['0x'] integer ['.' fraction] ['p' exponent]
538 where the optional ``sign`` may by either ``+`` or ``-``, ``integer``
539 and ``fraction`` are strings of hexadecimal digits, and ``exponent``
540 is a decimal integer with an optional leading sign. Case is not
541 significant, and there must be at least one hexadecimal digit in
542 either the integer or the fraction. This syntax is similar to the
543 syntax specified in section 6.4.4.2 of the C99 standard, and also to
544 the syntax used in Java 1.5 onwards. In particular, the output of
545 :meth:`float.hex` is usable as a hexadecimal floating-point literal in
546 C or Java code, and hexadecimal strings produced by C's ``%a`` format
547 character or Java's ``Double.toHexString`` are accepted by
548 :meth:`float.fromhex`.
551 Note that the exponent is written in decimal rather than hexadecimal,
552 and that it gives the power of 2 by which to multiply the coefficient.
553 For example, the hexadecimal string ``0x3.a7p10`` represents the
554 floating-point number ``(3 + 10./16 + 7./16**2) * 2.0**10``, or
557 >>> float.fromhex('0x3.a7p10')
561 Applying the reverse conversion to ``3740.0`` gives a different
562 hexadecimal string representing the same number::
564 >>> float.hex(3740.0)
565 '0x1.d380000000000p+11'
573 .. versionadded:: 2.2
576 single: iterator protocol
577 single: protocol; iterator
578 single: sequence; iteration
579 single: container; iteration over
581 Python supports a concept of iteration over containers. This is implemented
582 using two distinct methods; these are used to allow user-defined classes to
583 support iteration. Sequences, described below in more detail, always support
584 the iteration methods.
586 One method needs to be defined for container objects to provide iteration
589 .. XXX duplicated in reference/datamodel!
591 .. method:: container.__iter__()
593 Return an iterator object. The object is required to support the iterator
594 protocol described below. If a container supports different types of
595 iteration, additional methods can be provided to specifically request
596 iterators for those iteration types. (An example of an object supporting
597 multiple forms of iteration would be a tree structure which supports both
598 breadth-first and depth-first traversal.) This method corresponds to the
599 :attr:`tp_iter` slot of the type structure for Python objects in the Python/C
602 The iterator objects themselves are required to support the following two
603 methods, which together form the :dfn:`iterator protocol`:
606 .. method:: iterator.__iter__()
608 Return the iterator object itself. This is required to allow both containers
609 and iterators to be used with the :keyword:`for` and :keyword:`in` statements.
610 This method corresponds to the :attr:`tp_iter` slot of the type structure for
611 Python objects in the Python/C API.
614 .. method:: iterator.next()
616 Return the next item from the container. If there are no further items, raise
617 the :exc:`StopIteration` exception. This method corresponds to the
618 :attr:`tp_iternext` slot of the type structure for Python objects in the
621 Python defines several iterator objects to support iteration over general and
622 specific sequence types, dictionaries, and other more specialized forms. The
623 specific types are not important beyond their implementation of the iterator
626 The intention of the protocol is that once an iterator's :meth:`next` method
627 raises :exc:`StopIteration`, it will continue to do so on subsequent calls.
628 Implementations that do not obey this property are deemed broken. (This
629 constraint was added in Python 2.3; in Python 2.2, various iterators are broken
630 according to this rule.)
638 Python's :term:`generator`\s provide a convenient way to implement the iterator
639 protocol. If a container object's :meth:`__iter__` method is implemented as a
640 generator, it will automatically return an iterator object (technically, a
641 generator object) supplying the :meth:`__iter__` and :meth:`next` methods. More
642 information about generators can be found in :ref:`the documentation for the
643 yield expression <yieldexpr>`.
648 Sequence Types --- :class:`str`, :class:`unicode`, :class:`list`, :class:`tuple`, :class:`buffer`, :class:`xrange`
649 ==================================================================================================================
651 There are six sequence types: strings, Unicode strings, lists, tuples, buffers,
654 For other containers see the built in :class:`dict` and :class:`set` classes,
655 and the :mod:`collections` module.
667 String literals are written in single or double quotes: ``'xyzzy'``,
668 ``"frobozz"``. See :ref:`strings` for more about string literals.
669 Unicode strings are much like strings, but are specified in the syntax
670 using a preceding ``'u'`` character: ``u'abc'``, ``u"def"``. In addition
671 to the functionality described here, there are also string-specific
672 methods described in the :ref:`string-methods` section. Lists are
673 constructed with square brackets, separating items with commas: ``[a, b, c]``.
674 Tuples are constructed by the comma operator (not within square
675 brackets), with or without enclosing parentheses, but an empty tuple
676 must have the enclosing parentheses, such as ``a, b, c`` or ``()``. A
677 single item tuple must have a trailing comma, such as ``(d,)``.
679 Buffer objects are not directly supported by Python syntax, but can be created
680 by calling the built-in function :func:`buffer`. They don't support
681 concatenation or repetition.
683 Objects of type xrange are similar to buffers in that there is no specific syntax to
684 create them, but they are created using the :func:`xrange` function. They don't
685 support slicing, concatenation or repetition, and using ``in``, ``not in``,
686 :func:`min` or :func:`max` on them is inefficient.
688 Most sequence types support the following operations. The ``in`` and ``not in``
689 operations have the same priorities as the comparison operations. The ``+`` and
690 ``*`` operations have the same priority as the corresponding numeric operations.
691 [#]_ Additional methods are provided for :ref:`typesseq-mutable`.
693 This table lists the sequence operations sorted in ascending priority
694 (operations in the same box have the same priority). In the table, *s* and *t*
695 are sequences of the same type; *n*, *i* and *j* are integers:
697 +------------------+--------------------------------+----------+
698 | Operation | Result | Notes |
699 +==================+================================+==========+
700 | ``x in s`` | ``True`` if an item of *s* is | \(1) |
701 | | equal to *x*, else ``False`` | |
702 +------------------+--------------------------------+----------+
703 | ``x not in s`` | ``False`` if an item of *s* is | \(1) |
704 | | equal to *x*, else ``True`` | |
705 +------------------+--------------------------------+----------+
706 | ``s + t`` | the concatenation of *s* and | \(6) |
708 +------------------+--------------------------------+----------+
709 | ``s * n, n * s`` | *n* shallow copies of *s* | \(2) |
711 +------------------+--------------------------------+----------+
712 | ``s[i]`` | *i*'th item of *s*, origin 0 | \(3) |
713 +------------------+--------------------------------+----------+
714 | ``s[i:j]`` | slice of *s* from *i* to *j* | (3)(4) |
715 +------------------+--------------------------------+----------+
716 | ``s[i:j:k]`` | slice of *s* from *i* to *j* | (3)(5) |
717 | | with step *k* | |
718 +------------------+--------------------------------+----------+
719 | ``len(s)`` | length of *s* | |
720 +------------------+--------------------------------+----------+
721 | ``min(s)`` | smallest item of *s* | |
722 +------------------+--------------------------------+----------+
723 | ``max(s)`` | largest item of *s* | |
724 +------------------+--------------------------------+----------+
726 Sequence types also support comparisons. In particular, tuples and lists
727 are compared lexicographically by comparing corresponding
728 elements. This means that to compare equal, every element must compare
729 equal and the two sequences must be of the same type and have the same
730 length. (For full details see :ref:`comparisons` in the language
734 triple: operations on; sequence; types
738 pair: concatenation; operation
739 pair: repetition; operation
740 pair: subscript; operation
741 pair: slice; operation
742 pair: extended slice; operation
749 When *s* is a string or Unicode string object the ``in`` and ``not in``
750 operations act like a substring test. In Python versions before 2.3, *x* had to
751 be a string of length 1. In Python 2.3 and beyond, *x* may be a string of any
755 Values of *n* less than ``0`` are treated as ``0`` (which yields an empty
756 sequence of the same type as *s*). Note also that the copies are shallow;
757 nested structures are not copied. This often haunts new Python programmers;
763 >>> lists[0].append(3)
767 What has happened is that ``[[]]`` is a one-element list containing an empty
768 list, so all three elements of ``[[]] * 3`` are (pointers to) this single empty
769 list. Modifying any of the elements of ``lists`` modifies this single list.
770 You can create a list of different lists this way:
772 >>> lists = [[] for i in range(3)]
773 >>> lists[0].append(3)
774 >>> lists[1].append(5)
775 >>> lists[2].append(7)
780 If *i* or *j* is negative, the index is relative to the end of the string:
781 ``len(s) + i`` or ``len(s) + j`` is substituted. But note that ``-0`` is still
785 The slice of *s* from *i* to *j* is defined as the sequence of items with index
786 *k* such that ``i <= k < j``. If *i* or *j* is greater than ``len(s)``, use
787 ``len(s)``. If *i* is omitted or ``None``, use ``0``. If *j* is omitted or
788 ``None``, use ``len(s)``. If *i* is greater than or equal to *j*, the slice is
792 The slice of *s* from *i* to *j* with step *k* is defined as the sequence of
793 items with index ``x = i + n*k`` such that ``0 <= n < (j-i)/k``. In other words,
794 the indices are ``i``, ``i+k``, ``i+2*k``, ``i+3*k`` and so on, stopping when
795 *j* is reached (but never including *j*). If *i* or *j* is greater than
796 ``len(s)``, use ``len(s)``. If *i* or *j* are omitted or ``None``, they become
797 "end" values (which end depends on the sign of *k*). Note, *k* cannot be zero.
798 If *k* is ``None``, it is treated like ``1``.
803 If *s* and *t* are both strings, some Python implementations such as
804 CPython can usually perform an in-place optimization for assignments of
805 the form ``s = s + t`` or ``s += t``. When applicable, this optimization
806 makes quadratic run-time much less likely. This optimization is both
807 version and implementation dependent. For performance sensitive code, it
808 is preferable to use the :meth:`str.join` method which assures consistent
809 linear concatenation performance across versions and implementations.
811 .. versionchanged:: 2.4
812 Formerly, string concatenation never occurred in-place.
820 .. index:: pair: string; methods
822 Below are listed the string methods which both 8-bit strings and
823 Unicode objects support.
825 In addition, Python's strings support the sequence type methods
826 described in the :ref:`typesseq` section. To output formatted strings
827 use template strings or the ``%`` operator described in the
828 :ref:`string-formatting` section. Also, see the :mod:`re` module for
829 string functions based on regular expressions.
831 .. method:: str.capitalize()
833 Return a copy of the string with only its first character capitalized.
835 For 8-bit strings, this method is locale-dependent.
838 .. method:: str.center(width[, fillchar])
840 Return centered in a string of length *width*. Padding is done using the
841 specified *fillchar* (default is a space).
843 .. versionchanged:: 2.4
844 Support for the *fillchar* argument.
847 .. method:: str.count(sub[, start[, end]])
849 Return the number of non-overlapping occurrences of substring *sub* in the
850 range [*start*, *end*]. Optional arguments *start* and *end* are
851 interpreted as in slice notation.
854 .. method:: str.decode([encoding[, errors]])
856 Decodes the string using the codec registered for *encoding*. *encoding*
857 defaults to the default string encoding. *errors* may be given to set a
858 different error handling scheme. The default is ``'strict'``, meaning that
859 encoding errors raise :exc:`UnicodeError`. Other possible values are
860 ``'ignore'``, ``'replace'`` and any other name registered via
861 :func:`codecs.register_error`, see section :ref:`codec-base-classes`.
863 .. versionadded:: 2.2
865 .. versionchanged:: 2.3
866 Support for other error handling schemes added.
868 .. versionchanged:: 2.7
869 Support for keyword arguments added.
871 .. method:: str.encode([encoding[,errors]])
873 Return an encoded version of the string. Default encoding is the current
874 default string encoding. *errors* may be given to set a different error
875 handling scheme. The default for *errors* is ``'strict'``, meaning that
876 encoding errors raise a :exc:`UnicodeError`. Other possible values are
877 ``'ignore'``, ``'replace'``, ``'xmlcharrefreplace'``, ``'backslashreplace'`` and
878 any other name registered via :func:`codecs.register_error`, see section
879 :ref:`codec-base-classes`. For a list of possible encodings, see section
880 :ref:`standard-encodings`.
882 .. versionadded:: 2.0
884 .. versionchanged:: 2.3
885 Support for ``'xmlcharrefreplace'`` and ``'backslashreplace'`` and other error
886 handling schemes added.
888 .. versionchanged:: 2.7
889 Support for keyword arguments added.
891 .. method:: str.endswith(suffix[, start[, end]])
893 Return ``True`` if the string ends with the specified *suffix*, otherwise return
894 ``False``. *suffix* can also be a tuple of suffixes to look for. With optional
895 *start*, test beginning at that position. With optional *end*, stop comparing
898 .. versionchanged:: 2.5
899 Accept tuples as *suffix*.
902 .. method:: str.expandtabs([tabsize])
904 Return a copy of the string where all tab characters are replaced by one or
905 more spaces, depending on the current column and the given tab size. The
906 column number is reset to zero after each newline occurring in the string.
907 If *tabsize* is not given, a tab size of ``8`` characters is assumed. This
908 doesn't understand other non-printing characters or escape sequences.
911 .. method:: str.find(sub[, start[, end]])
913 Return the lowest index in the string where substring *sub* is found, such that
914 *sub* is contained in the range [*start*, *end*]. Optional arguments *start*
915 and *end* are interpreted as in slice notation. Return ``-1`` if *sub* is not
919 .. method:: str.format(*args, **kwargs)
921 Perform a string formatting operation. The *format_string* argument can
922 contain literal text or replacement fields delimited by braces ``{}``. Each
923 replacement field contains either the numeric index of a positional argument,
924 or the name of a keyword argument. Returns a copy of *format_string* where
925 each replacement field is replaced with the string value of the corresponding
928 >>> "The sum of 1 + 2 is {0}".format(1+2)
929 'The sum of 1 + 2 is 3'
931 See :ref:`formatstrings` for a description of the various formatting options
932 that can be specified in format strings.
934 This method of string formatting is the new standard in Python 3.0, and
935 should be preferred to the ``%`` formatting described in
936 :ref:`string-formatting` in new code.
938 .. versionadded:: 2.6
941 .. method:: str.index(sub[, start[, end]])
943 Like :meth:`find`, but raise :exc:`ValueError` when the substring is not found.
946 .. method:: str.isalnum()
948 Return true if all characters in the string are alphanumeric and there is at
949 least one character, false otherwise.
951 For 8-bit strings, this method is locale-dependent.
954 .. method:: str.isalpha()
956 Return true if all characters in the string are alphabetic and there is at least
957 one character, false otherwise.
959 For 8-bit strings, this method is locale-dependent.
962 .. method:: str.isdigit()
964 Return true if all characters in the string are digits and there is at least one
965 character, false otherwise.
967 For 8-bit strings, this method is locale-dependent.
970 .. method:: str.islower()
972 Return true if all cased characters in the string are lowercase and there is at
973 least one cased character, false otherwise.
975 For 8-bit strings, this method is locale-dependent.
978 .. method:: str.isspace()
980 Return true if there are only whitespace characters in the string and there is
981 at least one character, false otherwise.
983 For 8-bit strings, this method is locale-dependent.
986 .. method:: str.istitle()
988 Return true if the string is a titlecased string and there is at least one
989 character, for example uppercase characters may only follow uncased characters
990 and lowercase characters only cased ones. Return false otherwise.
992 For 8-bit strings, this method is locale-dependent.
995 .. method:: str.isupper()
997 Return true if all cased characters in the string are uppercase and there is at
998 least one cased character, false otherwise.
1000 For 8-bit strings, this method is locale-dependent.
1003 .. method:: str.join(iterable)
1005 Return a string which is the concatenation of the strings in the
1006 :term:`iterable` *iterable*. The separator between elements is the string
1007 providing this method.
1010 .. method:: str.ljust(width[, fillchar])
1012 Return the string left justified in a string of length *width*. Padding is done
1013 using the specified *fillchar* (default is a space). The original string is
1014 returned if *width* is less than ``len(s)``.
1016 .. versionchanged:: 2.4
1017 Support for the *fillchar* argument.
1020 .. method:: str.lower()
1022 Return a copy of the string converted to lowercase.
1024 For 8-bit strings, this method is locale-dependent.
1027 .. method:: str.lstrip([chars])
1029 Return a copy of the string with leading characters removed. The *chars*
1030 argument is a string specifying the set of characters to be removed. If omitted
1031 or ``None``, the *chars* argument defaults to removing whitespace. The *chars*
1032 argument is not a prefix; rather, all combinations of its values are stripped:
1034 >>> ' spacious '.lstrip()
1036 >>> 'www.example.com'.lstrip('cmowz.')
1039 .. versionchanged:: 2.2.2
1040 Support for the *chars* argument.
1043 .. method:: str.partition(sep)
1045 Split the string at the first occurrence of *sep*, and return a 3-tuple
1046 containing the part before the separator, the separator itself, and the part
1047 after the separator. If the separator is not found, return a 3-tuple containing
1048 the string itself, followed by two empty strings.
1050 .. versionadded:: 2.5
1053 .. method:: str.replace(old, new[, count])
1055 Return a copy of the string with all occurrences of substring *old* replaced by
1056 *new*. If the optional argument *count* is given, only the first *count*
1057 occurrences are replaced.
1060 .. method:: str.rfind(sub [,start [,end]])
1062 Return the highest index in the string where substring *sub* is found, such that
1063 *sub* is contained within s[start,end]. Optional arguments *start* and *end*
1064 are interpreted as in slice notation. Return ``-1`` on failure.
1067 .. method:: str.rindex(sub[, start[, end]])
1069 Like :meth:`rfind` but raises :exc:`ValueError` when the substring *sub* is not
1073 .. method:: str.rjust(width[, fillchar])
1075 Return the string right justified in a string of length *width*. Padding is done
1076 using the specified *fillchar* (default is a space). The original string is
1077 returned if *width* is less than ``len(s)``.
1079 .. versionchanged:: 2.4
1080 Support for the *fillchar* argument.
1083 .. method:: str.rpartition(sep)
1085 Split the string at the last occurrence of *sep*, and return a 3-tuple
1086 containing the part before the separator, the separator itself, and the part
1087 after the separator. If the separator is not found, return a 3-tuple containing
1088 two empty strings, followed by the string itself.
1090 .. versionadded:: 2.5
1093 .. method:: str.rsplit([sep [,maxsplit]])
1095 Return a list of the words in the string, using *sep* as the delimiter string.
1096 If *maxsplit* is given, at most *maxsplit* splits are done, the *rightmost*
1097 ones. If *sep* is not specified or ``None``, any whitespace string is a
1098 separator. Except for splitting from the right, :meth:`rsplit` behaves like
1099 :meth:`split` which is described in detail below.
1101 .. versionadded:: 2.4
1104 .. method:: str.rstrip([chars])
1106 Return a copy of the string with trailing characters removed. The *chars*
1107 argument is a string specifying the set of characters to be removed. If omitted
1108 or ``None``, the *chars* argument defaults to removing whitespace. The *chars*
1109 argument is not a suffix; rather, all combinations of its values are stripped:
1111 >>> ' spacious '.rstrip()
1113 >>> 'mississippi'.rstrip('ipz')
1116 .. versionchanged:: 2.2.2
1117 Support for the *chars* argument.
1120 .. method:: str.split([sep[, maxsplit]])
1122 Return a list of the words in the string, using *sep* as the delimiter
1123 string. If *maxsplit* is given, at most *maxsplit* splits are done (thus,
1124 the list will have at most ``maxsplit+1`` elements). If *maxsplit* is not
1125 specified, then there is no limit on the number of splits (all possible
1128 If *sep* is given, consecutive delimiters are not grouped together and are
1129 deemed to delimit empty strings (for example, ``'1,,2'.split(',')`` returns
1130 ``['1', '', '2']``). The *sep* argument may consist of multiple characters
1131 (for example, ``'1<>2<>3'.split('<>')`` returns ``['1', '2', '3']``).
1132 Splitting an empty string with a specified separator returns ``['']``.
1134 If *sep* is not specified or is ``None``, a different splitting algorithm is
1135 applied: runs of consecutive whitespace are regarded as a single separator,
1136 and the result will contain no empty strings at the start or end if the
1137 string has leading or trailing whitespace. Consequently, splitting an empty
1138 string or a string consisting of just whitespace with a ``None`` separator
1141 For example, ``' 1 2 3 '.split()`` returns ``['1', '2', '3']``, and
1142 ``' 1 2 3 '.split(None, 1)`` returns ``['1', '2 3 ']``.
1145 .. method:: str.splitlines([keepends])
1147 Return a list of the lines in the string, breaking at line boundaries. Line
1148 breaks are not included in the resulting list unless *keepends* is given and
1152 .. method:: str.startswith(prefix[, start[, end]])
1154 Return ``True`` if string starts with the *prefix*, otherwise return ``False``.
1155 *prefix* can also be a tuple of prefixes to look for. With optional *start*,
1156 test string beginning at that position. With optional *end*, stop comparing
1157 string at that position.
1159 .. versionchanged:: 2.5
1160 Accept tuples as *prefix*.
1163 .. method:: str.strip([chars])
1165 Return a copy of the string with the leading and trailing characters removed.
1166 The *chars* argument is a string specifying the set of characters to be removed.
1167 If omitted or ``None``, the *chars* argument defaults to removing whitespace.
1168 The *chars* argument is not a prefix or suffix; rather, all combinations of its
1169 values are stripped:
1171 >>> ' spacious '.strip()
1173 >>> 'www.example.com'.strip('cmowz.')
1176 .. versionchanged:: 2.2.2
1177 Support for the *chars* argument.
1180 .. method:: str.swapcase()
1182 Return a copy of the string with uppercase characters converted to lowercase and
1185 For 8-bit strings, this method is locale-dependent.
1188 .. method:: str.title()
1190 Return a titlecased version of the string where words start with an uppercase
1191 character and the remaining characters are lowercase.
1193 The algorithm uses a simple language-independent definition of a word as
1194 groups of consecutive letters. The definition works in many contexts but
1195 it means that apostrophes in contractions and possessives form word
1196 boundaries, which may not be the desired result::
1198 >>> "they're bill's friends from the UK".title()
1199 "They'Re Bill'S Friends From The Uk"
1201 A workaround for apostrophes can be constructed using regular expressions::
1204 >>> def titlecase(s):
1205 return re.sub(r"[A-Za-z]+('[A-Za-z]+)?",
1206 lambda mo: mo.group(0)[0].upper() +
1207 mo.group(0)[1:].lower(),
1210 >>> titlecase("they're bill's friends.")
1211 "They're Bill's Friends."
1213 For 8-bit strings, this method is locale-dependent.
1216 .. method:: str.translate(table[, deletechars])
1218 Return a copy of the string where all characters occurring in the optional
1219 argument *deletechars* are removed, and the remaining characters have been
1220 mapped through the given translation table, which must be a string of length
1223 You can use the :func:`maketrans` helper function in the :mod:`string` module to
1224 create a translation table. For string objects, set the *table* argument to
1225 ``None`` for translations that only delete characters:
1227 >>> 'read this short text'.translate(None, 'aeiou')
1230 .. versionadded:: 2.6
1231 Support for a ``None`` *table* argument.
1233 For Unicode objects, the :meth:`translate` method does not accept the optional
1234 *deletechars* argument. Instead, it returns a copy of the *s* where all
1235 characters have been mapped through the given translation table which must be a
1236 mapping of Unicode ordinals to Unicode ordinals, Unicode strings or ``None``.
1237 Unmapped characters are left untouched. Characters mapped to ``None`` are
1238 deleted. Note, a more flexible approach is to create a custom character mapping
1239 codec using the :mod:`codecs` module (see :mod:`encodings.cp1251` for an
1243 .. method:: str.upper()
1245 Return a copy of the string converted to uppercase.
1247 For 8-bit strings, this method is locale-dependent.
1250 .. method:: str.zfill(width)
1252 Return the numeric string left filled with zeros in a string of length
1253 *width*. A sign prefix is handled correctly. The original string is
1254 returned if *width* is less than ``len(s)``.
1257 .. versionadded:: 2.2.2
1259 The following methods are present only on unicode objects:
1261 .. method:: unicode.isnumeric()
1263 Return ``True`` if there are only numeric characters in S, ``False``
1264 otherwise. Numeric characters include digit characters, and all characters
1265 that have the Unicode numeric value property, e.g. U+2155,
1266 VULGAR FRACTION ONE FIFTH.
1268 .. method:: unicode.isdecimal()
1270 Return ``True`` if there are only decimal characters in S, ``False``
1271 otherwise. Decimal characters include digit characters, and all characters
1272 that that can be used to form decimal-radix numbers, e.g. U+0660,
1273 ARABIC-INDIC DIGIT ZERO.
1276 .. _string-formatting:
1278 String Formatting Operations
1279 ----------------------------
1282 single: formatting, string (%)
1283 single: interpolation, string (%)
1284 single: string; formatting
1285 single: string; interpolation
1286 single: printf-style formatting
1287 single: sprintf-style formatting
1288 single: % formatting
1289 single: % interpolation
1291 String and Unicode objects have one unique built-in operation: the ``%``
1292 operator (modulo). This is also known as the string *formatting* or
1293 *interpolation* operator. Given ``format % values`` (where *format* is a string
1294 or Unicode object), ``%`` conversion specifications in *format* are replaced
1295 with zero or more elements of *values*. The effect is similar to the using
1296 :cfunc:`sprintf` in the C language. If *format* is a Unicode object, or if any
1297 of the objects being converted using the ``%s`` conversion are Unicode objects,
1298 the result will also be a Unicode object.
1300 If *format* requires a single argument, *values* may be a single non-tuple
1301 object. [#]_ Otherwise, *values* must be a tuple with exactly the number of
1302 items specified by the format string, or a single mapping object (for example, a
1305 A conversion specifier contains two or more characters and has the following
1306 components, which must occur in this order:
1308 #. The ``'%'`` character, which marks the start of the specifier.
1310 #. Mapping key (optional), consisting of a parenthesised sequence of characters
1311 (for example, ``(somename)``).
1313 #. Conversion flags (optional), which affect the result of some conversion
1316 #. Minimum field width (optional). If specified as an ``'*'`` (asterisk), the
1317 actual width is read from the next element of the tuple in *values*, and the
1318 object to convert comes after the minimum field width and optional precision.
1320 #. Precision (optional), given as a ``'.'`` (dot) followed by the precision. If
1321 specified as ``'*'`` (an asterisk), the actual width is read from the next
1322 element of the tuple in *values*, and the value to convert comes after the
1325 #. Length modifier (optional).
1329 When the right argument is a dictionary (or other mapping type), then the
1330 formats in the string *must* include a parenthesised mapping key into that
1331 dictionary inserted immediately after the ``'%'`` character. The mapping key
1332 selects the value to be formatted from the mapping. For example:
1334 >>> print '%(language)s has %(#)03d quote types.' % \
1335 ... {'language': "Python", "#": 2}
1336 Python has 002 quote types.
1338 In this case no ``*`` specifiers may occur in a format (since they require a
1339 sequential parameter list).
1341 The conversion flag characters are:
1343 +---------+---------------------------------------------------------------------+
1345 +=========+=====================================================================+
1346 | ``'#'`` | The value conversion will use the "alternate form" (where defined |
1348 +---------+---------------------------------------------------------------------+
1349 | ``'0'`` | The conversion will be zero padded for numeric values. |
1350 +---------+---------------------------------------------------------------------+
1351 | ``'-'`` | The converted value is left adjusted (overrides the ``'0'`` |
1352 | | conversion if both are given). |
1353 +---------+---------------------------------------------------------------------+
1354 | ``' '`` | (a space) A blank should be left before a positive number (or empty |
1355 | | string) produced by a signed conversion. |
1356 +---------+---------------------------------------------------------------------+
1357 | ``'+'`` | A sign character (``'+'`` or ``'-'``) will precede the conversion |
1358 | | (overrides a "space" flag). |
1359 +---------+---------------------------------------------------------------------+
1361 A length modifier (``h``, ``l``, or ``L``) may be present, but is ignored as it
1362 is not necessary for Python -- so e.g. ``%ld`` is identical to ``%d``.
1364 The conversion types are:
1366 +------------+-----------------------------------------------------+-------+
1367 | Conversion | Meaning | Notes |
1368 +============+=====================================================+=======+
1369 | ``'d'`` | Signed integer decimal. | |
1370 +------------+-----------------------------------------------------+-------+
1371 | ``'i'`` | Signed integer decimal. | |
1372 +------------+-----------------------------------------------------+-------+
1373 | ``'o'`` | Signed octal value. | \(1) |
1374 +------------+-----------------------------------------------------+-------+
1375 | ``'u'`` | Obsolete type -- it is identical to ``'d'``. | \(7) |
1376 +------------+-----------------------------------------------------+-------+
1377 | ``'x'`` | Signed hexadecimal (lowercase). | \(2) |
1378 +------------+-----------------------------------------------------+-------+
1379 | ``'X'`` | Signed hexadecimal (uppercase). | \(2) |
1380 +------------+-----------------------------------------------------+-------+
1381 | ``'e'`` | Floating point exponential format (lowercase). | \(3) |
1382 +------------+-----------------------------------------------------+-------+
1383 | ``'E'`` | Floating point exponential format (uppercase). | \(3) |
1384 +------------+-----------------------------------------------------+-------+
1385 | ``'f'`` | Floating point decimal format. | \(3) |
1386 +------------+-----------------------------------------------------+-------+
1387 | ``'F'`` | Floating point decimal format. | \(3) |
1388 +------------+-----------------------------------------------------+-------+
1389 | ``'g'`` | Floating point format. Uses lowercase exponential | \(4) |
1390 | | format if exponent is less than -4 or not less than | |
1391 | | precision, decimal format otherwise. | |
1392 +------------+-----------------------------------------------------+-------+
1393 | ``'G'`` | Floating point format. Uses uppercase exponential | \(4) |
1394 | | format if exponent is less than -4 or not less than | |
1395 | | precision, decimal format otherwise. | |
1396 +------------+-----------------------------------------------------+-------+
1397 | ``'c'`` | Single character (accepts integer or single | |
1398 | | character string). | |
1399 +------------+-----------------------------------------------------+-------+
1400 | ``'r'`` | String (converts any Python object using | \(5) |
1401 | | :func:`repr`). | |
1402 +------------+-----------------------------------------------------+-------+
1403 | ``'s'`` | String (converts any Python object using | \(6) |
1404 | | :func:`str`). | |
1405 +------------+-----------------------------------------------------+-------+
1406 | ``'%'`` | No argument is converted, results in a ``'%'`` | |
1407 | | character in the result. | |
1408 +------------+-----------------------------------------------------+-------+
1413 The alternate form causes a leading zero (``'0'``) to be inserted between
1414 left-hand padding and the formatting of the number if the leading character
1415 of the result is not already a zero.
1418 The alternate form causes a leading ``'0x'`` or ``'0X'`` (depending on whether
1419 the ``'x'`` or ``'X'`` format was used) to be inserted between left-hand padding
1420 and the formatting of the number if the leading character of the result is not
1424 The alternate form causes the result to always contain a decimal point, even if
1425 no digits follow it.
1427 The precision determines the number of digits after the decimal point and
1431 The alternate form causes the result to always contain a decimal point, and
1432 trailing zeroes are not removed as they would otherwise be.
1434 The precision determines the number of significant digits before and after the
1435 decimal point and defaults to 6.
1438 The ``%r`` conversion was added in Python 2.0.
1440 The precision determines the maximal number of characters used.
1443 If the object or format provided is a :class:`unicode` string, the resulting
1444 string will also be :class:`unicode`.
1446 The precision determines the maximal number of characters used.
1451 Since Python strings have an explicit length, ``%s`` conversions do not assume
1452 that ``'\0'`` is the end of the string.
1456 .. versionchanged:: 2.7
1457 ``%f`` conversions for numbers whose absolute value is over 1e50 are no
1458 longer replaced by ``%g`` conversions.
1464 Additional string operations are defined in standard modules :mod:`string` and
1468 .. _typesseq-xrange:
1473 .. index:: object: xrange
1475 The :class:`xrange` type is an immutable sequence which is commonly used for
1476 looping. The advantage of the :class:`xrange` type is that an :class:`xrange`
1477 object will always take the same amount of memory, no matter the size of the
1478 range it represents. There are no consistent performance advantages.
1480 XRange objects have very little behavior: they only support indexing, iteration,
1481 and the :func:`len` function.
1484 .. _typesseq-mutable:
1486 Mutable Sequence Types
1487 ----------------------
1490 triple: mutable; sequence; types
1493 List objects support additional operations that allow in-place modification of
1494 the object. Other mutable sequence types (when added to the language) should
1495 also support these operations. Strings and tuples are immutable sequence types:
1496 such objects cannot be modified once created. The following operations are
1497 defined on mutable sequence types (where *x* is an arbitrary object):
1499 +------------------------------+--------------------------------+---------------------+
1500 | Operation | Result | Notes |
1501 +==============================+================================+=====================+
1502 | ``s[i] = x`` | item *i* of *s* is replaced by | |
1504 +------------------------------+--------------------------------+---------------------+
1505 | ``s[i:j] = t`` | slice of *s* from *i* to *j* | |
1506 | | is replaced by the contents of | |
1507 | | the iterable *t* | |
1508 +------------------------------+--------------------------------+---------------------+
1509 | ``del s[i:j]`` | same as ``s[i:j] = []`` | |
1510 +------------------------------+--------------------------------+---------------------+
1511 | ``s[i:j:k] = t`` | the elements of ``s[i:j:k]`` | \(1) |
1512 | | are replaced by those of *t* | |
1513 +------------------------------+--------------------------------+---------------------+
1514 | ``del s[i:j:k]`` | removes the elements of | |
1515 | | ``s[i:j:k]`` from the list | |
1516 +------------------------------+--------------------------------+---------------------+
1517 | ``s.append(x)`` | same as ``s[len(s):len(s)] = | \(2) |
1519 +------------------------------+--------------------------------+---------------------+
1520 | ``s.extend(x)`` | same as ``s[len(s):len(s)] = | \(3) |
1522 +------------------------------+--------------------------------+---------------------+
1523 | ``s.count(x)`` | return number of *i*'s for | |
1524 | | which ``s[i] == x`` | |
1525 +------------------------------+--------------------------------+---------------------+
1526 | ``s.index(x[, i[, j]])`` | return smallest *k* such that | \(4) |
1527 | | ``s[k] == x`` and ``i <= k < | |
1529 +------------------------------+--------------------------------+---------------------+
1530 | ``s.insert(i, x)`` | same as ``s[i:i] = [x]`` | \(5) |
1531 +------------------------------+--------------------------------+---------------------+
1532 | ``s.pop([i])`` | same as ``x = s[i]; del s[i]; | \(6) |
1534 +------------------------------+--------------------------------+---------------------+
1535 | ``s.remove(x)`` | same as ``del s[s.index(x)]`` | \(4) |
1536 +------------------------------+--------------------------------+---------------------+
1537 | ``s.reverse()`` | reverses the items of *s* in | \(7) |
1539 +------------------------------+--------------------------------+---------------------+
1540 | ``s.sort([cmp[, key[, | sort the items of *s* in place | (7)(8)(9)(10) |
1541 | reverse]]])`` | | |
1542 +------------------------------+--------------------------------+---------------------+
1545 triple: operations on; sequence; types
1546 triple: operations on; list; type
1547 pair: subscript; assignment
1548 pair: slice; assignment
1549 pair: extended slice; assignment
1551 single: append() (list method)
1552 single: extend() (list method)
1553 single: count() (list method)
1554 single: index() (list method)
1555 single: insert() (list method)
1556 single: pop() (list method)
1557 single: remove() (list method)
1558 single: reverse() (list method)
1559 single: sort() (list method)
1564 *t* must have the same length as the slice it is replacing.
1567 The C implementation of Python has historically accepted multiple parameters and
1568 implicitly joined them into a tuple; this no longer works in Python 2.0. Use of
1569 this misfeature has been deprecated since Python 1.4.
1572 *x* can be any iterable object.
1575 Raises :exc:`ValueError` when *x* is not found in *s*. When a negative index is
1576 passed as the second or third parameter to the :meth:`index` method, the list
1577 length is added, as for slice indices. If it is still negative, it is truncated
1578 to zero, as for slice indices.
1580 .. versionchanged:: 2.3
1581 Previously, :meth:`index` didn't have arguments for specifying start and stop
1585 When a negative index is passed as the first parameter to the :meth:`insert`
1586 method, the list length is added, as for slice indices. If it is still
1587 negative, it is truncated to zero, as for slice indices.
1589 .. versionchanged:: 2.3
1590 Previously, all negative indices were truncated to zero.
1593 The :meth:`pop` method is only supported by the list and array types. The
1594 optional argument *i* defaults to ``-1``, so that by default the last item is
1595 removed and returned.
1598 The :meth:`sort` and :meth:`reverse` methods modify the list in place for
1599 economy of space when sorting or reversing a large list. To remind you that
1600 they operate by side effect, they don't return the sorted or reversed list.
1603 The :meth:`sort` method takes optional arguments for controlling the
1606 *cmp* specifies a custom comparison function of two arguments (list items) which
1607 should return a negative, zero or positive number depending on whether the first
1608 argument is considered smaller than, equal to, or larger than the second
1609 argument: ``cmp=lambda x,y: cmp(x.lower(), y.lower())``. The default value
1612 *key* specifies a function of one argument that is used to extract a comparison
1613 key from each list element: ``key=str.lower``. The default value is ``None``.
1615 *reverse* is a boolean value. If set to ``True``, then the list elements are
1616 sorted as if each comparison were reversed.
1618 In general, the *key* and *reverse* conversion processes are much faster than
1619 specifying an equivalent *cmp* function. This is because *cmp* is called
1620 multiple times for each list element while *key* and *reverse* touch each
1623 .. versionchanged:: 2.3
1624 Support for ``None`` as an equivalent to omitting *cmp* was added.
1626 .. versionchanged:: 2.4
1627 Support for *key* and *reverse* was added.
1630 Starting with Python 2.3, the :meth:`sort` method is guaranteed to be stable. A
1631 sort is stable if it guarantees not to change the relative order of elements
1632 that compare equal --- this is helpful for sorting in multiple passes (for
1633 example, sort by department, then by salary grade).
1638 While a list is being sorted, the effect of attempting to mutate, or even
1639 inspect, the list is undefined. The C implementation of Python 2.3 and
1640 newer makes the list appear empty for the duration, and raises
1641 :exc:`ValueError` if it can detect that the list has been mutated during a
1647 Set Types --- :class:`set`, :class:`frozenset`
1648 ==============================================
1650 .. index:: object: set
1652 A :dfn:`set` object is an unordered collection of distinct :term:`hashable` objects.
1653 Common uses include membership testing, removing duplicates from a sequence, and
1654 computing mathematical operations such as intersection, union, difference, and
1655 symmetric difference.
1656 (For other containers see the built in :class:`dict`, :class:`list`,
1657 and :class:`tuple` classes, and the :mod:`collections` module.)
1660 .. versionadded:: 2.4
1662 Like other collections, sets support ``x in set``, ``len(set)``, and ``for x in
1663 set``. Being an unordered collection, sets do not record element position or
1664 order of insertion. Accordingly, sets do not support indexing, slicing, or
1665 other sequence-like behavior.
1667 There are currently two built-in set types, :class:`set` and :class:`frozenset`.
1668 The :class:`set` type is mutable --- the contents can be changed using methods
1669 like :meth:`add` and :meth:`remove`. Since it is mutable, it has no hash value
1670 and cannot be used as either a dictionary key or as an element of another set.
1671 The :class:`frozenset` type is immutable and :term:`hashable` --- its contents cannot be
1672 altered after it is created; it can therefore be used as a dictionary key or as
1673 an element of another set.
1675 The constructors for both classes work the same:
1677 .. class:: set([iterable])
1678 frozenset([iterable])
1680 Return a new set or frozenset object whose elements are taken from
1681 *iterable*. The elements of a set must be hashable. To represent sets of
1682 sets, the inner sets must be :class:`frozenset` objects. If *iterable* is
1683 not specified, a new empty set is returned.
1685 Instances of :class:`set` and :class:`frozenset` provide the following
1688 .. describe:: len(s)
1690 Return the cardinality of set *s*.
1692 .. describe:: x in s
1694 Test *x* for membership in *s*.
1696 .. describe:: x not in s
1698 Test *x* for non-membership in *s*.
1700 .. method:: isdisjoint(other)
1702 Return True if the set has no elements in common with *other*. Sets are
1703 disjoint if and only if their intersection is the empty set.
1705 .. versionadded:: 2.6
1707 .. method:: issubset(other)
1710 Test whether every element in the set is in *other*.
1712 .. method:: set < other
1714 Test whether the set is a true subset of *other*, that is,
1715 ``set <= other and set != other``.
1717 .. method:: issuperset(other)
1720 Test whether every element in *other* is in the set.
1722 .. method:: set > other
1724 Test whether the set is a true superset of *other*, that is, ``set >=
1725 other and set != other``.
1727 .. method:: union(other, ...)
1730 Return a new set with elements from the set and all others.
1732 .. versionchanged:: 2.6
1733 Accepts multiple input iterables.
1735 .. method:: intersection(other, ...)
1738 Return a new set with elements common to the set and all others.
1740 .. versionchanged:: 2.6
1741 Accepts multiple input iterables.
1743 .. method:: difference(other, ...)
1746 Return a new set with elements in the set that are not in the others.
1748 .. versionchanged:: 2.6
1749 Accepts multiple input iterables.
1751 .. method:: symmetric_difference(other)
1754 Return a new set with elements in either the set or *other* but not both.
1758 Return a new set with a shallow copy of *s*.
1761 Note, the non-operator versions of :meth:`union`, :meth:`intersection`,
1762 :meth:`difference`, and :meth:`symmetric_difference`, :meth:`issubset`, and
1763 :meth:`issuperset` methods will accept any iterable as an argument. In
1764 contrast, their operator based counterparts require their arguments to be
1765 sets. This precludes error-prone constructions like ``set('abc') & 'cbs'``
1766 in favor of the more readable ``set('abc').intersection('cbs')``.
1768 Both :class:`set` and :class:`frozenset` support set to set comparisons. Two
1769 sets are equal if and only if every element of each set is contained in the
1770 other (each is a subset of the other). A set is less than another set if and
1771 only if the first set is a proper subset of the second set (is a subset, but
1772 is not equal). A set is greater than another set if and only if the first set
1773 is a proper superset of the second set (is a superset, but is not equal).
1775 Instances of :class:`set` are compared to instances of :class:`frozenset`
1776 based on their members. For example, ``set('abc') == frozenset('abc')``
1777 returns ``True`` and so does ``set('abc') in set([frozenset('abc')])``.
1779 The subset and equality comparisons do not generalize to a complete ordering
1780 function. For example, any two disjoint sets are not equal and are not
1781 subsets of each other, so *all* of the following return ``False``: ``a<b``,
1782 ``a==b``, or ``a>b``. Accordingly, sets do not implement the :meth:`__cmp__`
1785 Since sets only define partial ordering (subset relationships), the output of
1786 the :meth:`list.sort` method is undefined for lists of sets.
1788 Set elements, like dictionary keys, must be :term:`hashable`.
1790 Binary operations that mix :class:`set` instances with :class:`frozenset`
1791 return the type of the first operand. For example: ``frozenset('ab') |
1792 set('bc')`` returns an instance of :class:`frozenset`.
1794 The following table lists operations available for :class:`set` that do not
1795 apply to immutable instances of :class:`frozenset`:
1797 .. method:: update(other, ...)
1800 Update the set, adding elements from all others.
1802 .. versionchanged:: 2.6
1803 Accepts multiple input iterables.
1805 .. method:: intersection_update(other, ...)
1808 Update the set, keeping only elements found in it and all others.
1810 .. versionchanged:: 2.6
1811 Accepts multiple input iterables.
1813 .. method:: difference_update(other, ...)
1816 Update the set, removing elements found in others.
1818 .. versionchanged:: 2.6
1819 Accepts multiple input iterables.
1821 .. method:: symmetric_difference_update(other)
1824 Update the set, keeping only elements found in either set, but not in both.
1826 .. method:: add(elem)
1828 Add element *elem* to the set.
1830 .. method:: remove(elem)
1832 Remove element *elem* from the set. Raises :exc:`KeyError` if *elem* is
1833 not contained in the set.
1835 .. method:: discard(elem)
1837 Remove element *elem* from the set if it is present.
1841 Remove and return an arbitrary element from the set. Raises
1842 :exc:`KeyError` if the set is empty.
1846 Remove all elements from the set.
1849 Note, the non-operator versions of the :meth:`update`,
1850 :meth:`intersection_update`, :meth:`difference_update`, and
1851 :meth:`symmetric_difference_update` methods will accept any iterable as an
1854 Note, the *elem* argument to the :meth:`__contains__`, :meth:`remove`, and
1855 :meth:`discard` methods may be a set. To support searching for an equivalent
1856 frozenset, the *elem* set is temporarily mutated during the search and then
1857 restored. During the search, the *elem* set should not be read or mutated
1858 since it does not have a meaningful value.
1863 :ref:`comparison-to-builtin-set`
1864 Differences between the :mod:`sets` module and the built-in set types.
1869 Mapping Types --- :class:`dict`
1870 ===============================
1875 triple: operations on; mapping; types
1876 triple: operations on; dictionary; type
1880 A :dfn:`mapping` object maps :term:`hashable` values to arbitrary objects.
1881 Mappings are mutable objects. There is currently only one standard mapping
1882 type, the :dfn:`dictionary`. (For other containers see the built in
1883 :class:`list`, :class:`set`, and :class:`tuple` classes, and the
1884 :mod:`collections` module.)
1886 A dictionary's keys are *almost* arbitrary values. Values that are not
1887 :term:`hashable`, that is, values containing lists, dictionaries or other
1888 mutable types (that are compared by value rather than by object identity) may
1889 not be used as keys. Numeric types used for keys obey the normal rules for
1890 numeric comparison: if two numbers compare equal (such as ``1`` and ``1.0``)
1891 then they can be used interchangeably to index the same dictionary entry. (Note
1892 however, that since computers store floating-point numbers as approximations it
1893 is usually unwise to use them as dictionary keys.)
1895 Dictionaries can be created by placing a comma-separated list of ``key: value``
1896 pairs within braces, for example: ``{'jack': 4098, 'sjoerd': 4127}`` or ``{4098:
1897 'jack', 4127: 'sjoerd'}``, or by the :class:`dict` constructor.
1899 .. class:: dict([arg])
1901 Return a new dictionary initialized from an optional positional argument or from
1902 a set of keyword arguments. If no arguments are given, return a new empty
1903 dictionary. If the positional argument *arg* is a mapping object, return a
1904 dictionary mapping the same keys to the same values as does the mapping object.
1905 Otherwise the positional argument must be a sequence, a container that supports
1906 iteration, or an iterator object. The elements of the argument must each also
1907 be of one of those kinds, and each must in turn contain exactly two objects.
1908 The first is used as a key in the new dictionary, and the second as the key's
1909 value. If a given key is seen more than once, the last value associated with it
1910 is retained in the new dictionary.
1912 If keyword arguments are given, the keywords themselves with their associated
1913 values are added as items to the dictionary. If a key is specified both in the
1914 positional argument and as a keyword argument, the value associated with the
1915 keyword is retained in the dictionary. For example, these all return a
1916 dictionary equal to ``{"one": 2, "two": 3}``:
1918 * ``dict(one=2, two=3)``
1920 * ``dict({'one': 2, 'two': 3})``
1922 * ``dict(zip(('one', 'two'), (2, 3)))``
1924 * ``dict([['two', 3], ['one', 2]])``
1926 The first example only works for keys that are valid Python
1927 identifiers; the others work with any valid keys.
1929 .. versionadded:: 2.2
1931 .. versionchanged:: 2.3
1932 Support for building a dictionary from keyword arguments added.
1935 These are the operations that dictionaries support (and therefore, custom
1936 mapping types should support too):
1938 .. describe:: len(d)
1940 Return the number of items in the dictionary *d*.
1942 .. describe:: d[key]
1944 Return the item of *d* with key *key*. Raises a :exc:`KeyError` if *key*
1947 .. versionadded:: 2.5
1948 If a subclass of dict defines a method :meth:`__missing__`, if the key
1949 *key* is not present, the ``d[key]`` operation calls that method with
1950 the key *key* as argument. The ``d[key]`` operation then returns or
1951 raises whatever is returned or raised by the ``__missing__(key)`` call
1952 if the key is not present. No other operations or methods invoke
1953 :meth:`__missing__`. If :meth:`__missing__` is not defined,
1954 :exc:`KeyError` is raised. :meth:`__missing__` must be a method; it
1955 cannot be an instance variable. For an example, see
1956 :class:`collections.defaultdict`.
1958 .. describe:: d[key] = value
1960 Set ``d[key]`` to *value*.
1962 .. describe:: del d[key]
1964 Remove ``d[key]`` from *d*. Raises a :exc:`KeyError` if *key* is not in the
1967 .. describe:: key in d
1969 Return ``True`` if *d* has a key *key*, else ``False``.
1971 .. versionadded:: 2.2
1973 .. describe:: key not in d
1975 Equivalent to ``not key in d``.
1977 .. versionadded:: 2.2
1979 .. describe:: iter(d)
1981 Return an iterator over the keys of the dictionary. This is a shortcut
1982 for :meth:`iterkeys`.
1986 Remove all items from the dictionary.
1990 Return a shallow copy of the dictionary.
1992 .. method:: fromkeys(seq[, value])
1994 Create a new dictionary with keys from *seq* and values set to *value*.
1996 :func:`fromkeys` is a class method that returns a new dictionary. *value*
1997 defaults to ``None``.
1999 .. versionadded:: 2.3
2001 .. method:: get(key[, default])
2003 Return the value for *key* if *key* is in the dictionary, else *default*.
2004 If *default* is not given, it defaults to ``None``, so that this method
2005 never raises a :exc:`KeyError`.
2007 .. method:: has_key(key)
2009 Test for the presence of *key* in the dictionary. :meth:`has_key` is
2010 deprecated in favor of ``key in d``.
2014 Return a copy of the dictionary's list of ``(key, value)`` pairs.
2018 Keys and values are listed in an arbitrary order which is non-random,
2019 varies across Python implementations, and depends on the dictionary's
2020 history of insertions and deletions.
2022 If :meth:`items`, :meth:`keys`, :meth:`values`, :meth:`iteritems`,
2023 :meth:`iterkeys`, and :meth:`itervalues` are called with no intervening
2024 modifications to the dictionary, the lists will directly correspond. This
2025 allows the creation of ``(value, key)`` pairs using :func:`zip`: ``pairs =
2026 zip(d.values(), d.keys())``. The same relationship holds for the
2027 :meth:`iterkeys` and :meth:`itervalues` methods: ``pairs =
2028 zip(d.itervalues(), d.iterkeys())`` provides the same value for
2029 ``pairs``. Another way to create the same list is ``pairs = [(v, k) for
2030 (k, v) in d.iteritems()]``.
2032 .. method:: iteritems()
2034 Return an iterator over the dictionary's ``(key, value)`` pairs. See the
2035 note for :meth:`dict.items`.
2037 Using :meth:`iteritems` while adding or deleting entries in the dictionary
2038 may raise a :exc:`RuntimeError` or fail to iterate over all entries.
2040 .. versionadded:: 2.2
2042 .. method:: iterkeys()
2044 Return an iterator over the dictionary's keys. See the note for
2047 Using :meth:`iterkeys` while adding or deleting entries in the dictionary
2048 may raise a :exc:`RuntimeError` or fail to iterate over all entries.
2050 .. versionadded:: 2.2
2052 .. method:: itervalues()
2054 Return an iterator over the dictionary's values. See the note for
2057 Using :meth:`itervalues` while adding or deleting entries in the
2058 dictionary may raise a :exc:`RuntimeError` or fail to iterate over all
2061 .. versionadded:: 2.2
2065 Return a copy of the dictionary's list of keys. See the note for
2068 .. method:: pop(key[, default])
2070 If *key* is in the dictionary, remove it and return its value, else return
2071 *default*. If *default* is not given and *key* is not in the dictionary,
2072 a :exc:`KeyError` is raised.
2074 .. versionadded:: 2.3
2076 .. method:: popitem()
2078 Remove and return an arbitrary ``(key, value)`` pair from the dictionary.
2080 :func:`popitem` is useful to destructively iterate over a dictionary, as
2081 often used in set algorithms. If the dictionary is empty, calling
2082 :func:`popitem` raises a :exc:`KeyError`.
2084 .. method:: setdefault(key[, default])
2086 If *key* is in the dictionary, return its value. If not, insert *key*
2087 with a value of *default* and return *default*. *default* defaults to
2090 .. method:: update([other])
2092 Update the dictionary with the key/value pairs from *other*, overwriting
2093 existing keys. Return ``None``.
2095 :func:`update` accepts either another dictionary object or an iterable of
2096 key/value pairs (as a tuple or other iterable of length two). If keyword
2097 arguments are specified, the dictionary is then updated with those
2098 key/value pairs: ``d.update(red=1, blue=2)``.
2100 .. versionchanged:: 2.4
2101 Allowed the argument to be an iterable of key/value pairs and allowed
2104 .. method:: values()
2106 Return a copy of the dictionary's list of values. See the note for
2110 .. _bltin-file-objects:
2121 File objects are implemented using C's ``stdio`` package and can be
2122 created with the built-in :func:`open` function. File
2123 objects are also returned by some other built-in functions and methods,
2124 such as :func:`os.popen` and :func:`os.fdopen` and the :meth:`makefile`
2125 method of socket objects. Temporary files can be created using the
2126 :mod:`tempfile` module, and high-level file operations such as copying,
2127 moving, and deleting files and directories can be achieved with the
2128 :mod:`shutil` module.
2130 When a file operation fails for an I/O-related reason, the exception
2131 :exc:`IOError` is raised. This includes situations where the operation is not
2132 defined for some reason, like :meth:`seek` on a tty device or writing a file
2135 Files have the following methods:
2138 .. method:: file.close()
2140 Close the file. A closed file cannot be read or written any more. Any operation
2141 which requires that the file be open will raise a :exc:`ValueError` after the
2142 file has been closed. Calling :meth:`close` more than once is allowed.
2144 As of Python 2.5, you can avoid having to call this method explicitly if you use
2145 the :keyword:`with` statement. For example, the following code will
2146 automatically close *f* when the :keyword:`with` block is exited::
2148 from __future__ import with_statement # This isn't required in Python 2.6
2150 with open("hello.txt") as f:
2154 In older versions of Python, you would have needed to do this to get the same
2157 f = open("hello.txt")
2166 Not all "file-like" types in Python support use as a context manager for the
2167 :keyword:`with` statement. If your code is intended to work with any file-like
2168 object, you can use the function :func:`contextlib.closing` instead of using
2169 the object directly.
2172 .. method:: file.flush()
2174 Flush the internal buffer, like ``stdio``'s :cfunc:`fflush`. This may be a
2175 no-op on some file-like objects.
2179 :meth:`flush` does not necessarily write the file's data to disk. Use
2180 :meth:`flush` followed by :func:`os.fsync` to ensure this behavior.
2183 .. method:: file.fileno()
2186 pair: file; descriptor
2189 Return the integer "file descriptor" that is used by the underlying
2190 implementation to request I/O operations from the operating system. This can be
2191 useful for other, lower level interfaces that use file descriptors, such as the
2192 :mod:`fcntl` module or :func:`os.read` and friends.
2196 File-like objects which do not have a real file descriptor should *not* provide
2200 .. method:: file.isatty()
2202 Return ``True`` if the file is connected to a tty(-like) device, else ``False``.
2206 If a file-like object is not associated with a real file, this method should
2207 *not* be implemented.
2210 .. method:: file.next()
2212 A file object is its own iterator, for example ``iter(f)`` returns *f* (unless
2213 *f* is closed). When a file is used as an iterator, typically in a
2214 :keyword:`for` loop (for example, ``for line in f: print line``), the
2215 :meth:`.next` method is called repeatedly. This method returns the next input
2216 line, or raises :exc:`StopIteration` when EOF is hit when the file is open for
2217 reading (behavior is undefined when the file is open for writing). In order to
2218 make a :keyword:`for` loop the most efficient way of looping over the lines of a
2219 file (a very common operation), the :meth:`next` method uses a hidden read-ahead
2220 buffer. As a consequence of using a read-ahead buffer, combining :meth:`.next`
2221 with other file methods (like :meth:`readline`) does not work right. However,
2222 using :meth:`seek` to reposition the file to an absolute position will flush the
2225 .. versionadded:: 2.3
2228 .. method:: file.read([size])
2230 Read at most *size* bytes from the file (less if the read hits EOF before
2231 obtaining *size* bytes). If the *size* argument is negative or omitted, read
2232 all data until EOF is reached. The bytes are returned as a string object. An
2233 empty string is returned when EOF is encountered immediately. (For certain
2234 files, like ttys, it makes sense to continue reading after an EOF is hit.) Note
2235 that this method may call the underlying C function :cfunc:`fread` more than
2236 once in an effort to acquire as close to *size* bytes as possible. Also note
2237 that when in non-blocking mode, less data than was requested may be
2238 returned, even if no *size* parameter was given.
2241 This function is simply a wrapper for the underlying
2242 :cfunc:`fread` C function, and will behave the same in corner cases,
2243 such as whether the EOF value is cached.
2246 .. method:: file.readline([size])
2248 Read one entire line from the file. A trailing newline character is kept in the
2249 string (but may be absent when a file ends with an incomplete line). [#]_ If
2250 the *size* argument is present and non-negative, it is a maximum byte count
2251 (including the trailing newline) and an incomplete line may be returned. An
2252 empty string is returned *only* when EOF is encountered immediately.
2256 Unlike ``stdio``'s :cfunc:`fgets`, the returned string contains null characters
2257 (``'\0'``) if they occurred in the input.
2260 .. method:: file.readlines([sizehint])
2262 Read until EOF using :meth:`readline` and return a list containing the lines
2263 thus read. If the optional *sizehint* argument is present, instead of
2264 reading up to EOF, whole lines totalling approximately *sizehint* bytes
2265 (possibly after rounding up to an internal buffer size) are read. Objects
2266 implementing a file-like interface may choose to ignore *sizehint* if it
2267 cannot be implemented, or cannot be implemented efficiently.
2270 .. method:: file.xreadlines()
2272 This method returns the same thing as ``iter(f)``.
2274 .. versionadded:: 2.1
2277 Use ``for line in file`` instead.
2280 .. method:: file.seek(offset[, whence])
2282 Set the file's current position, like ``stdio``'s :cfunc:`fseek`. The *whence*
2283 argument is optional and defaults to ``os.SEEK_SET`` or ``0`` (absolute file
2284 positioning); other values are ``os.SEEK_CUR`` or ``1`` (seek relative to the
2285 current position) and ``os.SEEK_END`` or ``2`` (seek relative to the file's
2286 end). There is no return value.
2288 For example, ``f.seek(2, os.SEEK_CUR)`` advances the position by two and
2289 ``f.seek(-3, os.SEEK_END)`` sets the position to the third to last.
2291 Note that if the file is opened for appending
2292 (mode ``'a'`` or ``'a+'``), any :meth:`seek` operations will be undone at the
2293 next write. If the file is only opened for writing in append mode (mode
2294 ``'a'``), this method is essentially a no-op, but it remains useful for files
2295 opened in append mode with reading enabled (mode ``'a+'``). If the file is
2296 opened in text mode (without ``'b'``), only offsets returned by :meth:`tell` are
2297 legal. Use of other offsets causes undefined behavior.
2299 Note that not all file objects are seekable.
2301 .. versionchanged:: 2.6
2302 Passing float values as offset has been deprecated.
2305 .. method:: file.tell()
2307 Return the file's current position, like ``stdio``'s :cfunc:`ftell`.
2311 On Windows, :meth:`tell` can return illegal values (after an :cfunc:`fgets`)
2312 when reading files with Unix-style line-endings. Use binary mode (``'rb'``) to
2313 circumvent this problem.
2316 .. method:: file.truncate([size])
2318 Truncate the file's size. If the optional *size* argument is present, the file
2319 is truncated to (at most) that size. The size defaults to the current position.
2320 The current file position is not changed. Note that if a specified size exceeds
2321 the file's current size, the result is platform-dependent: possibilities
2322 include that the file may remain unchanged, increase to the specified size as if
2323 zero-filled, or increase to the specified size with undefined new content.
2324 Availability: Windows, many Unix variants.
2327 .. method:: file.write(str)
2329 Write a string to the file. There is no return value. Due to buffering, the
2330 string may not actually show up in the file until the :meth:`flush` or
2331 :meth:`close` method is called.
2334 .. method:: file.writelines(sequence)
2336 Write a sequence of strings to the file. The sequence can be any iterable
2337 object producing strings, typically a list of strings. There is no return value.
2338 (The name is intended to match :meth:`readlines`; :meth:`writelines` does not
2339 add line separators.)
2341 Files support the iterator protocol. Each iteration returns the same result as
2342 ``file.readline()``, and iteration ends when the :meth:`readline` method returns
2345 File objects also offer a number of other interesting attributes. These are not
2346 required for file-like objects, but should be implemented if they make sense for
2347 the particular object.
2350 .. attribute:: file.closed
2352 bool indicating the current state of the file object. This is a read-only
2353 attribute; the :meth:`close` method changes the value. It may not be available
2354 on all file-like objects.
2357 .. attribute:: file.encoding
2359 The encoding that this file uses. When Unicode strings are written to a file,
2360 they will be converted to byte strings using this encoding. In addition, when
2361 the file is connected to a terminal, the attribute gives the encoding that the
2362 terminal is likely to use (that information might be incorrect if the user has
2363 misconfigured the terminal). The attribute is read-only and may not be present
2364 on all file-like objects. It may also be ``None``, in which case the file uses
2365 the system default encoding for converting Unicode strings.
2367 .. versionadded:: 2.3
2370 .. attribute:: file.errors
2372 The Unicode error handler used along with the encoding.
2374 .. versionadded:: 2.6
2377 .. attribute:: file.mode
2379 The I/O mode for the file. If the file was created using the :func:`open`
2380 built-in function, this will be the value of the *mode* parameter. This is a
2381 read-only attribute and may not be present on all file-like objects.
2384 .. attribute:: file.name
2386 If the file object was created using :func:`open`, the name of the file.
2387 Otherwise, some string that indicates the source of the file object, of the
2388 form ``<...>``. This is a read-only attribute and may not be present on all
2392 .. attribute:: file.newlines
2394 If Python was built with the :option:`--with-universal-newlines` option to
2395 :program:`configure` (the default) this read-only attribute exists, and for
2396 files opened in universal newline read mode it keeps track of the types of
2397 newlines encountered while reading the file. The values it can take are
2398 ``'\r'``, ``'\n'``, ``'\r\n'``, ``None`` (unknown, no newlines read yet) or a
2399 tuple containing all the newline types seen, to indicate that multiple newline
2400 conventions were encountered. For files not opened in universal newline read
2401 mode the value of this attribute will be ``None``.
2404 .. attribute:: file.softspace
2406 Boolean that indicates whether a space character needs to be printed before
2407 another value when using the :keyword:`print` statement. Classes that are trying
2408 to simulate a file object should also have a writable :attr:`softspace`
2409 attribute, which should be initialized to zero. This will be automatic for most
2410 classes implemented in Python (care may be needed for objects that override
2411 attribute access); types implemented in C will have to provide a writable
2412 :attr:`softspace` attribute.
2416 This attribute is not used to control the :keyword:`print` statement, but to
2417 allow the implementation of :keyword:`print` to keep track of its internal
2426 :class:`memoryview`\s allow Python code to access the internal data of an object
2427 that supports the buffer protocol without copying. Memory can be interpreted as
2428 simple bytes or complex data structures.
2430 .. class:: memoryview(obj)
2432 Create a :class:`memoryview` that references *obj*. *obj* must support the
2433 buffer protocol. Builtin objects that support the buffer protocol include
2434 :class:`str` and :class:`bytearray` (but not :class:`unicode`).
2436 ``len(view)`` returns the total number of bytes in the memoryview, *view*.
2438 A :class:`memoryview` supports slicing to expose its data. Taking a single
2439 index will return a single byte. Full slicing will result in a subview::
2441 >>> v = memoryview('abcefg')
2447 <memory at 0x77ab28>
2451 <memory at 0x744f18>
2455 If the object the memory view is over supports changing its data, the
2456 memoryview supports slice assignment::
2458 >>> data = bytearray('abcefg')
2459 >>> v = memoryview(data)
2464 bytearray(b'zbcefg')
2467 bytearray(b'z123fg')
2469 Traceback (most recent call last):
2470 File "<stdin>", line 1, in <module>
2471 ValueError: cannot modify size of memoryview object
2473 Notice how the size of the memoryview object can not be changed.
2476 :class:`memoryview` has two methods:
2478 .. method:: tobytes()
2480 Return the data in the buffer as a bytestring (an object of class
2483 .. method:: tolist()
2485 Return the data in the buffer as a list of integers. ::
2487 >>> memoryview(b'abc').tolist()
2490 There are also several readonly attributes available:
2492 .. attribute:: format
2494 A string containing the format (in :mod:`struct` module style) for each
2495 element in the view. This defaults to ``'B'``, a simple bytestring.
2497 .. attribute:: itemsize
2499 The size in bytes of each element of the memoryview.
2501 .. attribute:: shape
2503 A tuple of integers the length of :attr:`ndim` giving the shape of the
2504 memory as a N-dimensional array.
2508 An integer indicating how many dimensions of a multi-dimensional array the
2511 .. attribute:: strides
2513 A tuple of integers the length of :attr:`ndim` giving the size in bytes to
2514 access each element for each dimension of the array.
2516 .. memoryview.suboffsets isn't documented because it only seems useful for C
2519 .. _typecontextmanager:
2521 Context Manager Types
2522 =====================
2524 .. versionadded:: 2.5
2527 single: context manager
2528 single: context management protocol
2529 single: protocol; context management
2531 Python's :keyword:`with` statement supports the concept of a runtime context
2532 defined by a context manager. This is implemented using two separate methods
2533 that allow user-defined classes to define a runtime context that is entered
2534 before the statement body is executed and exited when the statement ends.
2536 The :dfn:`context management protocol` consists of a pair of methods that need
2537 to be provided for a context manager object to define a runtime context:
2540 .. method:: contextmanager.__enter__()
2542 Enter the runtime context and return either this object or another object
2543 related to the runtime context. The value returned by this method is bound to
2544 the identifier in the :keyword:`as` clause of :keyword:`with` statements using
2545 this context manager.
2547 An example of a context manager that returns itself is a file object. File
2548 objects return themselves from __enter__() to allow :func:`open` to be used as
2549 the context expression in a :keyword:`with` statement.
2551 An example of a context manager that returns a related object is the one
2552 returned by :func:`decimal.localcontext`. These managers set the active
2553 decimal context to a copy of the original decimal context and then return the
2554 copy. This allows changes to be made to the current decimal context in the body
2555 of the :keyword:`with` statement without affecting code outside the
2556 :keyword:`with` statement.
2559 .. method:: contextmanager.__exit__(exc_type, exc_val, exc_tb)
2561 Exit the runtime context and return a Boolean flag indicating if any exception
2562 that occurred should be suppressed. If an exception occurred while executing the
2563 body of the :keyword:`with` statement, the arguments contain the exception type,
2564 value and traceback information. Otherwise, all three arguments are ``None``.
2566 Returning a true value from this method will cause the :keyword:`with` statement
2567 to suppress the exception and continue execution with the statement immediately
2568 following the :keyword:`with` statement. Otherwise the exception continues
2569 propagating after this method has finished executing. Exceptions that occur
2570 during execution of this method will replace any exception that occurred in the
2571 body of the :keyword:`with` statement.
2573 The exception passed in should never be reraised explicitly - instead, this
2574 method should return a false value to indicate that the method completed
2575 successfully and does not want to suppress the raised exception. This allows
2576 context management code (such as ``contextlib.nested``) to easily detect whether
2577 or not an :meth:`__exit__` method has actually failed.
2579 Python defines several context managers to support easy thread synchronisation,
2580 prompt closure of files or other objects, and simpler manipulation of the active
2581 decimal arithmetic context. The specific types are not treated specially beyond
2582 their implementation of the context management protocol. See the
2583 :mod:`contextlib` module for some examples.
2585 Python's :term:`generator`\s and the ``contextlib.contextmanager`` :term:`decorator`
2586 provide a convenient way to implement these protocols. If a generator function is
2587 decorated with the ``contextlib.contextmanager`` decorator, it will return a
2588 context manager implementing the necessary :meth:`__enter__` and
2589 :meth:`__exit__` methods, rather than the iterator produced by an undecorated
2592 Note that there is no specific slot for any of these methods in the type
2593 structure for Python objects in the Python/C API. Extension types wanting to
2594 define these methods must provide them as a normal Python accessible method.
2595 Compared to the overhead of setting up the runtime context, the overhead of a
2596 single class dictionary lookup is negligible.
2601 Other Built-in Types
2602 ====================
2604 The interpreter supports several other kinds of objects. Most of these support
2605 only one or two operations.
2613 The only special operation on a module is attribute access: ``m.name``, where
2614 *m* is a module and *name* accesses a name defined in *m*'s symbol table.
2615 Module attributes can be assigned to. (Note that the :keyword:`import`
2616 statement is not, strictly speaking, an operation on a module object; ``import
2617 foo`` does not require a module object named *foo* to exist, rather it requires
2618 an (external) *definition* for a module named *foo* somewhere.)
2620 A special member of every module is :attr:`__dict__`. This is the dictionary
2621 containing the module's symbol table. Modifying this dictionary will actually
2622 change the module's symbol table, but direct assignment to the :attr:`__dict__`
2623 attribute is not possible (you can write ``m.__dict__['a'] = 1``, which defines
2624 ``m.a`` to be ``1``, but you can't write ``m.__dict__ = {}``). Modifying
2625 :attr:`__dict__` directly is not recommended.
2627 Modules built into the interpreter are written like this: ``<module 'sys'
2628 (built-in)>``. If loaded from a file, they are written as ``<module 'os' from
2629 '/usr/local/lib/pythonX.Y/os.pyc'>``.
2634 Classes and Class Instances
2635 ---------------------------
2637 See :ref:`objects` and :ref:`class` for these.
2645 Function objects are created by function definitions. The only operation on a
2646 function object is to call it: ``func(argument-list)``.
2648 There are really two flavors of function objects: built-in functions and
2649 user-defined functions. Both support the same operation (to call the function),
2650 but the implementation is different, hence the different object types.
2652 See :ref:`function` for more information.
2660 .. index:: object: method
2662 Methods are functions that are called using the attribute notation. There are
2663 two flavors: built-in methods (such as :meth:`append` on lists) and class
2664 instance methods. Built-in methods are described with the types that support
2667 The implementation adds two special read-only attributes to class instance
2668 methods: ``m.im_self`` is the object on which the method operates, and
2669 ``m.im_func`` is the function implementing the method. Calling ``m(arg-1,
2670 arg-2, ..., arg-n)`` is completely equivalent to calling ``m.im_func(m.im_self,
2671 arg-1, arg-2, ..., arg-n)``.
2673 Class instance methods are either *bound* or *unbound*, referring to whether the
2674 method was accessed through an instance or a class, respectively. When a method
2675 is unbound, its ``im_self`` attribute will be ``None`` and if called, an
2676 explicit ``self`` object must be passed as the first argument. In this case,
2677 ``self`` must be an instance of the unbound method's class (or a subclass of
2678 that class), otherwise a :exc:`TypeError` is raised.
2680 Like function objects, methods objects support getting arbitrary attributes.
2681 However, since method attributes are actually stored on the underlying function
2682 object (``meth.im_func``), setting method attributes on either bound or unbound
2683 methods is disallowed. Attempting to set a method attribute results in a
2684 :exc:`TypeError` being raised. In order to set a method attribute, you need to
2685 explicitly set it on the underlying function object::
2692 c.method.im_func.whoami = 'my name is c'
2694 See :ref:`types` for more information.
2697 .. _bltin-code-objects:
2702 .. index:: object: code
2706 single: func_code (function object attribute)
2708 Code objects are used by the implementation to represent "pseudo-compiled"
2709 executable Python code such as a function body. They differ from function
2710 objects because they don't contain a reference to their global execution
2711 environment. Code objects are returned by the built-in :func:`compile` function
2712 and can be extracted from function objects through their :attr:`func_code`
2713 attribute. See also the :mod:`code` module.
2719 A code object can be executed or evaluated by passing it (instead of a source
2720 string) to the :keyword:`exec` statement or the built-in :func:`eval` function.
2722 See :ref:`types` for more information.
2725 .. _bltin-type-objects:
2734 Type objects represent the various object types. An object's type is accessed
2735 by the built-in function :func:`type`. There are no special operations on
2736 types. The standard module :mod:`types` defines names for all standard built-in
2739 Types are written like this: ``<type 'int'>``.
2742 .. _bltin-null-object:
2747 This object is returned by functions that don't explicitly return a value. It
2748 supports no special operations. There is exactly one null object, named
2749 ``None`` (a built-in name).
2751 It is written as ``None``.
2754 .. _bltin-ellipsis-object:
2759 This object is used by extended slice notation (see :ref:`slicings`). It
2760 supports no special operations. There is exactly one ellipsis object, named
2761 :const:`Ellipsis` (a built-in name).
2763 It is written as ``Ellipsis``.
2769 Boolean values are the two constant objects ``False`` and ``True``. They are
2770 used to represent truth values (although other values can also be considered
2771 false or true). In numeric contexts (for example when used as the argument to
2772 an arithmetic operator), they behave like the integers 0 and 1, respectively.
2773 The built-in function :func:`bool` can be used to cast any value to a Boolean,
2774 if the value can be interpreted as a truth value (see section Truth Value
2780 pair: Boolean; values
2782 They are written as ``False`` and ``True``, respectively.
2790 See :ref:`types` for this information. It describes stack frame objects,
2791 traceback objects, and slice objects.
2799 The implementation adds a few special read-only attributes to several object
2800 types, where they are relevant. Some of these are not reported by the
2801 :func:`dir` built-in function.
2804 .. attribute:: object.__dict__
2806 A dictionary or other mapping object used to store an object's (writable)
2810 .. attribute:: object.__methods__
2813 Use the built-in function :func:`dir` to get a list of an object's attributes.
2814 This attribute is no longer available.
2817 .. attribute:: object.__members__
2820 Use the built-in function :func:`dir` to get a list of an object's attributes.
2821 This attribute is no longer available.
2824 .. attribute:: instance.__class__
2826 The class to which a class instance belongs.
2829 .. attribute:: class.__bases__
2831 The tuple of base classes of a class object.
2834 .. attribute:: class.__name__
2836 The name of the class or type.
2839 The following attributes are only supported by :term:`new-style class`\ es.
2841 .. attribute:: class.__mro__
2843 This attribute is a tuple of classes that are considered when looking for
2844 base classes during method resolution.
2847 .. method:: class.mro()
2849 This method can be overridden by a metaclass to customize the method
2850 resolution order for its instances. It is called at class instantiation, and
2851 its result is stored in :attr:`__mro__`.
2854 .. method:: class.__subclasses__
2856 Each new-style class keeps a list of weak references to its immediate
2857 subclasses. This method returns a list of all those references still alive.
2860 >>> int.__subclasses__()
2864 .. rubric:: Footnotes
2866 .. [#] Additional information on these special methods may be found in the Python
2867 Reference Manual (:ref:`customization`).
2869 .. [#] As a consequence, the list ``[1, 2]`` is considered equal to ``[1.0, 2.0]``, and
2870 similarly for tuples.
2872 .. [#] They must have since the parser can't tell the type of the operands.
2874 .. [#] To format only a tuple you should therefore provide a singleton tuple whose only
2875 element is the tuple to be formatted.
2877 .. [#] The advantage of leaving the newline on is that returning an empty string is
2878 then an unambiguous EOF indication. It is also possible (in cases where it
2879 might matter, for example, if you want to make an exact copy of a file while
2880 scanning its lines) to tell whether the last line of a file ended in a newline
2881 or not (yes this happens!).