The following sections describe the standard types that are built into the interpreter.
Note
Historically (until release 2.2), Python’s built-in types have differed from user-defined types because it was not possible to use the built-in types as the basis for object-oriented inheritance. This limitation no longer exists.
The principal built-in types are numerics, sequences, mappings, files, classes, instances and exceptions.
Some operations are supported by several object types; in particular,
practically all objects can be compared, tested for truth value, and converted
to a string (with the
Any object can be tested for truth value, for use in an
zero of any numeric type, for example,
any empty sequence, for example,
any empty mapping, for example,
instances of user-defined classes, if the class defines a
All other values are considered true — so objects of many types are always true.
Operations and built-in functions that have a Boolean result always return
These are the Boolean operations, ordered by ascending priority:
Operation | Result | Notes |
---|---|---|
if x is false, then y, else x | (1) | |
if x is false, then x, else y | (2) | |
if x is false, then |
(3) |
Notes:
Comparison operations are supported by all objects. They all have the same
priority (which is higher than that of the Boolean operations). Comparisons can
be chained arbitrarily; for example,
This table summarizes the comparison operations:
Operation | Meaning | Notes |
---|---|---|
strictly less than | ||
less than or equal | ||
strictly greater than | ||
greater than or equal | ||
equal | ||
not equal | (1) | |
object identity | ||
negated object identity |
Notes:
Objects of different types, except different numeric types and different string
types, never compare equal; such objects are ordered consistently but
arbitrarily (so that sorting a heterogeneous array yields a consistent result).
Furthermore, some types (for example, file objects) support only a degenerate
notion of comparison where any two objects of that type are unequal. Again,
such objects are ordered arbitrarily but consistently. The
Instances of a class normally compare as non-equal unless the class defines the
CPython implementation detail: Objects of different types except numbers are ordered by their type names; objects of the same types that don’t support proper comparison are ordered by their address.
Two more operations with the same syntactic priority,
There are four distinct numeric types: plain integers, long
integers, floating point numbers, and complex numbers. In
addition, Booleans are a subtype of plain integers. Plain integers (also just
called integers) are implemented using
Numbers are created by numeric literals or as the result of built-in functions
and operators. Unadorned integer literals (including binary, hex, and octal
numbers) yield plain integers unless the value they denote is too large to be
represented as a plain integer, in which case they yield a long integer.
Integer literals with an
Python fully supports mixed arithmetic: when a binary arithmetic operator has
operands of different numeric types, the operand with the “narrower” type is
widened to that of the other, where plain integer is narrower than long integer
is narrower than floating point is narrower than complex. Comparisons between
numbers of mixed type use the same rule. [2] The constructors
All built-in numeric types support the following operations. See The power operator and later sections for the operators’ priorities.
Operation | Result | Notes |
---|---|---|
sum of x and y | ||
difference of x and y | ||
product of x and y | ||
quotient of x and y | (1) | |
(floored) quotient of x and y | (4)(5) | |
remainder of |
(4) | |
x negated | ||
x unchanged | ||
absolute value or magnitude of x | (3) | |
x converted to integer | (2) | |
x converted to long integer | (2) | |
x converted to floating point | (6) | |
a complex number with real part re, imaginary part im. im defaults to zero. | ||
conjugate of the complex number c. (Identity on real numbers) | ||
the pair |
(3)(4) | |
x to the power y | (3)(7) | |
x to the power y | (7) |
Notes:
For (plain or long) integer division, the result is an integer. The result is always rounded towards minus infinity: 1/2 is 0, (-1)/2 is -1, 1/(-2) is -1, and (-1)/(-2) is 0. Note that the result is a long integer if either operand is a long integer, regardless of the numeric value.
Conversion from floats using
See Built-in Functions for a full description.
Deprecated since version 2.3: The floor division operator, the modulo operator, and the
Also referred to as integer division. The resultant value is a whole integer, though the result’s type is not necessarily int.
float also accepts the strings “nan” and “inf” with an optional prefix “+” or “-” for Not a Number (NaN) and positive or negative infinity.
New in version 2.6.
Python defines
All
Operation | Result | Notes |
---|---|---|
x truncated to Integral | ||
x rounded to n digits, rounding half to even. If n is omitted, it defaults to 0. | ||
the greatest integral float <= x | ||
the least integral float >= x |
Bitwise operations only make sense for integers. Negative numbers are treated as their 2’s complement value (this assumes a sufficiently large number of bits that no overflow occurs during the operation).
The priorities of the binary bitwise operations are all lower than the numeric
operations and higher than the comparisons; the unary operation
This table lists the bitwise operations sorted in ascending priority (operations in the same box have the same priority):
Operation | Result | Notes |
---|---|---|
bitwise or of x and y | ||
bitwise exclusive or of x and y | ||
bitwise and of x and y | ||
x shifted left by n bits | (1)(2) | |
x shifted right by n bits | (1)(3) | |
the bits of x inverted |
Notes:
The integer types implement the
Return the number of bits necessary to represent an integer in binary, excluding the sign and leading zeros:
>>> n = -37
>>> bin(n)
'-0b100101'
>>> n.bit_length()
6
More precisely, if
Equivalent to:
def bit_length(self):
s = bin(self) # binary representation: bin(-37) --> '-0b100101'
s = s.lstrip('-0b') # remove leading zeros and minus sign
return len(s) # len('100101') --> 6
New in version 2.7.
The float type implements the
Return a pair of integers whose ratio is exactly equal to the
original float and with a positive denominator. Raises
New in version 2.6.
Return
>>> (-2.0).is_integer()
True
>>> (3.2).is_integer()
False
New in version 2.6.
Two methods support conversion to and from hexadecimal strings. Since Python’s floats are stored internally as binary numbers, converting a float to or from a decimal string usually involves a small rounding error. In contrast, hexadecimal strings allow exact representation and specification of floating-point numbers. This can be useful when debugging, and in numerical work.
Return a representation of a floating-point number as a hexadecimal
string. For finite floating-point numbers, this representation
will always include a leading
New in version 2.6.
Class method to return the float represented by a hexadecimal string s. The string s may have leading and trailing whitespace.
New in version 2.6.
Note that
A hexadecimal string takes the form:
[sign] ['0x'] integer ['.' fraction] ['p' exponent]
where the optional
Note that the exponent is written in decimal rather than hexadecimal,
and that it gives the power of 2 by which to multiply the coefficient.
For example, the hexadecimal string
>>> float.fromhex('0x3.a7p10')
3740.0
Applying the reverse conversion to
>>> float.hex(3740.0)
'0x1.d380000000000p+11'
New in version 2.2.
Python supports a concept of iteration over containers. This is implemented using two distinct methods; these are used to allow user-defined classes to support iteration. Sequences, described below in more detail, always support the iteration methods.
One method needs to be defined for container objects to provide iteration support:
Return an iterator object. The object is required to support the iterator
protocol described below. If a container supports different types of
iteration, additional methods can be provided to specifically request
iterators for those iteration types. (An example of an object supporting
multiple forms of iteration would be a tree structure which supports both
breadth-first and depth-first traversal.) This method corresponds to the
The iterator objects themselves are required to support the following two methods, which together form the iterator protocol:
Return the iterator object itself. This is required to allow both containers
and iterators to be used with the
Return the next item from the container. If there are no further items, raise
the
Python defines several iterator objects to support iteration over general and specific sequence types, dictionaries, and other more specialized forms. The specific types are not important beyond their implementation of the iterator protocol.
The intention of the protocol is that once an iterator’s
Python’s generators provide a convenient way to implement the iterator
protocol. If a container object’s
There are seven sequence types: strings, Unicode strings, lists, tuples, bytearrays, buffers, and xrange objects.
For other containers see the built in
String literals are written in single or double quotes:
Bytearray objects are created with the built-in function
Buffer objects are not directly supported by Python syntax, but can be created
by calling the built-in function
Objects of type xrange are similar to buffers in that there is no specific syntax to
create them, but they are created using the
Most sequence types support the following operations. The
This table lists the sequence operations sorted in ascending priority (operations in the same box have the same priority). In the table, s and t are sequences of the same type; n, i and j are integers:
Operation | Result | Notes |
---|---|---|
(1) | ||
(1) | ||
the concatenation of s and t | (6) | |
n shallow copies of s concatenated | (2) | |
ith item of s, origin 0 | (3) | |
slice of s from i to j | (3)(4) | |
slice of s from i to j with step k | (3)(5) | |
length of s | ||
smallest item of s | ||
largest item of s | ||
index of the first occurence of i in s | ||
total number of occurences of i in s |
Sequence types also support comparisons. In particular, tuples and lists are compared lexicographically by comparing corresponding elements. This means that to compare equal, every element must compare equal and the two sequences must be of the same type and have the same length. (For full details see Comparisons in the language reference.)
Notes:
When s is a string or Unicode string object the
Values of n less than
>>> lists = [[]] * 3
>>> lists
[[], [], []]
>>> lists[0].append(3)
>>> lists
[[3], [3], [3]]
What has happened is that
>>> lists = [[] for i in range(3)]
>>> lists[0].append(3)
>>> lists[1].append(5)
>>> lists[2].append(7)
>>> lists
[[3], [5], [7]]
If i or j is negative, the index is relative to the end of the string:
The slice of s from i to j is defined as the sequence of items with index
k such that
The slice of s from i to j with step k is defined as the sequence of
items with index
CPython implementation detail: If s and t are both strings, some Python implementations such as
CPython can usually perform an in-place optimization for assignments of
the form
Changed in version 2.4: Formerly, string concatenation never occurred in-place.
Below are listed the string methods which both 8-bit strings and
Unicode objects support. Some of them are also available on
In addition, Python’s strings support the sequence type methods
described in the Sequence Types — str, unicode, list, tuple, bytearray, buffer, xrange section. To output formatted strings
use template strings or the
Return a copy of the string with its first character capitalized and the rest lowercased.
For 8-bit strings, this method is locale-dependent.
Return centered in a string of length width. Padding is done using the specified fillchar (default is a space).
Changed in version 2.4: Support for the fillchar argument.
Return the number of non-overlapping occurrences of substring sub in the range [start, end]. Optional arguments start and end are interpreted as in slice notation.
Decodes the string using the codec registered for encoding. encoding
defaults to the default string encoding. errors may be given to set a
different error handling scheme. The default is
New in version 2.2.
Changed in version 2.3: Support for other error handling schemes added.
Changed in version 2.7: Support for keyword arguments added.
Return an encoded version of the string. Default encoding is the current
default string encoding. errors may be given to set a different error
handling scheme. The default for errors is
New in version 2.0.
Changed in version 2.3: Support for
Changed in version 2.7: Support for keyword arguments added.
Return
Changed in version 2.5: Accept tuples as suffix.
Return a copy of the string where all tab characters are replaced by one or
more spaces, depending on the current column and the given tab size. The
column number is reset to zero after each newline occurring in the string.
If tabsize is not given, a tab size of
Return the lowest index in the string where substring sub is found, such
that sub is contained in the slice
Perform a string formatting operation. The string on which this method is
called can contain literal text or replacement fields delimited by braces
>>> "The sum of 1 + 2 is {0}".format(1+2)
'The sum of 1 + 2 is 3'
See Format String Syntax for a description of the various formatting options that can be specified in format strings.
This method of string formatting is the new standard in Python 3, and
should be preferred to the
New in version 2.6.
Like
Return true if all characters in the string are alphanumeric and there is at least one character, false otherwise.
For 8-bit strings, this method is locale-dependent.
Return true if all characters in the string are alphabetic and there is at least one character, false otherwise.
For 8-bit strings, this method is locale-dependent.
Return true if all characters in the string are digits and there is at least one character, false otherwise.
For 8-bit strings, this method is locale-dependent.
Return true if all cased characters [4] in the string are lowercase and there is at least one cased character, false otherwise.
For 8-bit strings, this method is locale-dependent.
Return true if there are only whitespace characters in the string and there is at least one character, false otherwise.
For 8-bit strings, this method is locale-dependent.
Return true if the string is a titlecased string and there is at least one character, for example uppercase characters may only follow uncased characters and lowercase characters only cased ones. Return false otherwise.
For 8-bit strings, this method is locale-dependent.
Return true if all cased characters [4] in the string are uppercase and there is at least one cased character, false otherwise.
For 8-bit strings, this method is locale-dependent.
Return a string which is the concatenation of the strings in the iterable iterable. The separator between elements is the string providing this method.
Return the string left justified in a string of length width. Padding is done
using the specified fillchar (default is a space). The original string is
returned if width is less than or equal to
Changed in version 2.4: Support for the fillchar argument.
Return a copy of the string with all the cased characters [4] converted to lowercase.
For 8-bit strings, this method is locale-dependent.
Return a copy of the string with leading characters removed. The chars
argument is a string specifying the set of characters to be removed. If omitted
or
>>> ' spacious '.lstrip()
'spacious '
>>> 'www.example.com'.lstrip('cmowz.')
'example.com'
Changed in version 2.2.2: Support for the chars argument.
Split the string at the first occurrence of sep, and return a 3-tuple containing the part before the separator, the separator itself, and the part after the separator. If the separator is not found, return a 3-tuple containing the string itself, followed by two empty strings.
New in version 2.5.
Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.
Return the highest index in the string where substring sub is found, such
that sub is contained within
Like
Return the string right justified in a string of length width. Padding is done
using the specified fillchar (default is a space). The original string is
returned if width is less than or equal to
Changed in version 2.4: Support for the fillchar argument.
Split the string at the last occurrence of sep, and return a 3-tuple containing the part before the separator, the separator itself, and the part after the separator. If the separator is not found, return a 3-tuple containing two empty strings, followed by the string itself.
New in version 2.5.
Return a list of the words in the string, using sep as the delimiter string.
If maxsplit is given, at most maxsplit splits are done, the rightmost
ones. If sep is not specified or
New in version 2.4.
Return a copy of the string with trailing characters removed. The chars
argument is a string specifying the set of characters to be removed. If omitted
or
>>> ' spacious '.rstrip()
' spacious'
>>> 'mississippi'.rstrip('ipz')
'mississ'
Changed in version 2.2.2: Support for the chars argument.
Return a list of the words in the string, using sep as the delimiter
string. If maxsplit is given, at most maxsplit splits are done (thus,
the list will have at most
If sep is given, consecutive delimiters are not grouped together and are
deemed to delimit empty strings (for example,
If sep is not specified or is
For example,
Return a list of the lines in the string, breaking at line boundaries. This method uses the universal newlines approach to splitting lines. Line breaks are not included in the resulting list unless keepends is given and true.
For example,
Unlike
Return
Changed in version 2.5: Accept tuples as prefix.
Return a copy of the string with the leading and trailing characters removed.
The chars argument is a string specifying the set of characters to be removed.
If omitted or
>>> ' spacious '.strip()
'spacious'
>>> 'www.example.com'.strip('cmowz.')
'example'
Changed in version 2.2.2: Support for the chars argument.
Return a copy of the string with uppercase characters converted to lowercase and vice versa.
For 8-bit strings, this method is locale-dependent.
Return a titlecased version of the string where words start with an uppercase character and the remaining characters are lowercase.
The algorithm uses a simple language-independent definition of a word as groups of consecutive letters. The definition works in many contexts but it means that apostrophes in contractions and possessives form word boundaries, which may not be the desired result:
>>> "they're bill's friends from the UK".title()
"They'Re Bill'S Friends From The Uk"
A workaround for apostrophes can be constructed using regular expressions:
>>> import re
>>> def titlecase(s):
... return re.sub(r"[A-Za-z]+('[A-Za-z]+)?",
... lambda mo: mo.group(0)[0].upper() +
... mo.group(0)[1:].lower(),
... s)
...
>>> titlecase("they're bill's friends.")
"They're Bill's Friends."
For 8-bit strings, this method is locale-dependent.
Return a copy of the string where all characters occurring in the optional argument deletechars are removed, and the remaining characters have been mapped through the given translation table, which must be a string of length 256.
You can use the
>>> 'read this short text'.translate(None, 'aeiou')
'rd ths shrt txt'
New in version 2.6: Support for a
For Unicode objects, the
Return a copy of the string with all the cased characters [4] converted to
uppercase. Note that
For 8-bit strings, this method is locale-dependent.
Return the numeric string left filled with zeros in a string of length
width. A sign prefix is handled correctly. The original string is
returned if width is less than or equal to
New in version 2.2.2.
The following methods are present only on unicode objects:
Return
Return
String and Unicode objects have one unique built-in operation: the
If format requires a single argument, values may be a single non-tuple object. [5] Otherwise, values must be a tuple with exactly the number of items specified by the format string, or a single mapping object (for example, a dictionary).
A conversion specifier contains two or more characters and has the following components, which must occur in this order:
When the right argument is a dictionary (or other mapping type), then the
formats in the string must include a parenthesised mapping key into that
dictionary inserted immediately after the
>>> print '%(language)s has %(number)03d quote types.' % \
... {"language": "Python", "number": 2}
Python has 002 quote types.
In this case no
The conversion flag characters are:
Flag | Meaning |
---|---|
The value conversion will use the “alternate form” (where defined below). | |
The conversion will be zero padded for numeric values. | |
The converted value is left adjusted (overrides the |
|
(a space) A blank should be left before a positive number (or empty string) produced by a signed conversion. | |
A sign character ( |
A length modifier (
The conversion types are:
Conversion | Meaning | Notes |
---|---|---|
Signed integer decimal. | ||
Signed integer decimal. | ||
Signed octal value. | (1) | |
Obsolete type – it is identical to |
(7) | |
Signed hexadecimal (lowercase). | (2) | |
Signed hexadecimal (uppercase). | (2) | |
Floating point exponential format (lowercase). | (3) | |
Floating point exponential format (uppercase). | (3) | |
Floating point decimal format. | (3) | |
Floating point decimal format. | (3) | |
Floating point format. Uses lowercase exponential format if exponent is less than -4 or not less than precision, decimal format otherwise. | (4) | |
Floating point format. Uses uppercase exponential format if exponent is less than -4 or not less than precision, decimal format otherwise. | (4) | |
Single character (accepts integer or single character string). | ||
String (converts any Python object using
|
(5) | |
String (converts any Python object using
|
(6) | |
No argument is converted, results in a |
Notes:
The alternate form causes a leading zero (
The alternate form causes a leading
The alternate form causes the result to always contain a decimal point, even if no digits follow it.
The precision determines the number of digits after the decimal point and defaults to 6.
The alternate form causes the result to always contain a decimal point, and trailing zeroes are not removed as they would otherwise be.
The precision determines the number of significant digits before and after the decimal point and defaults to 6.
The
The precision determines the maximal number of characters used.
If the object or format provided is a
The precision determines the maximal number of characters used.
See PEP 237.
Since Python strings have an explicit length,
Changed in version 2.7:
Additional string operations are defined in standard modules
The
XRange objects have very little behavior: they only support indexing, iteration,
and the
List and
Operation | Result | Notes |
---|---|---|
item i of s is replaced by x | ||
slice of s from i to j is replaced by the contents of the iterable t | ||
same as |
||
the elements of |
(1) | |
removes the elements of
|
||
same as |
(2) | |
same as |
(3) | |
return number of i‘s for
which |
||
return smallest k such that
|
(4) | |
same as |
(5) | |
same as |
(6) | |
same as |
(4) | |
reverses the items of s in place | (7) | |
sort the items of s in place | (7)(8)(9)(10) |
Notes:
t must have the same length as the slice it is replacing.
The C implementation of Python has historically accepted multiple parameters and implicitly joined them into a tuple; this no longer works in Python 2.0. Use of this misfeature has been deprecated since Python 1.4.
x can be any iterable object.
Raises
Changed in version 2.3: Previously,
When a negative index is passed as the first parameter to the
Changed in version 2.3: Previously, all negative indices were truncated to zero.
The
The
The
cmp specifies a custom comparison function of two arguments (list items) which
should return a negative, zero or positive number depending on whether the first
argument is considered smaller than, equal to, or larger than the second
argument:
key specifies a function of one argument that is used to extract a comparison
key from each list element:
reverse is a boolean value. If set to
In general, the key and reverse conversion processes are much faster than
specifying an equivalent cmp function. This is because cmp is called
multiple times for each list element while key and reverse touch each
element only once. Use
Changed in version 2.3: Support for
Changed in version 2.4: Support for key and reverse was added.
Starting with Python 2.3, the
CPython implementation detail: While a list is being sorted, the effect of attempting to mutate, or even
inspect, the list is undefined. The C implementation of Python 2.3 and
newer makes the list appear empty for the duration, and raises
A set object is an unordered collection of distinct hashable objects.
Common uses include membership testing, removing duplicates from a sequence, and
computing mathematical operations such as intersection, union, difference, and
symmetric difference.
(For other containers see the built in
New in version 2.4.
Like other collections, sets support
There are currently two built-in set types,
As of Python 2.7, non-empty sets (not frozensets) can be created by placing a
comma-separated list of elements within braces, for example:
The constructors for both classes work the same:
Return a new set or frozenset object whose elements are taken from
iterable. The elements of a set must be hashable. To represent sets of
sets, the inner sets must be
Instances of
Return the cardinality of set s.
Test x for membership in s.
Test x for non-membership in s.
Return True if the set has no elements in common with other. Sets are disjoint if and only if their intersection is the empty set.
New in version 2.6.
Test whether every element in the set is in other.
Test whether the set is a proper subset of other, that is,
Test whether every element in other is in the set.
Test whether the set is a proper superset of other, that is,
Return a new set with elements from the set and all others.
Changed in version 2.6: Accepts multiple input iterables.
Return a new set with elements common to the set and all others.
Changed in version 2.6: Accepts multiple input iterables.
Return a new set with elements in the set that are not in the others.
Changed in version 2.6: Accepts multiple input iterables.
Return a new set with elements in either the set or other but not both.
Return a new set with a shallow copy of s.
Note, the non-operator versions of
Both
Instances of
The subset and equality comparisons do not generalize to a complete ordering
function. For example, any two disjoint sets are not equal and are not
subsets of each other, so all of the following return
Since sets only define partial ordering (subset relationships), the output of
the
Set elements, like dictionary keys, must be hashable.
Binary operations that mix
The following table lists operations available for
Update the set, adding elements from all others.
Changed in version 2.6: Accepts multiple input iterables.
Update the set, keeping only elements found in it and all others.
Changed in version 2.6: Accepts multiple input iterables.
Update the set, removing elements found in others.
Changed in version 2.6: Accepts multiple input iterables.
Update the set, keeping only elements found in either set, but not in both.
Add element elem to the set.
Remove element elem from the set. Raises
Remove element elem from the set if it is present.
Remove all elements from the set.
Note, the non-operator versions of the
Note, the elem argument to the
See also
A mapping object maps hashable values to arbitrary objects.
Mappings are mutable objects. There is currently only one standard mapping
type, the dictionary. (For other containers see the built in
A dictionary’s keys are almost arbitrary values. Values that are not
hashable, that is, values containing lists, dictionaries or other
mutable types (that are compared by value rather than by object identity) may
not be used as keys. Numeric types used for keys obey the normal rules for
numeric comparison: if two numbers compare equal (such as
Dictionaries can be created by placing a comma-separated list of
Return a new dictionary initialized from an optional positional argument and a possibly empty set of keyword arguments.
If no positional argument is given, an empty dictionary is created. If a positional argument is given and it is a mapping object, a dictionary is created with the same key-value pairs as the mapping object. Otherwise, the positional argument must be an iterator object. Each item in the iterable must itself be an iterator with exactly two objects. The first object of each item becomes a key in the new dictionary, and the second object the corresponding value. If a key occurs more than once, the last value for that key becomes the corresponding value in the new dictionary.
If keyword arguments are given, the keyword arguments and their values are added to the dictionary created from the positional argument. If a key being added is already present, the value from the keyword argument replaces the value from the positional argument.
To illustrate, the following examples all return a dictionary equal to
>>> a = dict(one=1, two=2, three=3)
>>> b = {'one': 1, 'two': 2, 'three': 3}
>>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
>>> d = dict([('two', 2), ('one', 1), ('three', 3)])
>>> e = dict({'three': 3, 'one': 1, 'two': 2})
>>> a == b == c == d == e
True
Providing keyword arguments as in the first example only works for keys that are valid Python identifiers. Otherwise, any valid keys can be used.
New in version 2.2.
Changed in version 2.3: Support for building a dictionary from keyword arguments added.
These are the operations that dictionaries support (and therefore, custom mapping types should support too):
Return the number of items in the dictionary d.
Return the item of d with key key. Raises a
New in version 2.5: If a subclass of dict defines a method
Set
Remove
Return
New in version 2.2.
Equivalent to
New in version 2.2.
Return an iterator over the keys of the dictionary. This is a shortcut
for
Remove all items from the dictionary.
Return a shallow copy of the dictionary.
Create a new dictionary with keys from seq and values set to value.
New in version 2.3.
Return the value for key if key is in the dictionary, else default.
If default is not given, it defaults to
Test for the presence of key in the dictionary.
Return a copy of the dictionary’s list of
CPython implementation detail: Keys and values are listed in an arbitrary order which is non-random, varies across Python implementations, and depends on the dictionary’s history of insertions and deletions.
If
Return an iterator over the dictionary’s
Using
New in version 2.2.
Return an iterator over the dictionary’s keys. See the note for
Using
New in version 2.2.
Return an iterator over the dictionary’s values. See the note for
Using
New in version 2.2.
Return a copy of the dictionary’s list of keys. See the note for
If key is in the dictionary, remove it and return its value, else return
default. If default is not given and key is not in the dictionary,
a
New in version 2.3.
Remove and return an arbitrary
If key is in the dictionary, return its value. If not, insert key
with a value of default and return default. default defaults to
Update the dictionary with the key/value pairs from other, overwriting
existing keys. Return
Changed in version 2.4: Allowed the argument to be an iterable of key/value pairs and allowed keyword arguments.
Return a copy of the dictionary’s list of values. See the note for
Return a new view of the dictionary’s items (
New in version 2.7.
Return a new view of the dictionary’s keys. See below for documentation of view objects.
New in version 2.7.
Return a new view of the dictionary’s values. See below for documentation of view objects.
New in version 2.7.
The objects returned by
Dictionary views can be iterated over to yield their respective data, and support membership tests:
Return the number of entries in the dictionary.
Return an iterator over the keys, values or items (represented as tuples of
Keys and values are iterated over in an arbitrary order which is non-random,
varies across Python implementations, and depends on the dictionary’s history
of insertions and deletions. If keys, values and items views are iterated
over with no intervening modifications to the dictionary, the order of items
will directly correspond. This allows the creation of
Iterating views while adding or deleting entries in the dictionary may raise
a
Return
Keys views are set-like since their entries are unique and hashable. If all values are hashable, so that (key, value) pairs are unique and hashable, then the items view is also set-like. (Values views are not treated as set-like since the entries are generally not unique.) Then these set operations are available (“other” refers either to another view or a set):
Return the intersection of the dictview and the other object as a new set.
Return the union of the dictview and the other object as a new set.
Return the difference between the dictview and the other object (all elements in dictview that aren’t in other) as a new set.
Return the symmetric difference (all elements either in dictview or other, but not in both) of the dictview and the other object as a new set.
An example of dictionary view usage:
>>> dishes = {'eggs': 2, 'sausage': 1, 'bacon': 1, 'spam': 500}
>>> keys = dishes.viewkeys()
>>> values = dishes.viewvalues()
>>> # iteration
>>> n = 0
>>> for val in values:
... n += val
>>> print(n)
504
>>> # keys and values are iterated over in the same order
>>> list(keys)
['eggs', 'bacon', 'sausage', 'spam']
>>> list(values)
[2, 1, 1, 500]
>>> # view objects are dynamic and reflect dict changes
>>> del dishes['eggs']
>>> del dishes['sausage']
>>> list(keys)
['spam', 'bacon']
>>> # set operations
>>> keys & {'eggs', 'bacon', 'salad'}
{'bacon'}
File objects are implemented using C’s
When a file operation fails for an I/O-related reason, the exception
Files have the following methods:
Close the file. A closed file cannot be read or written any more. Any operation
which requires that the file be open will raise a
As of Python 2.5, you can avoid having to call this method explicitly if you use
the
from __future__ import with_statement # This isn't required in Python 2.6
with open("hello.txt") as f:
for line in f:
print line,
In older versions of Python, you would have needed to do this to get the same effect:
f = open("hello.txt")
try:
for line in f:
print line,
finally:
f.close()
Note
Not all “file-like” types in Python support use as a context manager for the
Flush the internal buffer, like
Note
Return the integer “file descriptor” that is used by the underlying
implementation to request I/O operations from the operating system. This can be
useful for other, lower level interfaces that use file descriptors, such as the
Note
File-like objects which do not have a real file descriptor should not provide this method!
Return
Note
If a file-like object is not associated with a real file, this method should not be implemented.
A file object is its own iterator, for example
New in version 2.3.
Read at most size bytes from the file (less if the read hits EOF before
obtaining size bytes). If the size argument is negative or omitted, read
all data until EOF is reached. The bytes are returned as a string object. An
empty string is returned when EOF is encountered immediately. (For certain
files, like ttys, it makes sense to continue reading after an EOF is hit.) Note
that this method may call the underlying C function
Note
This function is simply a wrapper for the underlying
Read one entire line from the file. A trailing newline character is kept in the string (but may be absent when a file ends with an incomplete line). [6] If the size argument is present and non-negative, it is a maximum byte count (including the trailing newline) and an incomplete line may be returned. When size is not 0, an empty string is returned only when EOF is encountered immediately.
Note
Unlike
Read until EOF using
This method returns the same thing as
New in version 2.1.
Deprecated since version 2.3: Use
Set the file’s current position, like
For example,
Note that if the file is opened for appending
(mode
Note that not all file objects are seekable.
Changed in version 2.6: Passing float values as offset has been deprecated.
Return the file’s current position, like
Note
On Windows,
Truncate the file’s size. If the optional size argument is present, the file is truncated to (at most) that size. The size defaults to the current position. The current file position is not changed. Note that if a specified size exceeds the file’s current size, the result is platform-dependent: possibilities include that the file may remain unchanged, increase to the specified size as if zero-filled, or increase to the specified size with undefined new content. Availability: Windows, many Unix variants.
Write a string to the file. There is no return value. Due to buffering, the
string may not actually show up in the file until the
Write a sequence of strings to the file. The sequence can be any iterable
object producing strings, typically a list of strings. There is no return value.
(The name is intended to match
Files support the iterator protocol. Each iteration returns the same result as
File objects also offer a number of other interesting attributes. These are not required for file-like objects, but should be implemented if they make sense for the particular object.
bool indicating the current state of the file object. This is a read-only
attribute; the
The encoding that this file uses. When Unicode strings are written to a file,
they will be converted to byte strings using this encoding. In addition, when
the file is connected to a terminal, the attribute gives the encoding that the
terminal is likely to use (that information might be incorrect if the user has
misconfigured the terminal). The attribute is read-only and may not be present
on all file-like objects. It may also be
New in version 2.3.
The Unicode error handler used along with the encoding.
New in version 2.6.
The I/O mode for the file. If the file was created using the
If the file object was created using
If Python was built with universal newlines enabled (the default) this
read-only attribute exists, and for files opened in universal newline read
mode it keeps track of the types of newlines encountered while reading the
file. The values it can take are
Boolean that indicates whether a space character needs to be printed before
another value when using the
New in version 2.7.
Create a
A
A
>>> v = memoryview('abcefg')
>>> v[1]
'b'
>>> v[-1]
'g'
>>> v[1:4]
<memory at 0x77ab28>
>>> v[1:4].tobytes()
'bce'
If the object the memoryview is over supports changing its data, the memoryview supports slice assignment:
>>> data = bytearray('abcefg')
>>> v = memoryview(data)
>>> v.readonly
False
>>> v[0] = 'z'
>>> data
bytearray(b'zbcefg')
>>> v[1:4] = '123'
>>> data
bytearray(b'z123fg')
>>> v[2] = 'spam'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: cannot modify size of memoryview object
Notice how the size of the memoryview object cannot be changed.
Return the data in the buffer as a bytestring (an object of class
>>> m = memoryview("abc")
>>> m.tobytes()
'abc'
Return the data in the buffer as a list of integers.
>>> memoryview("abc").tolist()
[97, 98, 99]
There are also several readonly attributes available:
A string containing the format (in
The size in bytes of each element of the memoryview.
A tuple of integers the length of
An integer indicating how many dimensions of a multi-dimensional array the memory represents.
A tuple of integers the length of
A bool indicating whether the memory is read only.
New in version 2.5.
Python’s
The context management protocol consists of a pair of methods that need to be provided for a context manager object to define a runtime context:
Enter the runtime context and return either this object or another object
related to the runtime context. The value returned by this method is bound to
the identifier in the
An example of a context manager that returns itself is a file object. File
objects return themselves from __enter__() to allow
An example of a context manager that returns a related object is the one
returned by
Exit the runtime context and return a Boolean flag indicating if any exception
that occurred should be suppressed. If an exception occurred while executing the
body of the
Returning a true value from this method will cause the
The exception passed in should never be reraised explicitly - instead, this
method should return a false value to indicate that the method completed
successfully and does not want to suppress the raised exception. This allows
context management code (such as
Python defines several context managers to support easy thread synchronisation,
prompt closure of files or other objects, and simpler manipulation of the active
decimal arithmetic context. The specific types are not treated specially beyond
their implementation of the context management protocol. See the
Python’s generators and the
Note that there is no specific slot for any of these methods in the type structure for Python objects in the Python/C API. Extension types wanting to define these methods must provide them as a normal Python accessible method. Compared to the overhead of setting up the runtime context, the overhead of a single class dictionary lookup is negligible.
The interpreter supports several other kinds of objects. Most of these support only one or two operations.
The only special operation on a module is attribute access:
A special attribute of every module is
Modules built into the interpreter are written like this:
See Objects, values and types and Class definitions for these.
Function objects are created by function definitions. The only operation on a
function object is to call it:
There are really two flavors of function objects: built-in functions and user-defined functions. Both support the same operation (to call the function), but the implementation is different, hence the different object types.
See Function definitions for more information.
Methods are functions that are called using the attribute notation. There are
two flavors: built-in methods (such as
The implementation adds two special read-only attributes to class instance
methods:
Class instance methods are either bound or unbound, referring to whether the
method was accessed through an instance or a class, respectively. When a method
is unbound, its
Like function objects, methods objects support getting arbitrary attributes.
However, since method attributes are actually stored on the underlying function
object (
>>> class C:
... def method(self):
... pass
...
>>> c = C()
>>> c.method.whoami = 'my name is method' # can't set on the method
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'instancemethod' object has no attribute 'whoami'
>>> c.method.im_func.whoami = 'my name is method'
>>> c.method.whoami
'my name is method'
See The standard type hierarchy for more information.
Code objects are used by the implementation to represent “pseudo-compiled”
executable Python code such as a function body. They differ from function
objects because they don’t contain a reference to their global execution
environment. Code objects are returned by the built-in
A code object can be executed or evaluated by passing it (instead of a source
string) to the
See The standard type hierarchy for more information.
Type objects represent the various object types. An object’s type is accessed
by the built-in function
Types are written like this:
This object is returned by functions that don’t explicitly return a value. It
supports no special operations. There is exactly one null object, named
It is written as
This object is used by extended slice notation (see Slicings). It
supports no special operations. There is exactly one ellipsis object, named
It is written as
This object is returned from comparisons and binary operations when they are asked to operate on types they don’t support. See Comparisons for more information.
It is written as
Boolean values are the two constant objects
They are written as
See The standard type hierarchy for this information. It describes stack frame objects, traceback objects, and slice objects.
The implementation adds a few special read-only attributes to several object
types, where they are relevant. Some of these are not reported by the
A dictionary or other mapping object used to store an object’s (writable) attributes.
Deprecated since version 2.2: Use the built-in function
Deprecated since version 2.2: Use the built-in function
The class to which a class instance belongs.
The tuple of base classes of a class object.
The name of the class or type.
The following attributes are only supported by new-style classes.
This attribute is a tuple of classes that are considered when looking for base classes during method resolution.
This method can be overridden by a metaclass to customize the method
resolution order for its instances. It is called at class instantiation, and
its result is stored in
Each new-style class keeps a list of weak references to its immediate subclasses. This method returns a list of all those references still alive. Example:
>>> int.__subclasses__()
[<type 'bool'>]
Footnotes
[1] | Additional information on these special methods may be found in the Python Reference Manual (Basic customization). |
[2] | As a consequence, the list |
[3] | They must have since the parser can’t tell the type of the operands. |
[4] | (1, 2, 3, 4) Cased characters are those with general category property being one of “Lu” (Letter, uppercase), “Ll” (Letter, lowercase), or “Lt” (Letter, titlecase). |
[5] | To format only a tuple you should therefore provide a singleton tuple whose only element is the tuple to be formatted. |
[6] | The advantage of leaving the newline on is that returning an empty string is then an unambiguous EOF indication. It is also possible (in cases where it might matter, for example, if you want to make an exact copy of a file while scanning its lines) to tell whether the last line of a file ended in a newline or not (yes this happens!). |