Built-in Types

The following sections describe the standard types that are built into the interpreter.

The principal built-in types are numerics, sequences, mappings, classes, instances and exceptions.

Some collection classes are mutable. The methods that add, subtract, or rearrange their members in place, and don’t return a specific item, never return the collection instance itself butNone.

Some operations are supported by several object types; in particular, practically all objects can be compared for equality, tested for truth value, and converted to a string (with therepr()function or the slightly differentstr()function). The latter function is implicitly used when an object is written by theprint()function.

Truth Value Testing

Any object can be tested for truth value, for use in anifor whilecondition or as operand of the Boolean operations below.

By default, an object is considered true unless its class defines either a __bool__()method that returnsFalseor a __len__()method that returns zero, when called with the object.[1]Here are most of the built-in objects considered false:

  • constants defined to be false:NoneandFalse

  • zero of any numeric type:0,0.0,0j,Decimal(0), Fraction(0,1)

  • empty sequences and collections:'',(),[],{},set(), range(0)

Operations and built-in functions that have a Boolean result always return0 orFalsefor false and1orTruefor true, unless otherwise stated. (Important exception: the Boolean operationsorandandalways return one of their operands.)

Boolean Operations —and,or,not

These are the Boolean operations, ordered by ascending priority:

Operation

Result

Notes

xory

ifxis true, thenx,else y

(1)

xandy

ifxis false, thenx,else y

(2)

notx

ifxis false, thenTrue, elseFalse

(3)

Notes:

  1. This is a short-circuit operator, so it only evaluates the second argument if the first one is false.

  2. This is a short-circuit operator, so it only evaluates the second argument if the first one is true.

  3. nothas a lower priority than non-Boolean operators, sonota==bis interpreted asnot(a==b),anda==notbis a syntax error.

Comparisons

There are eight comparison operations in Python. They all have the same priority (which is higher than that of the Boolean operations). Comparisons can be chained arbitrarily; for example,x<y<=zis equivalent tox<yand y<=z,except thatyis evaluated only once (but in both caseszis not evaluated at all whenx<yis found to be false).

This table summarizes the comparison operations:

Operation

Meaning

<

strictly less than

<=

less than or equal

>

strictly greater than

>=

greater than or equal

==

equal

!=

not equal

is

object identity

isnot

negated object identity

Objects of different types, except different numeric types, never compare equal. The==operator is always defined but for some object types (for example, class objects) is equivalent tois.The<,<=,>and>= operators are only defined where they make sense; for example, they raise a TypeErrorexception when one of the arguments is a complex number.

Non-identical instances of a class normally compare as non-equal unless the class defines the__eq__()method.

Instances of a class cannot be ordered with respect to other instances of the same class, or other types of object, unless the class defines enough of the methods__lt__(),__le__(),__gt__(),and __ge__()(in general,__lt__()and __eq__()are sufficient, if you want the conventional meanings of the comparison operators).

The behavior of theisandisnotoperators cannot be customized; also they can be applied to any two objects and never raise an exception.

Two more operations with the same syntactic priority,inand notin,are supported by types that areiterableor implement the__contains__()method.

Numeric Types —int,float,complex

There are three distinct numeric types:integers,floating-point numbers,andcomplex numbers.In addition, Booleans are a subtype of integers. Integers have unlimited precision. Floating-point numbers are usually implemented usingdoublein C; information about the precision and internal representation of floating-point numbers for the machine on which your program is running is available insys.float_info.Complex numbers have a real and imaginary part, which are each a floating-point number. To extract these parts from a complex numberz,usez.realandz.imag.(The standard library includes the additional numeric typesfractions.Fraction,for rationals, anddecimal.Decimal,for floating-point numbers with user-definable precision.)

Numbers are created by numeric literals or as the result of built-in functions and operators. Unadorned integer literals (including hex, octal and binary numbers) yield integers. Numeric literals containing a decimal point or an exponent sign yield floating-point numbers. Appending'j'or'J'to a numeric literal yields an imaginary number (a complex number with a zero real part) which you can add to an integer or float to get a complex number with real and imaginary parts.

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 integer is narrower than floating point, which is narrower than complex. A comparison between numbers of different types behaves as though the exact values of those numbers were being compared.[2]

The constructorsint(),float(),and complex()can be used to produce numbers of a specific type.

All numeric types (except complex) support the following operations (for priorities of the operations, seeOperator precedence):

Operation

Result

Notes

Full documentation

x+y

sum ofxandy

x-y

difference ofxandy

x*y

product ofxandy

x/y

quotient ofxandy

x//y

floored quotient ofxand y

(1)(2)

x%y

remainder ofx/y

(2)

-x

xnegated

+x

xunchanged

abs(x)

absolute value or magnitude of x

abs()

int(x)

xconverted to integer

(3)(6)

int()

float(x)

xconverted to floating point

(4)(6)

float()

complex(re,im)

a complex number with real part re,imaginary partim. imdefaults to zero.

(6)

complex()

c.conjugate()

conjugate of the complex number c

divmod(x,y)

the pair(x//y,x%y)

(2)

divmod()

pow(x,y)

xto the powery

(5)

pow()

x**y

xto the powery

(5)

Notes:

  1. Also referred to as integer division. For operands of typeint, the result has typeint.For operands of typefloat, the result has typefloat.In general, the result is a whole integer, though the result’s type is not necessarilyint.The result is always rounded towards minus infinity:1//2is0,(-1)//2is -1,1//(-2)is-1,and(-1)//(-2)is0.

  2. Not for complex numbers. Instead convert to floats usingabs()if appropriate.

  3. Conversion fromfloattointtruncates, discarding the fractional part. See functionsmath.floor()andmath.ceil()for alternative conversions.

  4. float also accepts the strings “nan” and “inf” with an optional prefix “+” or “-” for Not a Number (NaN) and positive or negative infinity.

  5. Python definespow(0,0)and0**0to be1,as is common for programming languages.

  6. The numeric literals accepted include the digits0to9or any Unicode equivalent (code points with theNdproperty).

    Seethe Unicode Standard for a complete list of code points with theNdproperty.

Allnumbers.Realtypes (intandfloat) also include the following operations:

Operation

Result

math.trunc(x)

xtruncated toIntegral

round(x[, n])

xrounded tondigits, rounding half to even. Ifnis omitted, it defaults to 0.

math.floor(x)

the greatestIntegral <=x

math.ceil(x)

the leastIntegral>=x

For additional numeric operations see themathandcmath modules.

Bitwise Operations on Integer Types

Bitwise operations only make sense for integers. The result of bitwise operations is calculated as though carried out in two’s complement with an infinite number of sign bits.

The priorities of the binary bitwise operations are all lower than the numeric operations and higher than the comparisons; the unary operation~has the same priority as the other unary numeric operations (+and-).

This table lists the bitwise operations sorted in ascending priority:

Operation

Result

Notes

x|y

bitwiseorofxand y

(4)

x^y

bitwiseexclusive orof xandy

(4)

x&y

bitwiseandofxand y

(4)

x<<n

xshifted left bynbits

(1)(2)

x>>n

xshifted right bynbits

(1)(3)

~x

the bits ofxinverted

Notes:

  1. Negative shift counts are illegal and cause aValueErrorto be raised.

  2. A left shift bynbits is equivalent to multiplication bypow(2,n).

  3. A right shift bynbits is equivalent to floor division bypow(2,n).

  4. Performing these calculations with at least one extra sign extension bit in a finite two’s complement representation (a working bit-width of 1+max(x.bit_length(),y.bit_length())or more) is sufficient to get the same result as if there were an infinite number of sign bits.

Additional Methods on Integer Types

The int type implements thenumbers.Integralabstract base class.In addition, it provides a few more methods:

int.bit_length()

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, ifxis nonzero, thenx.bit_length()is the unique positive integerksuch that2**(k-1)<=abs(x)<2**k. Equivalently, whenabs(x)is small enough to have a correctly rounded logarithm, thenk=1+int(log(abs(x),2)). Ifxis zero, thenx.bit_length()returns0.

Equivalent to:

defbit_length(self):
s=bin(self)# binary representation: bin(-37) --> '-0b100101'
s=s.lstrip('-0b')# remove leading zeros and minus sign
returnlen(s)# len('100101') --> 6

Added in version 3.1.

int.bit_count()

Return the number of ones in the binary representation of the absolute value of the integer. This is also known as the population count. Example:

>>>n=19
>>>bin(n)
'0b10011'
>>>n.bit_count()
3
>>>(-n).bit_count()
3

Equivalent to:

defbit_count(self):
returnbin(self).count("1")

Added in version 3.10.

int.to_bytes(length=1,byteorder='big',*,signed=False)

Return an array of bytes representing an integer.

>>>(1024).to_bytes(2,byteorder='big')
b'\x04\x00'
>>>(1024).to_bytes(10,byteorder='big')
b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00'
>>>(-1024).to_bytes(10,byteorder='big',signed=True)
b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00'
>>>x=1000
>>>x.to_bytes((x.bit_length()+7)//8,byteorder='little')
b'\xe8\x03'

The integer is represented usinglengthbytes, and defaults to 1. An OverflowErroris raised if the integer is not representable with the given number of bytes.

Thebyteorderargument determines the byte order used to represent the integer, and defaults to"big".Ifbyteorderis "big",the most significant byte is at the beginning of the byte array. Ifbyteorderis"little",the most significant byte is at the end of the byte array.

Thesignedargument determines whether two’s complement is used to represent the integer. IfsignedisFalseand a negative integer is given, anOverflowErroris raised. The default value forsigned isFalse.

The default values can be used to conveniently turn an integer into a single byte object:

>>>(65).to_bytes()
b'A'

However, when using the default arguments, don’t try to convert a value greater than 255 or you’ll get anOverflowError.

Equivalent to:

defto_bytes(n,length=1,byteorder='big',signed=False):
ifbyteorder=='little':
order=range(length)
elifbyteorder=='big':
order=reversed(range(length))
else:
raiseValueError("byteorder must be either 'little' or 'big'")

returnbytes((n>>i*8)&0xffforiinorder)

Added in version 3.2.

Changed in version 3.11:Added default argument values forlengthandbyteorder.

classmethodint.from_bytes(bytes,byteorder='big',*,signed=False)

Return the integer represented by the given array of bytes.

>>>int.from_bytes(b'\x00\x10',byteorder='big')
16
>>>int.from_bytes(b'\x00\x10',byteorder='little')
4096
>>>int.from_bytes(b'\xfc\x00',byteorder='big',signed=True)
-1024
>>>int.from_bytes(b'\xfc\x00',byteorder='big',signed=False)
64512
>>>int.from_bytes([255,0,0],byteorder='big')
16711680

The argumentbytesmust either be abytes-like objector an iterable producing bytes.

Thebyteorderargument determines the byte order used to represent the integer, and defaults to"big".Ifbyteorderis "big",the most significant byte is at the beginning of the byte array. Ifbyteorderis"little",the most significant byte is at the end of the byte array. To request the native byte order of the host system, usesys.byteorderas the byte order value.

Thesignedargument indicates whether two’s complement is used to represent the integer.

Equivalent to:

deffrom_bytes(bytes,byteorder='big',signed=False):
ifbyteorder=='little':
little_ordered=list(bytes)
elifbyteorder=='big':
little_ordered=list(reversed(bytes))
else:
raiseValueError("byteorder must be either 'little' or 'big'")

n=sum(b<<i*8fori,binenumerate(little_ordered))
ifsignedandlittle_orderedand(little_ordered[-1]&0x80):
n-=1<<8*len(little_ordered)

returnn

Added in version 3.2.

Changed in version 3.11:Added default argument value forbyteorder.

int.as_integer_ratio()

Return a pair of integers whose ratio is equal to the original integer and has a positive denominator. The integer ratio of integers (whole numbers) is always the integer as the numerator and1as the denominator.

Added in version 3.8.

int.is_integer()

ReturnsTrue.Exists for duck type compatibility withfloat.is_integer().

Added in version 3.12.

Additional Methods on Float

The float type implements thenumbers.Realabstract base class.float also has the following additional methods.

float.as_integer_ratio()

Return a pair of integers whose ratio is exactly equal to the original float. The ratio is in lowest terms and has a positive denominator. Raises OverflowErroron infinities and aValueErroron NaNs.

float.is_integer()

ReturnTrueif the float instance is finite with integral value, andFalseotherwise:

>>>(-2.0).is_integer()
True
>>>(3.2).is_integer()
False

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 decimalstring 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.

float.hex()

Return a representation of a floating-point number as a hexadecimal string. For finite floating-point numbers, this representation will always include a leading0xand a trailingpand exponent.

classmethodfloat.fromhex(s)

Class method to return the float represented by a hexadecimal strings.The stringsmay have leading and trailing whitespace.

Note thatfloat.hex()is an instance method, while float.fromhex()is a class method.

A hexadecimal string takes the form:

[sign]['0x']integer['.'fraction]['p'exponent]

where the optionalsignmay by either+or-,integer andfractionare strings of hexadecimal digits, andexponent is a decimal integer with an optional leading sign. Case is not significant, and there must be at least one hexadecimal digit in either the integer or the fraction. This syntax is similar to the syntax specified in section 6.4.4.2 of the C99 standard, and also to the syntax used in Java 1.5 onwards. In particular, the output of float.hex()is usable as a hexadecimal floating-point literal in C or Java code, and hexadecimal strings produced by C’s%aformat character or Java’sDouble.toHexStringare accepted by float.fromhex().

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 string0x3.a7p10represents the floating-point number(3+10./16+7./16**2)*2.0**10,or 3740.0:

>>>float.fromhex('0x3.a7p10')
3740.0

Applying the reverse conversion to3740.0gives a different hexadecimal string representing the same number:

>>>float.hex(3740.0)
'0x1.d380000000000p+11'

Hashing of numeric types

For numbersxandy,possibly of different types, it’s a requirement thathash(x)==hash(y)wheneverx==y(see the__hash__() method documentation for more details). For ease of implementation and efficiency across a variety of numeric types (includingint, float,decimal.Decimalandfractions.Fraction) Python’s hash for numeric types is based on a single mathematical function that’s defined for any rational number, and hence applies to all instances of intandfractions.Fraction,and all finite instances of floatanddecimal.Decimal.Essentially, this function is given by reduction moduloPfor a fixed primeP.The value ofPis made available to Python as themodulusattribute of sys.hash_info.

CPython implementation detail:Currently, the prime used isP=2**31-1on machines with 32-bit C longs andP=2**61-1on machines with 64-bit C longs.

Here are the rules in detail:

  • Ifx=m/nis a nonnegative rational number andnis not divisible byP,definehash(x)asm*invmod(n,P)%P,whereinvmod(n, P)gives the inverse ofnmoduloP.

  • Ifx=m/nis a nonnegative rational number andnis divisible byP(butmis not) thennhas no inverse moduloPand the rule above doesn’t apply; in this case define hash(x)to be the constant valuesys.hash_info.inf.

  • Ifx=m/nis a negative rational number definehash(x) as-hash(-x).If the resulting hash is-1,replace it with -2.

  • The particular valuessys.hash_info.infand-sys.hash_info.inf are used as hash values for positive infinity or negative infinity (respectively).

  • For acomplexnumberz,the hash values of the real and imaginary parts are combined by computinghash(z.real)+ sys.hash_info.imag*hash(z.imag),reduced modulo 2**sys.hash_info.widthso that it lies in range(-2**(sys.hash_info.width-1),2**(sys.hash_info.width- 1)).Again, if the result is-1,it’s replaced with-2.

To clarify the above rules, here’s some example Python code, equivalent to the built-in hash, for computing the hash of a rational number,float,orcomplex:

importsys,math

defhash_fraction(m,n):
"""Compute the hash of a rational number m / n.

Assumes m and n are integers, with n positive.
Equivalent to hash(fractions.Fraction(m, n)).

"""
P=sys.hash_info.modulus
# Remove common factors of P. (Unnecessary if m and n already coprime.)
whilem%P==n%P==0:
m,n=m//P,n//P

ifn%P==0:
hash_value=sys.hash_info.inf
else:
# Fermat's Little Theorem: pow(n, P-1, P) is 1, so
# pow(n, P-2, P) gives the inverse of n modulo P.
hash_value=(abs(m)%P)*pow(n,P-2,P)%P
ifm<0:
hash_value=-hash_value
ifhash_value==-1:
hash_value=-2
returnhash_value

defhash_float(x):
"""Compute the hash of a float x." ""

ifmath.isnan(x):
returnobject.__hash__(x)
elifmath.isinf(x):
returnsys.hash_info.infifx>0else-sys.hash_info.inf
else:
returnhash_fraction(*x.as_integer_ratio())

defhash_complex(z):
"""Compute the hash of a complex number z." ""

hash_value=hash_float(z.real)+sys.hash_info.imag*hash_float(z.imag)
# do a signed reduction modulo 2**sys.hash_info.width
M=2**(sys.hash_info.width-1)
hash_value=(hash_value&(M-1))-(hash_value&M)
ifhash_value==-1:
hash_value=-2
returnhash_value

Boolean Type -bool

Booleans represent truth values. Thebooltype has exactly two constant instances:TrueandFalse.

The built-in functionbool()converts any value to a boolean, if the value can be interpreted as a truth value (see sectionTruth Value Testingabove).

For logical operations, use theboolean operatorsand, orandnot. When applying the bitwise operators&,|,^to two booleans, they return a bool equivalent to the logical operations “and”, “or”, “xor”. However, the logical operatorsand,orand!=should be preferred over&,|and^.

Deprecated since version 3.12:The use of the bitwise inversion operator~is deprecated and will raise an error in Python 3.16.

boolis a subclass ofint(seeNumeric Types — int, float, complex). In many numeric contexts,FalseandTruebehave like the integers 0 and 1, respectively. However, relying on this is discouraged; explicitly convert usingint() instead.

Iterator Types

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 provideiterable support:

container.__iter__()

Return aniteratorobject. 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 tp_iterslot of the type structure for Python objects in the Python/C API.

The iterator objects themselves are required to support the following two methods, which together form theiterator protocol:

iterator.__iter__()

Return theiteratorobject itself. This is required to allow both containers and iterators to be used with theforand instatements. This method corresponds to the tp_iterslot of the type structure for Python objects in the Python/C API.

iterator.__next__()

Return the next item from theiterator.If there are no further items, raise theStopIterationexception. This method corresponds to thetp_iternextslot of the type structure for Python objects in the Python/C API.

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.

Once an iterator’s__next__()method raises StopIteration,it must continue to do so on subsequent calls. Implementations that do not obey this property are deemed broken.

Generator Types

Python’sgenerators provide a convenient way to implement the iterator protocol. If a container object’s__iter__()method is implemented as a generator, it will automatically return an iterator object (technically, a generator object) supplying the__iter__()and__next__() methods. More information about generators can be found inthe documentation for the yield expression.

Sequence Types —list,tuple,range

There are three basic sequence types: lists, tuples, and range objects. Additional sequence types tailored for processing of binary dataandtext stringsare described in dedicated sections.

Common Sequence Operations

The operations in the following table are supported by most sequence types, both mutable and immutable. Thecollections.abc.SequenceABC is provided to make it easier to correctly implement these operations on custom sequence types.

This table lists the sequence operations sorted in ascending priority. In the table,sandtare sequences of the same type,n,i,jandkare integers andxis an arbitrary object that meets any type and value restrictions imposed bys.

Theinandnotinoperations have the same priorities as the comparison operations. The+(concatenation) and*(repetition) operations have the same priority as the corresponding numeric operations.[3]

Operation

Result

Notes

xins

Trueif an item ofsis equal tox,elseFalse

(1)

xnotins

Falseif an item ofsis equal tox,elseTrue

(1)

s+t

the concatenation ofsand t

(6)(7)

s*nor n*s

equivalent to addingsto itselfntimes

(2)(7)

s[i]

ith item ofs,origin 0

(3)

s[i:j]

slice ofsfromitoj

(3)(4)

s[i:j:k]

slice ofsfromitoj with stepk

(3)(5)

len(s)

length ofs

min(s)

smallest item ofs

max(s)

largest item ofs

s.index(x[,i[,j]])

index of the first occurrence ofxins(at or after indexiand before indexj)

(8)

s.count(x)

total number of occurrences of xins

Sequences of the same type 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 seeComparisonsin the language reference.)

Forward and reversed iterators over mutable sequences access values using an index. That index will continue to march forward (or backward) even if the underlying sequence is mutated. The iterator terminates only when an IndexErroror aStopIterationis encountered (or when the index drops below zero).

Notes:

  1. While theinandnotinoperations are used only for simple containment testing in the general case, some specialised sequences (such asstr,bytesandbytearray) also use them for subsequence testing:

    >>>"gg"in"eggs"
    True
    
  2. Values ofnless than0are treated as0(which yields an empty sequence of the same type ass). Note that items in the sequences are not copied; they are referenced multiple times. This often haunts new Python programmers; consider:

    >>>lists=[[]]*3
    >>>lists
    [[], [], []]
    >>>lists[0].append(3)
    >>>lists
    [[3], [3], [3]]
    

    What has happened is that[[]]is a one-element list containing an empty list, so all three elements of[[]]*3are references to this single empty list. Modifying any of the elements oflistsmodifies this single list. You can create a list of different lists this way:

    >>>lists=[[]foriinrange(3)]
    >>>lists[0].append(3)
    >>>lists[1].append(5)
    >>>lists[2].append(7)
    >>>lists
    [[3], [5], [7]]
    

    Further explanation is available in the FAQ entry How do I create a multidimensional list?.

  3. Ifiorjis negative, the index is relative to the end of sequences: len(s)+iorlen(s)+jis substituted. But note that-0is still0.

  4. The slice ofsfromitojis defined as the sequence of items with index ksuch thati<=k<j.Ifiorjis greater thanlen(s),use len(s).Ifiis omitted orNone,use0.Ifjis omitted or None,uselen(s).Ifiis greater than or equal toj,the slice is empty.

  5. The slice ofsfromitojwith stepkis defined as the sequence of items with indexx=i+n*ksuch that0<=n<(j-i)/k.In other words, the indices arei,i+k,i+2*k,i+3*kand so on, stopping when jis reached (but never includingj). Whenkis positive, iandjare reduced tolen(s)if they are greater. Whenkis negative,iandjare reduced tolen(s)-1if they are greater. Ifiorjare omitted orNone,they become “end” values (which end depends on the sign ofk). Note,kcannot be zero. IfkisNone,it is treated like1.

  6. Concatenating immutable sequences always results in a new object. This means that building up a sequence by repeated concatenation will have a quadratic runtime cost in the total sequence length. To get a linear runtime cost, you must switch to one of the alternatives below:

    • if concatenatingstrobjects, you can build a list and use str.join()at the end or else write to anio.StringIO instance and retrieve its value when complete

    • if concatenatingbytesobjects, you can similarly use bytes.join()orio.BytesIO,or you can do in-place concatenation with abytearrayobject.bytearray objects are mutable and have an efficient overallocation mechanism

    • if concatenatingtupleobjects, extend alistinstead

    • for other types, investigate the relevant class documentation

  7. Some sequence types (such asrange) only support item sequences that follow specific patterns, and hence don’t support sequence concatenation or repetition.

  8. indexraisesValueErrorwhenxis not found ins. Not all implementations support passing the additional argumentsiandj. These arguments allow efficient searching of subsections of the sequence. Passing the extra arguments is roughly equivalent to usings[i:j].index(x),only without copying any data and with the returned index being relative to the start of the sequence rather than the start of the slice.

Immutable Sequence Types

The only operation that immutable sequence types generally implement that is not also implemented by mutable sequence types is support for thehash() built-in.

This support allows immutable sequences, such astupleinstances, to be used asdictkeys and stored insetandfrozenset instances.

Attempting to hash an immutable sequence that contains unhashable values will result inTypeError.

Mutable Sequence Types

The operations in the following table are defined on mutable sequence types. Thecollections.abc.MutableSequenceABC is provided to make it easier to correctly implement these operations on custom sequence types.

In the tablesis an instance of a mutable sequence type,tis any iterable object andxis an arbitrary object that meets any type and value restrictions imposed bys(for example,bytearrayonly accepts integers that meet the value restriction0<=x<=255).

Operation

Result

Notes

s[i]=x

itemiofsis replaced by x

s[i:j]=t

slice ofsfromitoj is replaced by the contents of the iterablet

dels[i:j]

same ass[i:j]=[]

s[i:j:k]=t

the elements ofs[i:j:k] are replaced by those oft

(1)

dels[i:j:k]

removes the elements of s[i:j:k]from the list

s.append(x)

appendsxto the end of the sequence (same as s[len(s):len(s)]=[x])

s.clear()

removes all items froms (same asdels[:])

(5)

s.copy()

creates a shallow copy ofs (same ass[:])

(5)

s.extend(t)or s+=t

extendsswith the contents oft(for the most part the same as s[len(s):len(s)]=t)

s*=n

updatesswith its contents repeatedntimes

(6)

s.insert(i,x)

insertsxintosat the index given byi (same ass[i:i]=[x])

s.pop()ors.pop(i)

retrieves the item atiand also removes it froms

(2)

s.remove(x)

removes the first item from swheres[i]is equal to x

(3)

s.reverse()

reverses the items ofsin place

(4)

Notes:

  1. Ifkis not equal to1,tmust have the same length as the slice it is replacing.

  2. The optional argumentidefaults to-1,so that by default the last item is removed and returned.

  3. remove()raisesValueErrorwhenxis not found ins.

  4. Thereverse()method modifies the sequence in place for economy of space when reversing a large sequence. To remind users that it operates by side effect, it does not return the reversed sequence.

  5. clear()andcopy()are included for consistency with the interfaces of mutable containers that don’t support slicing operations (such asdictandset).copy()is not part of the collections.abc.MutableSequenceABC, but most concrete mutable sequence classes provide it.

    Added in version 3.3:clear()andcopy()methods.

  6. The valuenis an integer, or an object implementing __index__().Zero and negative values ofnclear the sequence. Items in the sequence are not copied; they are referenced multiple times, as explained fors*nunderCommon Sequence Operations.

Lists

Lists are mutable sequences, typically used to store collections of homogeneous items (where the precise degree of similarity will vary by application).

classlist([iterable])

Lists may be constructed in several ways:

  • Using a pair of square brackets to denote the empty list:[]

  • Using square brackets, separating items with commas:[a],[a,b,c]

  • Using a list comprehension:[xforxiniterable]

  • Using the type constructor:list()orlist(iterable)

The constructor builds a list whose items are the same and in the same order asiterable’s items.iterablemay be either a sequence, a container that supports iteration, or an iterator object. Ifiterable is already a list, a copy is made and returned, similar toiterable[:]. For example,list('abc')returns['a','b','c']and list((1,2,3))returns[1,2,3]. If no argument is given, the constructor creates a new empty list,[].

Many other operations also produce lists, including thesorted() built-in.

Lists implement all of thecommonand mutablesequence operations. Lists also provide the following additional method:

sort(*,key=None,reverse=False)

This method sorts the list in place, using only<comparisons between items. Exceptions are not suppressed - if any comparison operations fail, the entire sort operation will fail (and the list will likely be left in a partially modified state).

sort()accepts two arguments that can only be passed by keyword (keyword-only arguments):

keyspecifies a function of one argument that is used to extract a comparison key from each list element (for example,key=str.lower). The key corresponding to each item in the list is calculated once and then used for the entire sorting process. The default value ofNone means that list items are sorted directly without calculating a separate key value.

Thefunctools.cmp_to_key()utility is available to convert a 2.x stylecmpfunction to akeyfunction.

reverseis a boolean value. If set toTrue,then the list elements are sorted as if each comparison were reversed.

This method modifies the sequence in place for economy of space when sorting a large sequence. To remind users that it operates by side effect, it does not return the sorted sequence (usesorted()to explicitly request a new sorted list instance).

Thesort()method is guaranteed to be stable. A sort is stable if it guarantees not to change the relative order of elements that compare equal — this is helpful for sorting in multiple passes (for example, sort by department, then by salary grade).

For sorting examples and a brief sorting tutorial, seeSorting Techniques.

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 makes the list appear empty for the duration, and raisesValueErrorif it can detect that the list has been mutated during a sort.

Tuples

Tuples are immutable sequences, typically used to store collections of heterogeneous data (such as the 2-tuples produced by theenumerate() built-in). Tuples are also used for cases where an immutable sequence of homogeneous data is needed (such as allowing storage in asetor dictinstance).

classtuple([iterable])

Tuples may be constructed in a number of ways:

  • Using a pair of parentheses to denote the empty tuple:()

  • Using a trailing comma for a singleton tuple:a,or(a,)

  • Separating items with commas:a,b,cor(a,b,c)

  • Using thetuple()built-in:tuple()ortuple(iterable)

The constructor builds a tuple whose items are the same and in the same order asiterable’s items.iterablemay be either a sequence, a container that supports iteration, or an iterator object. Ifiterable is already a tuple, it is returned unchanged. For example, tuple('abc')returns('a','b','c')and tuple([1,2,3])returns(1,2,3). If no argument is given, the constructor creates a new empty tuple,().

Note that it is actually the comma which makes a tuple, not the parentheses. The parentheses are optional, except in the empty tuple case, or when they are needed to avoid syntactic ambiguity. For example, f(a,b,c)is a function call with three arguments, while f((a,b,c))is a function call with a 3-tuple as the sole argument.

Tuples implement all of thecommonsequence operations.

For heterogeneous collections of data where access by name is clearer than access by index,collections.namedtuple()may be a more appropriate choice than a simple tuple object.

Ranges

Therangetype represents an immutable sequence of numbers and is commonly used for looping a specific number of times infor loops.

classrange(stop)
classrange(start,stop[,step])

The arguments to the range constructor must be integers (either built-in intor any object that implements the__index__()special method). If thestepargument is omitted, it defaults to1. If thestartargument is omitted, it defaults to0. Ifstepis zero,ValueErroris raised.

For a positivestep,the contents of a rangerare determined by the formular[i]=start+step*iwherei>=0and r[i]<stop.

For a negativestep,the contents of the range are still determined by the formular[i]=start+step*i,but the constraints arei>=0 andr[i]>stop.

A range object will be empty ifr[0]does not meet the value constraint. Ranges do support negative indices, but these are interpreted as inde xing from the end of the sequence determined by the positive indices.

Ranges containing absolute values larger thansys.maxsizeare permitted but some features (such aslen()) may raise OverflowError.

Range examples:

>>>list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>list(range(1,11))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>>list(range(0,30,5))
[0, 5, 10, 15, 20, 25]
>>>list(range(0,10,3))
[0, 3, 6, 9]
>>>list(range(0,-10,-1))
[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
>>>list(range(0))
[]
>>>list(range(1,0))
[]

Ranges implement all of thecommonsequence operations except concatenation and repetition (due to the fact that range objects can only represent sequences that follow a strict pattern and repetition and concatenation will usually violate that pattern).

start

The value of thestartparameter (or0if the parameter was not supplied)

stop

The value of thestopparameter

step

The value of thestepparameter (or1if the parameter was not supplied)

The advantage of therangetype over a regularlistor tupleis that arangeobject will always take the same (small) amount of memory, no matter the size of the range it represents (as it only stores thestart,stopandstepvalues, calculating individual items and subranges as needed).

Range objects implement thecollections.abc.SequenceABC, and provide features such as containment tests, element index lookup, slicing and support for negative indices (seeSequence Types — list, tuple, range):

>>>r=range(0,20,2)
>>>r
range(0, 20, 2)
>>>11inr
False
>>>10inr
True
>>>r.index(10)
5
>>>r[5]
10
>>>r[:5]
range(0, 10, 2)
>>>r[-1]
18

Testing range objects for equality with==and!=compares them as sequences. That is, two range objects are considered equal if they represent the same sequence of values. (Note that two range objects that compare equal might have differentstart, stopandstepattributes, for example range(0)==range(2,1,3)orrange(0,3,2)==range(0,4,2).)

Changed in version 3.2:Implement the Sequence ABC. Support slicing and negative indices. Testintobjects for membership in constant time instead of iterating through all items.

Changed in version 3.3:Define ‘==’ and ‘!=’ to compare range objects based on the sequence of values they define (instead of comparing based on object identity).

Added thestart,stopandstep attributes.

See also

  • Thelinspace recipe shows how to implement a lazy version of range suitable for floating-point applications.

Text Sequence Type —str

Textual data in Python is handled withstrobjects, orstrings. Strings are immutable sequencesof Unicode code points. String literals are written in a variety of ways:

  • Single quotes:'allowsembedded"double"quotes'

  • Double quotes:"allowsembedded'single'quotes "

  • Triple quoted:'''Threesinglequotes''',"""Threedoublequotes "" "

Triple quoted strings may span multiple lines - all associated whitespace will be included in the string literal.

String literals that are part of a single expression and have only whitespace between them will be implicitly converted to a single string literal. That is,( "spam""eggs" )=="spameggs ".

SeeString and Bytes literalsfor more about the various forms of string literal, including supportedescape sequences,and ther( “raw” ) prefix that disables most escape sequence processing.

Strings may also be created from other objects using thestr constructor.

Since there is no separate “character” type, inde xing a string produces strings of length 1. That is, for a non-empty strings,s[0]==s[0:1].

There is also no mutable string type, butstr.join()or io.StringIOcan be used to efficiently construct strings from multiple fragments.

Changed in version 3.3:For backwards compatibility with the Python 2 series, theuprefix is once again permitted on string literals. It has no effect on the meaning of string literals and cannot be combined with therprefix.

classstr(object='')
classstr(object=b'',encoding='utf-8',errors='strict')

Return astringversion ofobject.Ifobjectis not provided, returns the empty string. Otherwise, the behavior ofstr() depends on whetherencodingorerrorsis given, as follows.

If neitherencodingnorerrorsis given,str(object)returns type(object).__str__(object), which is the “informal” or nicely printable string representation ofobject.For string objects, this is the string itself. Ifobjectdoes not have a__str__() method, thenstr()falls back to returning repr(object).

If at least one ofencodingorerrorsis given,objectshould be a bytes-like object(e.g.bytesorbytearray). In this case, ifobjectis abytes(orbytearray) object, thenstr(bytes,encoding,errors)is equivalent to bytes.decode(encoding,errors).Otherwise, the bytes object underlying the buffer object is obtained before calling bytes.decode().SeeBinary Sequence Types — bytes, bytearray, memoryviewand Buffer Protocolfor information on buffer objects.

Passing abytesobject tostr()without theencoding orerrorsarguments falls under the first case of returning the informal string representation (see also the-bcommand-line option to Python). For example:

>>>str(b'Zoot!')
"b'Zoot!'"

For more information on thestrclass and its methods, see Text Sequence Type — strand theString Methodssection below. To output formatted strings, see thef-stringsandFormat String Syntax sections. In addition, see theText Processing Servicessection.

String Methods

Strings implement all of thecommonsequence operations, along with the additional methods described below.

Strings also support two styles of string formatting, one providing a large degree of flexibility and customization (seestr.format(), Format String SyntaxandCustom String Formatting) and the other based on C printfstyle formatting that handles a narrower range of types and is slightly harder to use correctly, but is often faster for the cases it can handle (printf-style String Formatting).

TheText Processing Servicessection of the standard library covers a number of other modules that provide various text related utilities (including regular expression support in theremodule).

str.capitalize()

Return a copy of the string with its first character capitalized and the rest lowercased.

Changed in version 3.8:The first character is now put into titlecase rather than uppercase. This means that characters like digraphs will only have their first letter capitalized, instead of the full character.

str.casefold()

Return a casefolded copy of the string. Casefolded strings may be used for caseless matching.

Casefolding is similar to lowercasing but more aggressive because it is intended to remove all case distinctions in a string. For example, the German lowercase letter'ß'is equivalent to"ss".Since it is already lowercase,lower()would do nothing to'ß';casefold() converts it to"ss".

The casefolding algorithm is described in section 3.13 ‘Default Case Folding’ of the Unicode Standard.

Added in version 3.3.

str.center(width[,fillchar])

Return centered in a string of lengthwidth.Padding is done using the specifiedfillchar(default is an ASCII space). The original string is returned ifwidthis less than or equal tolen(s).

str.count(sub[,start[,end]])

Return the number of non-overlapping occurrences of substringsubin the range [start,end]. Optional argumentsstartandendare interpreted as in slice notation.

Ifsubis empty, returns the number of empty strings between characters which is the length of the string plus one.

str.encode(encoding='utf-8',errors='strict')

Return the string encoded tobytes.

encodingdefaults to'utf-8'; seeStandard Encodingsfor possible values.

errorscontrols how encoding errors are handled. If'strict'(the default), aUnicodeErrorexception is raised. Other possible values are'ignore', 'replace','xmlcharrefreplace','backslashreplace'and any other name registered viacodecs.register_error(). SeeError Handlersfor details.

For performance reasons, the value oferrorsis not checked for validity unless an encoding error actually occurs, Python Development Modeis enabled or adebug buildis used.

Changed in version 3.1:Added support for keyword arguments.

Changed in version 3.9:The value of theerrorsargument is now checked inPython Development Modeand indebug mode.

str.endswith(suffix[,start[,end]])

ReturnTrueif the string ends with the specifiedsuffix,otherwise return False.suffixcan also be a tuple of suffixes to look for. With optional start,test beginning at that position. With optionalend,stop comparing at that position.

str.expandtabs(tabsize=8)

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. Tab positions occur everytabsizecharacters (default is 8, giving tab positions at columns 0, 8, 16 and so on). To expand the string, the current column is set to zero and the string is examined character by character. If the character is a tab (\t), one or more space characters are inserted in the result until the current column is equal to the next tab position. (The tab character itself is not copied.) If the character is a newline (\n) or return (\r), it is copied and the current column is reset to zero. Any other character is copied unchanged and the current column is incremented by one regardless of how the character is represented when printed.

>>>'01\t012\t0123\t01234'.expandtabs()
'01 012 0123 01234'
>>>'01\t012\t0123\t01234'.expandtabs(4)
'01 012 0123 01234'
str.find(sub[,start[,end]])

Return the lowest index in the string where substringsubis found within the slices[start:end].Optional argumentsstartandendare interpreted as in slice notation. Return-1ifsubis not found.

Note

Thefind()method should be used only if you need to know the position ofsub.To check ifsubis a substring or not, use the inoperator:

>>>'Py'in'Python'
True
str.format(*args,**kwargs)

Perform a string formatting operation. The string on which this method is called can contain literal text or replacement fields delimited by braces {}.Each replacement field contains either the numeric index of a positional argument, or the name of a keyword argument. Returns a copy of the string where each replacement field is replaced with the string value of the corresponding argument.

>>>"The sum of 1 + 2 is{0}".format(1+2)
'The sum of 1 + 2 is 3'

SeeFormat String Syntaxfor a description of the various formatting options that can be specified in format strings.

Note

When formatting a number (int,float,complex, decimal.Decimaland subclasses) with thentype (ex:'{:n}'.format(1234)), the function temporarily sets the LC_CTYPElocale to theLC_NUMERIClocale to decode decimal_pointandthousands_sepfields oflocaleconv()if they are non-ASCII or longer than 1 byte, and theLC_NUMERIClocale is different than theLC_CTYPElocale. This temporary change affects other threads.

Changed in version 3.7:When formatting a number with thentype, the function sets temporarily theLC_CTYPElocale to theLC_NUMERIClocale in some cases.

str.format_map(mapping,/)

Similar tostr.format(**mapping),except thatmappingis used directly and not copied to adict.This is useful if for examplemappingis a dict subclass:

>>>classDefault(dict):
...def__missing__(self,key):
...returnkey
...
>>>'{name}was born in{country}'.format_map(Default(name='Guido'))
'Guido was born in country'

Added in version 3.2.

str.index(sub[,start[,end]])

Likefind(),but raiseValueErrorwhen the substring is not found.

str.isalnum()

ReturnTrueif all characters in the string are Alpha numeric and there is at least one character,Falseotherwise. A charactercis Alpha numeric if one of the following returnsTrue:c.is Alpha (),c.isdecimal(), c.isdigit(),orc.isnumeric().

str.is Alpha()

ReturnTrueif all characters in the string are Alpha betic and there is at least one character,Falseotherwise. Alphabetic characters are those characters defined in the Unicode character database as “Letter”, i.e., those with general category property being one of “Lm”, “Lt”, “Lu”, “Ll”, or “Lo”. Note that this is different from theAlphabetic property defined in the section 4.10 ‘Letters, Alphabetic, and Ideographic’ of the Unicode Standard.

str.isascii()

ReturnTrueif the string is empty or all characters in the string are ASCII, Falseotherwise. ASCII characters have code points in the range U+0000-U+007F.

Added in version 3.7.

str.isdecimal()

ReturnTrueif all characters in the string are decimal characters and there is at least one character,False otherwise. Decimal characters are those that can be used to form numbers in base 10, e.g. U+0660, ARABIC-INDIC DIGIT ZERO. Formally a decimal character is a character in the Unicode General Category “Nd”.

str.isdigit()

ReturnTrueif all characters in the string are digits and there is at least one character,Falseotherwise. Digits include decimal characters and digits that need special handling, such as the compatibility superscript digits. This covers digits which cannot be used to form numbers in base 10, like the Kharosthi numbers. Formally, a digit is a character that has the property value Numeric_Type=Digit or Numeric_Type=Decimal.

str.isidentifier()

ReturnTrueif the string is a valid identifier according to the language definition, sectionIdentifiers and keywords.

keyword.iskeyword()can be used to test whether stringsis a reserved identifier, such asdefandclass.

Example:

>>>fromkeywordimportiskeyword

>>>'hello'.isidentifier(),iskeyword('hello')
(True, False)
>>>'def'.isidentifier(),iskeyword('def')
(True, True)
str.islower()

ReturnTrueif all cased characters[4]in the string are lowercase and there is at least one cased character,Falseotherwise.

str.isnumeric()

ReturnTrueif all characters in the string are numeric characters, and there is at least one character,False otherwise. Numeric characters include digit characters, and all characters that have the Unicode numeric value property, e.g. U+2155, VULGAR FRACTION ONE FIFTH. Formally, numeric characters are those with the property value Numeric_Type=Digit, Numeric_Type=Decimal or Numeric_Type=Numeric.

str.isprintable()

ReturnTrueif all characters in the string are printable or the string is empty,Falseotherwise. Nonprintable characters are those characters defined in the Unicode character database as “Other” or “Separator”, excepting the ASCII space (0x20) which is considered printable. (Note that printable characters in this context are those which should not be escaped when repr()is invoked on a string. It has no bearing on the handling of strings written tosys.stdoutorsys.stderr.)

str.isspace()

ReturnTrueif there are only whitespace characters in the string and there is at least one character,Falseotherwise.

A character iswhitespaceif in the Unicode character database (seeunicodedata), either its general category isZs ( “Separator, space” ), or its bidirectional class is one ofWS, B,orS.

str.istitle()

ReturnTrueif 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. ReturnFalseotherwise.

str.isupper()

ReturnTrueif all cased characters[4]in the string are uppercase and there is at least one cased character,Falseotherwise.

>>>'BANANA'.isupper()
True
>>>'banana'.isupper()
False
>>>'baNana'.isupper()
False
>>>' '.isupper()
False
str.join(iterable)

Return a string which is the concatenation of the strings initerable. ATypeErrorwill be raised if there are any non-string values in iterable,includingbytesobjects. The separator between elements is the string providing this method.

str.ljust(width[,fillchar])

Return the string left justified in a string of lengthwidth.Padding is done using the specifiedfillchar(default is an ASCII space). The original string is returned ifwidthis less than or equal tolen(s).

str.lower()

Return a copy of the string with all the cased characters[4]converted to lowercase.

The lowercasing algorithm used is described in section 3.13 ‘Default Case Folding’ of the Unicode Standard.

str.lstrip([chars])

Return a copy of the string with leading characters removed. Thechars argument is a string specifying the set of characters to be removed. If omitted orNone,thecharsargument defaults to removing whitespace. Thechars argument is not a prefix; rather, all combinations of its values are stripped:

>>>' spacious '.lstrip()
'spacious '
>>>' example '.lstrip('cmowz.')
'example '

Seestr.removeprefix()for a method that will remove a single prefix string rather than all of a set of characters. For example:

>>>'Arthur: three!'.lstrip('Arthur: ')
'ee!'
>>>'Arthur: three!'.removeprefix('Arthur: ')
'three!'
staticstr.maketrans(x[,y[,z]])

This static method returns a translation table usable forstr.translate().

If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters (strings of length 1) to Unicode ordinals, strings (of arbitrary lengths) orNone.Character keys will then be converted to ordinals.

If there are two arguments, they must be strings of equal length, and in the resulting dictionary, each character in x will be mapped to the character at the same position in y. If there is a third argument, it must be a string, whose characters will be mapped toNonein the result.

str.partition(sep)

Split the string at the first occurrence ofsep,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.

str.removeprefix(prefix,/)

If the string starts with theprefixstring, return string[len(prefix):].Otherwise, return a copy of the original string:

>>>'TestHook'.removeprefix('Test')
'Hook'
>>>'BaseTestCase'.removeprefix('Test')
'BaseTestCase'

Added in version 3.9.

str.removesuffix(suffix,/)

If the string ends with thesuffixstring and thatsuffixis not empty, returnstring[:-len(suffix)].Otherwise, return a copy of the original string:

>>>'MiscTests'.removesuffix('Tests')
'Misc'
>>>'TmpDirMixin'.removesuffix('Tests')
'TmpDirMixin'

Added in version 3.9.

str.replace(old,new,count=-1)

Return a copy of the string with all occurrences of substringoldreplaced by new.Ifcountis given, only the firstcountoccurrences are replaced. Ifcountis not specified or-1,then all occurrences are replaced.

Changed in version 3.13:countis now supported as a keyword argument.

str.rfind(sub[,start[,end]])

Return the highest index in the string where substringsubis found, such thatsubis contained withins[start:end].Optional argumentsstart andendare interpreted as in slice notation. Return-1on failure.

str.rindex(sub[,start[,end]])

Likerfind()but raisesValueErrorwhen the substringsubis not found.

str.rjust(width[,fillchar])

Return the string right justified in a string of lengthwidth.Padding is done using the specifiedfillchar(default is an ASCII space). The original string is returned ifwidthis less than or equal tolen(s).

str.rpartition(sep)

Split the string at the last occurrence ofsep,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.

str.rsplit(sep=None,maxsplit=-1)

Return a list of the words in the string, usingsepas the delimiter string. Ifmaxsplitis given, at mostmaxsplitsplits are done, therightmost ones. Ifsepis not specified orNone,any whitespace string is a separator. Except for splitting from the right,rsplit()behaves like split()which is described in detail below.

str.rstrip([chars])

Return a copy of the string with trailing characters removed. Thechars argument is a string specifying the set of characters to be removed. If omitted orNone,thecharsargument defaults to removing whitespace. Thechars argument is not a suffix; rather, all combinations of its values are stripped:

>>>' spacious '.rstrip()
' spacious'
>>>'mississippi'.rstrip('ipz')
'mississ'

Seestr.removesuffix()for a method that will remove a single suffix string rather than all of a set of characters. For example:

>>>'Monty Python'.rstrip(' Python')
'M'
>>>'Monty Python'.removesuffix(' Python')
'Monty'
str.split(sep=None,maxsplit=-1)

Return a list of the words in the string, usingsepas the delimiter string. Ifmaxsplitis given, at mostmaxsplitsplits are done (thus, the list will have at mostmaxsplit+1elements). Ifmaxsplitis not specified or-1,then there is no limit on the number of splits (all possible splits are made).

Ifsepis given, consecutive delimiters are not grouped together and are deemed to delimit empty strings (for example,'1,,2'.split(',')returns ['1','','2']). Thesepargument may consist of multiple characters as a single delimiter (to split with multiple delimiters, use re.split()). Splitting an empty string with a specified separator returns[''].

For example:

>>>'1,2,3'.split(',')
['1', '2', '3']
>>>'1,2,3'.split(',',maxsplit=1)
['1', '2,3']
>>>'1,2,,3,'.split(',')
['1', '2', '', '3', '']
>>>'1<>2<>3<4'.split('<>')
['1', '2', '3<4']

Ifsepis not specified or isNone,a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace. Consequently, splitting an empty string or a string consisting of just whitespace with aNoneseparator returns[].

For example:

>>>'1 2 3'.split()
['1', '2', '3']
>>>'1 2 3'.split(maxsplit=1)
['1', '2 3']
>>>' 1 2 3 '.split()
['1', '2', '3']
str.splitlines(keepends=False)

Return a list of the lines in the string, breaking at line boundaries. Line breaks are not included in the resulting list unlesskeependsis given and true.

This method splits on the following line boundaries. In particular, the boundaries are a superset ofuniversal newlines.

Representation

Description

\n

Line Feed

\r

Carriage Return

\r\n

Carriage Return + Line Feed

\vor\x0b

Line Tabulation

\for\x0c

Form Feed

\x1c

File Separator

\x1d

Group Separator

\x1e

Record Separator

\x85

Next Line (C1 Control Code)

\u2028

Line Separator

\u2029

Paragraph Separator

Changed in version 3.2:\vand\fadded to list of line boundaries.

For example:

>>>'ab c\n\nde fg\rkl\r\n'.splitlines()
['ab c', '', 'de fg', 'kl']
>>>'ab c\n\nde fg\rkl\r\n'.splitlines(keepends=True)
['ab c\n', '\n', 'de fg\r', 'kl\r\n']

Unlikesplit()when a delimiter stringsepis given, this method returns an empty list for the empty string, and a terminal line break does not result in an extra line:

>>>"".splitlines()
[]
>>>"One line\n".splitlines()
['One line']

For comparison,split('\n')gives:

>>>''.split('\n')
['']
>>>'Two lines\n'.split('\n')
['Two lines', '']
str.startswith(prefix[,start[,end]])

ReturnTrueif string starts with theprefix,otherwise returnFalse. prefixcan also be a tuple of prefixes to look for. With optionalstart, test string beginning at that position. With optionalend,stop comparing string at that position.

str.strip([chars])

Return a copy of the string with the leading and trailing characters removed. Thecharsargument is a string specifying the set of characters to be removed. If omitted orNone,thecharsargument defaults to removing whitespace. Thecharsargument is not a prefix or suffix; rather, all combinations of its values are stripped:

>>>' spacious '.strip()
'spacious'
>>>' example '.strip('cmowz.')
'example'

The outermost leading and trailingcharsargument values are stripped from the string. Characters are removed from the leading end until reaching a string character that is not contained in the set of characters inchars.A similar action takes place on the trailing end. For example:

>>>comment_string='#....... Section 3.2.1 Issue #32.......'
>>>comment_string.strip('.#! ')
'Section 3.2.1 Issue #32'
str.swapcase()

Return a copy of the string with uppercase characters converted to lowercase and vice versa. Note that it is not necessarily true that s.swapcase().swapcase()==s.

str.title()

Return a titlecased version of the string where words start with an uppercase character and the remaining characters are lowercase.

For example:

>>>'Hello world'.title()
'Hello World'

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"

Thestring.capwords()function does not have this problem, as it splits words on spaces only.

Alternatively, a workaround for apostrophes can be constructed using regular expressions:

>>>importre
>>>deftitlecase(s):
...returnre.sub(r"[A-Za-z]+('[A-Za-z]+)?",
...lambdamo:mo.group(0).capitalize(),
...s)
...
>>>titlecase("they're bill's friends.")
"They're Bill's Friends."
str.translate(table)

Return a copy of the string in which each character has been mapped through the given translation table. The table must be an object that implements inde xing via__getitem__(),typically amappingor sequence.When indexed by a Unicode ordinal (an integer), the table object can do any of the following: return a Unicode ordinal or a string, to map the character to one or more other characters; return None,to delete the character from the return string; or raise a LookupErrorexception, to map the character to itself.

You can usestr.maketrans()to create a translation map from character-to-character mappings in different formats.

See also thecodecsmodule for a more flexible approach to custom character mappings.

str.upper()

Return a copy of the string with all the cased characters[4]converted to uppercase. Note thats.upper().isupper()might beFalseifs contains uncased characters or if the Unicode category of the resulting character(s) is not “Lu” (Letter, uppercase), but e.g. “Lt” (Letter, titlecase).

The uppercasing algorithm used is described in section 3.13 ‘Default Case Folding’ of the Unicode Standard.

str.zfill(width)

Return a copy of the string left filled with ASCII'0'digits to make a string of lengthwidth.A leading sign prefix ('+'/'-') is handled by inserting the paddingafterthe sign character rather than before. The original string is returned ifwidthis less than or equal tolen(s).

For example:

>>>"42".zfill(5)
'00042'
>>>"-42".zfill(5)
'-0042'

printf-style String Formatting

Note

The formatting operations described here exhibit a variety of quirks that lead to a number of common errors (such as failing to display tuples and dictionaries correctly). Using the newerformatted string literals,thestr.format()interface, ortemplate stringsmay help avoid these errors. Each of these alternatives provides their own trade-offs and benefits of simplicity, flexibility, and/or extensibility.

String objects have one unique built-in operation: the%operator (modulo). This is also known as the stringformattingorinterpolationoperator. Givenformat%values(whereformatis a string),%conversion specifications informatare replaced with zero or more elements ofvalues. The effect is similar to using thesprintf()function in the C language. For example:

>>>print('%shas%dquote types.'%('Python',2))
Python has 2 quote types.

Ifformatrequires a single argument,valuesmay be a single non-tuple object.[5]Otherwise,valuesmust 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:

  1. The'%'character, which marks the start of the specifier.

  2. Mapping key (optional), consisting of a parenthesised sequence of characters (for example,(somename)).

  3. Conversion flags (optional), which affect the result of some conversion types.

  4. Minimum field width (optional). If specified as an'*'(asterisk), the actual width is read from the next element of the tuple invalues,and the object to convert comes after the minimum field width and optional precision.

  5. Precision (optional), given as a'.'(dot) followed by the precision. If specified as'*'(an asterisk), the actual precision is read from the next element of the tuple invalues,and the value to convert comes after the precision.

  6. Length modifier (optional).

  7. Conversion type.

When the right argument is a dictionary (or other mapping type), then the formats in the stringmustinclude a parenthesised mapping key into that dictionary inserted immediately after the'%'character. The mapping key selects the value to be formatted from the mapping. For example:

>>>print('%(language)shas%(number)03dquote types.'%
...{'language':"Python","number":2})
Python has 002 quote types.

In this case no*specifiers may occur in a format (since they require a sequential parameter list).

The conversion flag characters are:

Flag

Meaning

'#'

The value conversion will use the “alternate form” (where defined below).

'0'

The conversion will be zero padded for numeric values.

'-'

The converted value is left adjusted (overrides the'0' conversion if both are given).

''

(a space) A blank should be left before a positive number (or empty string) produced by a signed conversion.

'+'

A sign character ('+'or'-') will precede the conversion (overrides a “space” flag).

A length modifier (h,l,orL) may be present, but is ignored as it is not necessary for Python – so e.g.%ldis identical to%d.

The conversion types are:

Conversion

Meaning

Notes

'd'

Signed integer decimal.

'i'

Signed integer decimal.

'o'

Signed octal value.

(1)

'u'

Obsolete type – it is identical to'd'.

(6)

'x'

Signed hexadecimal (lowercase).

(2)

'X'

Signed hexadecimal (uppercase).

(2)

'e'

Floating-point exponential format (lowercase).

(3)

'E'

Floating-point exponential format (uppercase).

(3)

'f'

Floating-point decimal format.

(3)

'F'

Floating-point decimal format.

(3)

'g'

Floating-point format. Uses lowercase exponential format if exponent is less than -4 or not less than precision, decimal format otherwise.

(4)

'G'

Floating-point format. Uses uppercase exponential format if exponent is less than -4 or not less than precision, decimal format otherwise.

(4)

'c'

Single character (accepts integer or single character string).

'r'

String (converts any Python object using repr()).

(5)

's'

String (converts any Python object using str()).

(5)

'a'

String (converts any Python object using ascii()).

(5)

'%'

No argument is converted, results in a'%' character in the result.

Notes:

  1. The alternate form causes a leading octal specifier ('0o') to be inserted before the first digit.

  2. The alternate form causes a leading'0x'or'0X'(depending on whether the'x'or'X'format was used) to be inserted before the first digit.

  3. 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.

  4. 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.

  5. If precision isN,the output is truncated toNcharacters.

  6. SeePEP 237.

Since Python strings have an explicit length,%sconversions do not assume that'\0'is the end of the string.

Changed in version 3.1:%fconversions for numbers whose absolute value is over 1e50 are no longer replaced by%gconversions.

Binary Sequence Types —bytes,bytearray,memoryview

The core built-in types for manipulating binary data arebytesand bytearray.They are supported bymemoryviewwhich uses thebuffer protocolto access the memory of other binary objects without needing to make a copy.

Thearraymodule supports efficient storage of basic data types like 32-bit integers and IEEE754 double-precision floating values.

Bytes Objects

Bytes objects are immutable sequences of single bytes. Since many major binary protocols are based on the ASCII text encoding, bytes objects offer several methods that are only valid when working with ASCII compatible data and are closely related to string objects in a variety of other ways.

classbytes([source[,encoding[,errors]]])

Firstly, the syntax for bytes literals is largely the same as that for string literals, except that abprefix is added:

  • Single quotes:b'stillallowsembedded"double"quotes'

  • Double quotes:b "stillallowsembedded'single'quotes "

  • Triple quoted:b'''3singlequotes''',b "" "3doublequotes "" "

Only ASCII characters are permitted in bytes literals (regardless of the declared source code encoding). Any binary values over 127 must be entered into bytes literals using the appropriate escape sequence.

As with string literals, bytes literals may also use arprefix to disable processing of escape sequences. SeeString and Bytes literalsfor more about the various forms of bytes literal, including supported escape sequences.

While bytes literals and representations are based on ASCII text, bytes objects actually behave like immutable sequences of integers, with each value in the sequence restricted such that0<=x<256(attempts to violate this restriction will triggerValueError). This is done deliberately to emphasise that while many binary formats include ASCII based elements and can be usefully manipulated with some text-oriented algorithms, this is not generally the case for arbitrary binary data (blindly applying text processing algorithms to binary data formats that are not ASCII compatible will usually lead to data corruption).

In addition to the literal forms, bytes objects can be created in a number of other ways:

  • A zero-filled bytes object of a specified length:bytes(10)

  • From an iterable of integers:bytes(range(20))

  • Copying existing binary data via the buffer protocol:bytes(obj)

Also see thebytesbuilt-in.

Since 2 hexadecimal digits correspond precisely to a single byte, hexadecimal numbers are a commonly used format for describing binary data. Accordingly, the bytes type has an additional class method to read data in that format:

classmethodfromhex(string)

Thisbytesclass method returns a bytes object, decoding the given string object. The string must contain two hexadecimal digits per byte, with ASCII whitespace being ignored.

>>>bytes.fromhex('2Ef0 F1f2 ')
b'.\xf0\xf1\xf2'

Changed in version 3.7:bytes.fromhex()now skips all ASCII whitespace in the string, not just spaces.

A reverse conversion function exists to transform a bytes object into its hexadecimal representation.

hex([sep[,bytes_per_sep]])

Return a string object containing two hexadecimal digits for each byte in the instance.

>>>b'\xf0\xf1\xf2'.hex()
'f0f1f2'

If you want to make the hex string easier to read, you can specify a single character separatorsepparameter to include in the output. By default, this separator will be included between each byte. A second optionalbytes_per_sepparameter controls the spacing. Positive values calculate the separator position from the right, negative values from the left.

>>>value=b'\xf0\xf1\xf2'
>>>value.hex('-')
'f0-f1-f2'
>>>value.hex('_',2)
'f0_f1f2'
>>>b'UUDDLRLRAB'.hex(' ',-4)
'55554444 4c524c52 4142'

Added in version 3.5.

Changed in version 3.8:bytes.hex()now supports optionalsepandbytes_per_sep parameters to insert separators between bytes in the hex output.

Since bytes objects are sequences of integers (akin to a tuple), for a bytes objectb,b[0]will be an integer, whileb[0:1]will be a bytes object of length 1. (This contrasts with text strings, where both inde xing and slicing will produce a string of length 1)

The representation of bytes objects uses the literal format (b'...') since it is often more useful than e.g.bytes([46,46,46]).You can always convert a bytes object into a list of integers usinglist(b).

Bytearray Objects

bytearrayobjects are a mutable counterpart tobytes objects.

classbytearray([source[,encoding[,errors]]])

There is no dedicated literal syntax for bytearray objects, instead they are always created by calling the constructor:

  • Creating an empty instance:bytearray()

  • Creating a zero-filled instance with a given length:bytearray(10)

  • From an iterable of integers:bytearray(range(20))

  • Copying existing binary data via the buffer protocol:bytearray(b'Hi!')

As bytearray objects are mutable, they support the mutablesequence operations in addition to the common bytes and bytearray operations described inBytes and Bytearray Operations.

Also see thebytearraybuilt-in.

Since 2 hexadecimal digits correspond precisely to a single byte, hexadecimal numbers are a commonly used format for describing binary data. Accordingly, the bytearray type has an additional class method to read data in that format:

classmethodfromhex(string)

Thisbytearrayclass method returns bytearray object, decoding the given string object. The string must contain two hexadecimal digits per byte, with ASCII whitespace being ignored.

>>>bytearray.fromhex('2Ef0 F1f2 ')
bytearray(b'.\xf0\xf1\xf2')

Changed in version 3.7:bytearray.fromhex()now skips all ASCII whitespace in the string, not just spaces.

A reverse conversion function exists to transform a bytearray object into its hexadecimal representation.

hex([sep[,bytes_per_sep]])

Return a string object containing two hexadecimal digits for each byte in the instance.

>>>bytearray(b'\xf0\xf1\xf2').hex()
'f0f1f2'

Added in version 3.5.

Changed in version 3.8:Similar tobytes.hex(),bytearray.hex()now supports optionalsepandbytes_per_sepparameters to insert separators between bytes in the hex output.

Since bytearray objects are sequences of integers (akin to a list), for a bytearray objectb,b[0]will be an integer, whileb[0:1]will be a bytearray object of length 1. (This contrasts with text strings, where both inde xing and slicing will produce a string of length 1)

The representation of bytearray objects uses the bytes literal format (bytearray(b'...')) since it is often more useful than e.g. bytearray([46,46,46]).You can always convert a bytearray object into a list of integers usinglist(b).

Bytes and Bytearray Operations

Both bytes and bytearray objects support thecommon sequence operations. They interoperate not just with operands of the same type, but with anybytes-like object.Due to this flexibility, they can be freely mixed in operations without causing errors. However, the return type of the result may depend on the order of operands.

Note

The methods on bytes and bytearray objects don’t accept strings as their arguments, just as the methods on strings don’t accept bytes as their arguments. For example, you have to write:

a="abc"
b=a.replace("a","f")

and:

a=b"abc"
b=a.replace(b"a",b"f")

Some bytes and bytearray operations assume the use of ASCII compatible binary formats, and hence should be avoided when working with arbitrary binary data. These restrictions are covered below.

Note

Using these ASCII based operations to manipulate binary data that is not stored in an ASCII based format may lead to data corruption.

The following methods on bytes and bytearray objects can be used with arbitrary binary data.

bytes.count(sub[,start[,end]])
bytearray.count(sub[,start[,end]])

Return the number of non-overlapping occurrences of subsequencesubin the range [start,end]. Optional argumentsstartandendare interpreted as in slice notation.

The subsequence to search for may be anybytes-like objector an integer in the range 0 to 255.

Ifsubis empty, returns the number of empty slices between characters which is the length of the bytes object plus one.

Changed in version 3.3:Also accept an integer in the range 0 to 255 as the subsequence.

bytes.removeprefix(prefix,/)
bytearray.removeprefix(prefix,/)

If the binary data starts with theprefixstring, return bytes[len(prefix):].Otherwise, return a copy of the original binary data:

>>>b'TestHook'.removeprefix(b'Test')
b'Hook'
>>>b'BaseTestCase'.removeprefix(b'Test')
b'BaseTestCase'

Theprefixmay be anybytes-like object.

Note

The bytearray version of this method doesnotoperate in place - it always produces a new object, even if no changes were made.

Added in version 3.9.

bytes.removesuffix(suffix,/)
bytearray.removesuffix(suffix,/)

If the binary data ends with thesuffixstring and thatsuffixis not empty, returnbytes[:-len(suffix)].Otherwise, return a copy of the original binary data:

>>>b'MiscTests'.removesuffix(b'Tests')
b'Misc'
>>>b'TmpDirMixin'.removesuffix(b'Tests')
b'TmpDirMixin'

Thesuffixmay be anybytes-like object.

Note

The bytearray version of this method doesnotoperate in place - it always produces a new object, even if no changes were made.

Added in version 3.9.

bytes.decode(encoding='utf-8',errors='strict')
bytearray.decode(encoding='utf-8',errors='strict')

Return the bytes decoded to astr.

encodingdefaults to'utf-8'; seeStandard Encodingsfor possible values.

errorscontrols how decoding errors are handled. If'strict'(the default), aUnicodeErrorexception is raised. Other possible values are'ignore','replace', and any other name registered viacodecs.register_error(). SeeError Handlersfor details.

For performance reasons, the value oferrorsis not checked for validity unless a decoding error actually occurs, Python Development Modeis enabled or adebug buildis used.

Note

Passing theencodingargument tostrallows decoding any bytes-like objectdirectly, without needing to make a temporary bytesorbytearrayobject.

Changed in version 3.1:Added support for keyword arguments.

Changed in version 3.9:The value of theerrorsargument is now checked inPython Development Modeand indebug mode.

bytes.endswith(suffix[,start[,end]])
bytearray.endswith(suffix[,start[,end]])

ReturnTrueif the binary data ends with the specifiedsuffix, otherwise returnFalse.suffixcan also be a tuple of suffixes to look for. With optionalstart,test beginning at that position. With optionalend,stop comparing at that position.

The suffix(es) to search for may be anybytes-like object.

bytes.find(sub[,start[,end]])
bytearray.find(sub[,start[,end]])

Return the lowest index in the data where the subsequencesubis found, such thatsubis contained in the slices[start:end].Optional argumentsstartandendare interpreted as in slice notation. Return -1ifsubis not found.

The subsequence to search for may be anybytes-like objector an integer in the range 0 to 255.

Note

Thefind()method should be used only if you need to know the position ofsub.To check ifsubis a substring or not, use the inoperator:

>>>b'Py'inb'Python'
True

Changed in version 3.3:Also accept an integer in the range 0 to 255 as the subsequence.

bytes.index(sub[,start[,end]])
bytearray.index(sub[,start[,end]])

Likefind(),but raiseValueErrorwhen the subsequence is not found.

The subsequence to search for may be anybytes-like objector an integer in the range 0 to 255.

Changed in version 3.3:Also accept an integer in the range 0 to 255 as the subsequence.

bytes.join(iterable)
bytearray.join(iterable)

Return a bytes or bytearray object which is the concatenation of the binary data sequences initerable.ATypeErrorwill be raised if there are any values initerablethat are notbytes-like objects,includingstrobjects. The separator between elements is the contents of the bytes or bytearray object providing this method.

staticbytes.maketrans(from,to)
staticbytearray.maketrans(from,to)

This static method returns a translation table usable for bytes.translate()that will map each character infrominto the character at the same position into;fromandtomust both be bytes-like objectsand have the same length.

Added in version 3.1.

bytes.partition(sep)
bytearray.partition(sep)

Split the sequence at the first occurrence ofsep,and return a 3-tuple containing the part before the separator, the separator itself or its bytearray copy, and the part after the separator. If the separator is not found, return a 3-tuple containing a copy of the original sequence, followed by two empty bytes or bytearray objects.

The separator to search for may be anybytes-like object.

bytes.replace(old,new[,count])
bytearray.replace(old,new[,count])

Return a copy of the sequence with all occurrences of subsequenceold replaced bynew.If the optional argumentcountis given, only the firstcountoccurrences are replaced.

The subsequence to search for and its replacement may be any bytes-like object.

Note

The bytearray version of this method doesnotoperate in place - it always produces a new object, even if no changes were made.

bytes.rfind(sub[,start[,end]])
bytearray.rfind(sub[,start[,end]])

Return the highest index in the sequence where the subsequencesubis found, such thatsubis contained withins[start:end].Optional argumentsstartandendare interpreted as in slice notation. Return -1on failure.

The subsequence to search for may be anybytes-like objector an integer in the range 0 to 255.

Changed in version 3.3:Also accept an integer in the range 0 to 255 as the subsequence.

bytes.rindex(sub[,start[,end]])
bytearray.rindex(sub[,start[,end]])

Likerfind()but raisesValueErrorwhen the subsequencesubis not found.

The subsequence to search for may be anybytes-like objector an integer in the range 0 to 255.

Changed in version 3.3:Also accept an integer in the range 0 to 255 as the subsequence.

bytes.rpartition(sep)
bytearray.rpartition(sep)

Split the sequence at the last occurrence ofsep,and return a 3-tuple containing the part before the separator, the separator itself or its bytearray copy, and the part after the separator. If the separator is not found, return a 3-tuple containing two empty bytes or bytearray objects, followed by a copy of the original sequence.

The separator to search for may be anybytes-like object.

bytes.startswith(prefix[,start[,end]])
bytearray.startswith(prefix[,start[,end]])

ReturnTrueif the binary data starts with the specifiedprefix, otherwise returnFalse.prefixcan also be a tuple of prefixes to look for. With optionalstart,test beginning at that position. With optionalend,stop comparing at that position.

The prefix(es) to search for may be anybytes-like object.

bytes.translate(table,/,delete=b'')
bytearray.translate(table,/,delete=b'')

Return a copy of the bytes or bytearray object where all bytes occurring in the optional argumentdeleteare removed, and the remaining bytes have been mapped through the given translation table, which must be a bytes object of length 256.

You can use thebytes.maketrans()method to create a translation table.

Set thetableargument toNonefor translations that only delete characters:

>>>b'read this short text'.translate(None,b'aeiou')
b'rd ths shrt txt'

Changed in version 3.6:deleteis now supported as a keyword argument.

The following methods on bytes and bytearray objects have default behaviours that assume the use of ASCII compatible binary formats, but can still be used with arbitrary binary data by passing appropriate arguments. Note that all of the bytearray methods in this section donotoperate in place, and instead produce new objects.

bytes.center(width[,fillbyte])
bytearray.center(width[,fillbyte])

Return a copy of the object centered in a sequence of lengthwidth. Padding is done using the specifiedfillbyte(default is an ASCII space). Forbytesobjects, the original sequence is returned if widthis less than or equal tolen(s).

Note

The bytearray version of this method doesnotoperate in place - it always produces a new object, even if no changes were made.

bytes.ljust(width[,fillbyte])
bytearray.ljust(width[,fillbyte])

Return a copy of the object left justified in a sequence of lengthwidth. Padding is done using the specifiedfillbyte(default is an ASCII space). Forbytesobjects, the original sequence is returned if widthis less than or equal tolen(s).

Note

The bytearray version of this method doesnotoperate in place - it always produces a new object, even if no changes were made.

bytes.lstrip([chars])
bytearray.lstrip([chars])

Return a copy of the sequence with specified leading bytes removed. The charsargument is a binary sequence specifying the set of byte values to be removed - the name refers to the fact this method is usually used with ASCII characters. If omitted orNone,thecharsargument defaults to removing ASCII whitespace. Thecharsargument is not a prefix; rather, all combinations of its values are stripped:

>>>b' spacious '.lstrip()
b'spacious '
>>>b' example '.lstrip(b'cmowz.')
b'example '

The binary sequence of byte values to remove may be any bytes-like object.Seeremoveprefix()for a method that will remove a single prefix string rather than all of a set of characters. For example:

>>>b'Arthur: three!'.lstrip(b'Arthur: ')
b'ee!'
>>>b'Arthur: three!'.removeprefix(b'Arthur: ')
b'three!'

Note

The bytearray version of this method doesnotoperate in place - it always produces a new object, even if no changes were made.

bytes.rjust(width[,fillbyte])
bytearray.rjust(width[,fillbyte])

Return a copy of the object right justified in a sequence of lengthwidth. Padding is done using the specifiedfillbyte(default is an ASCII space). Forbytesobjects, the original sequence is returned if widthis less than or equal tolen(s).

Note

The bytearray version of this method doesnotoperate in place - it always produces a new object, even if no changes were made.

bytes.rsplit(sep=None,maxsplit=-1)
bytearray.rsplit(sep=None,maxsplit=-1)

Split the binary sequence into subsequences of the same type, usingsep as the delimiter string. Ifmaxsplitis given, at mostmaxsplitsplits are done, therightmostones. Ifsepis not specified orNone, any subsequence consisting solely of ASCII whitespace is a separator. Except for splitting from the right,rsplit()behaves like split()which is described in detail below.

bytes.rstrip([chars])
bytearray.rstrip([chars])

Return a copy of the sequence with specified trailing bytes removed. The charsargument is a binary sequence specifying the set of byte values to be removed - the name refers to the fact this method is usually used with ASCII characters. If omitted orNone,thecharsargument defaults to removing ASCII whitespace. Thecharsargument is not a suffix; rather, all combinations of its values are stripped:

>>>b' spacious '.rstrip()
b' spacious'
>>>b'mississippi'.rstrip(b'ipz')
b'mississ'

The binary sequence of byte values to remove may be any bytes-like object.Seeremovesuffix()for a method that will remove a single suffix string rather than all of a set of characters. For example:

>>>b'Monty Python'.rstrip(b' Python')
b'M'
>>>b'Monty Python'.removesuffix(b' Python')
b'Monty'

Note

The bytearray version of this method doesnotoperate in place - it always produces a new object, even if no changes were made.

bytes.split(sep=None,maxsplit=-1)
bytearray.split(sep=None,maxsplit=-1)

Split the binary sequence into subsequences of the same type, usingsep as the delimiter string. Ifmaxsplitis given and non-negative, at most maxsplitsplits are done (thus, the list will have at mostmaxsplit+1 elements). Ifmaxsplitis not specified or is-1,then there is no limit on the number of splits (all possible splits are made).

Ifsepis given, consecutive delimiters are not grouped together and are deemed to delimit empty subsequences (for example,b'1,,2'.split(b',') returns[b'1',b'',b'2']). Thesepargument may consist of a multibyte sequence as a single delimiter. Splitting an empty sequence with a specified separator returns[b'']or[bytearray(b'')]depending on the type of object being split. Thesepargument may be any bytes-like object.

For example:

>>>b'1,2,3'.split(b',')
[b'1', b'2', b'3']
>>>b'1,2,3'.split(b',',maxsplit=1)
[b'1', b'2,3']
>>>b'1,2,,3,'.split(b',')
[b'1', b'2', b'', b'3', b'']
>>>b'1<>2<>3<4'.split(b'<>')
[b'1', b'2', b'3<4']

Ifsepis not specified or isNone,a different splitting algorithm is applied: runs of consecutive ASCII whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the sequence has leading or trailing whitespace. Consequently, splitting an empty sequence or a sequence consisting solely of ASCII whitespace without a specified separator returns[].

For example:

>>>b'1 2 3'.split()
[b'1', b'2', b'3']
>>>b'1 2 3'.split(maxsplit=1)
[b'1', b'2 3']
>>>b' 1 2 3 '.split()
[b'1', b'2', b'3']
bytes.strip([chars])
bytearray.strip([chars])

Return a copy of the sequence with specified leading and trailing bytes removed. Thecharsargument is a binary sequence specifying the set of byte values to be removed - the name refers to the fact this method is usually used with ASCII characters. If omitted orNone,thechars argument defaults to removing ASCII whitespace. Thecharsargument is not a prefix or suffix; rather, all combinations of its values are stripped:

>>>b' spacious '.strip()
b'spacious'
>>>b' example '.strip(b'cmowz.')
b'example'

The binary sequence of byte values to remove may be any bytes-like object.

Note

The bytearray version of this method doesnotoperate in place - it always produces a new object, even if no changes were made.

The following methods on bytes and bytearray objects assume the use of ASCII compatible binary formats and should not be applied to arbitrary binary data. Note that all of the bytearray methods in this section donotoperate in place, and instead produce new objects.

bytes.capitalize()
bytearray.capitalize()

Return a copy of the sequence with each byte interpreted as an ASCII character, and the first byte capitalized and the rest lowercased. Non-ASCII byte values are passed through unchanged.

Note

The bytearray version of this method doesnotoperate in place - it always produces a new object, even if no changes were made.

bytes.expandtabs(tabsize=8)
bytearray.expandtabs(tabsize=8)

Return a copy of the sequence where all ASCII tab characters are replaced by one or more ASCII spaces, depending on the current column and the given tab size. Tab positions occur everytabsizebytes (default is 8, giving tab positions at columns 0, 8, 16 and so on). To expand the sequence, the current column is set to zero and the sequence is examined byte by byte. If the byte is an ASCII tab character (b'\t'), one or more space characters are inserted in the result until the current column is equal to the next tab position. (The tab character itself is not copied.) If the current byte is an ASCII newline (b'\n') or carriage return (b'\r'), it is copied and the current column is reset to zero. Any other byte value is copied unchanged and the current column is incremented by one regardless of how the byte value is represented when printed:

>>>b'01\t012\t0123\t01234'.expandtabs()
b'01 012 0123 01234'
>>>b'01\t012\t0123\t01234'.expandtabs(4)
b'01 012 0123 01234'

Note

The bytearray version of this method doesnotoperate in place - it always produces a new object, even if no changes were made.

bytes.isalnum()
bytearray.isalnum()

ReturnTrueif all bytes in the sequence are Alpha betical ASCII characters or ASCII decimal digits and the sequence is not empty,Falseotherwise. Alphabetic ASCII characters are those byte values in the sequence b'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.ASCII decimal digits are those byte values in the sequenceb'0123456789'.

For example:

>>>b'ABCabc1'.isalnum()
True
>>>b'ABC abc1'.isalnum()
False
bytes.is Alpha()
bytearray.is Alpha()

ReturnTrueif all bytes in the sequence are Alpha betic ASCII characters and the sequence is not empty,Falseotherwise. Alphabetic ASCII characters are those byte values in the sequence b'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.

For example:

>>>b'ABCabc'.is Alpha()
True
>>>b'ABCabc1'.is Alpha()
False
bytes.isascii()
bytearray.isascii()

ReturnTrueif the sequence is empty or all bytes in the sequence are ASCII, Falseotherwise. ASCII bytes are in the range 0-0x7F.

Added in version 3.7.

bytes.isdigit()
bytearray.isdigit()

ReturnTrueif all bytes in the sequence are ASCII decimal digits and the sequence is not empty,Falseotherwise. ASCII decimal digits are those byte values in the sequenceb'0123456789'.

For example:

>>>b'1234'.isdigit()
True
>>>b'1.23'.isdigit()
False
bytes.islower()
bytearray.islower()

ReturnTrueif there is at least one lowercase ASCII character in the sequence and no uppercase ASCII characters,Falseotherwise.

For example:

>>>b'hello world'.islower()
True
>>>b'Hello world'.islower()
False

Lowercase ASCII characters are those byte values in the sequence b'abcdefghijklmnopqrstuvwxyz'.Uppercase ASCII characters are those byte values in the sequenceb'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.

bytes.isspace()
bytearray.isspace()

ReturnTrueif all bytes in the sequence are ASCII whitespace and the sequence is not empty,Falseotherwise. ASCII whitespace characters are those byte values in the sequenceb'\t\n\r\x0b\f'(space, tab, newline, carriage return, vertical tab, form feed).

bytes.istitle()
bytearray.istitle()

ReturnTrueif the sequence is ASCII titlecase and the sequence is not empty,Falseotherwise. Seebytes.title()for more details on the definition of “titlecase”.

For example:

>>>b'Hello World'.istitle()
True
>>>b'Hello world'.istitle()
False
bytes.isupper()
bytearray.isupper()

ReturnTrueif there is at least one uppercase Alpha betic ASCII character in the sequence and no lowercase ASCII characters,Falseotherwise.

For example:

>>>b'HELLO WORLD'.isupper()
True
>>>b'Hello world'.isupper()
False

Lowercase ASCII characters are those byte values in the sequence b'abcdefghijklmnopqrstuvwxyz'.Uppercase ASCII characters are those byte values in the sequenceb'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.

bytes.lower()
bytearray.lower()

Return a copy of the sequence with all the uppercase ASCII characters converted to their corresponding lowercase counterpart.

For example:

>>>b'Hello World'.lower()
b'hello world'

Lowercase ASCII characters are those byte values in the sequence b'abcdefghijklmnopqrstuvwxyz'.Uppercase ASCII characters are those byte values in the sequenceb'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.

Note

The bytearray version of this method doesnotoperate in place - it always produces a new object, even if no changes were made.

bytes.splitlines(keepends=False)
bytearray.splitlines(keepends=False)

Return a list of the lines in the binary sequence, breaking at ASCII line boundaries. This method uses theuniversal newlinesapproach to splitting lines. Line breaks are not included in the resulting list unlesskeependsis given and true.

For example:

>>>b'ab c\n\nde fg\rkl\r\n'.splitlines()
[b'ab c', b'', b'de fg', b'kl']
>>>b'ab c\n\nde fg\rkl\r\n'.splitlines(keepends=True)
[b'ab c\n', b'\n', b'de fg\r', b'kl\r\n']

Unlikesplit()when a delimiter stringsepis given, this method returns an empty list for the empty string, and a terminal line break does not result in an extra line:

>>>b"".split(b'\n'),b"Two lines\n".split(b'\n')
([b''], [b'Two lines', b''])
>>>b"".splitlines(),b"One line\n".splitlines()
([], [b'One line'])
bytes.swapcase()
bytearray.swapcase()

Return a copy of the sequence with all the lowercase ASCII characters converted to their corresponding uppercase counterpart and vice-versa.

For example:

>>>b'Hello World'.swapcase()
b'hELLO wORLD'

Lowercase ASCII characters are those byte values in the sequence b'abcdefghijklmnopqrstuvwxyz'.Uppercase ASCII characters are those byte values in the sequenceb'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.

Unlikestr.swapcase(),it is always the case that bin.swapcase().swapcase()==binfor the binary versions. Case conversions are symmetrical in ASCII, even though that is not generally true for arbitrary Unicode code points.

Note

The bytearray version of this method doesnotoperate in place - it always produces a new object, even if no changes were made.

bytes.title()
bytearray.title()

Return a titlecased version of the binary sequence where words start with an uppercase ASCII character and the remaining characters are lowercase. Uncased byte values are left unmodified.

For example:

>>>b'Hello world'.title()
b'Hello World'

Lowercase ASCII characters are those byte values in the sequence b'abcdefghijklmnopqrstuvwxyz'.Uppercase ASCII characters are those byte values in the sequenceb'ABCDEFGHIJKLMNOPQRSTUVWXYZ'. All other byte values are uncased.

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:

>>>b"they're bill's friends from the UK".title()
b "They'Re Bill'S Friends From The Uk"

A workaround for apostrophes can be constructed using regular expressions:

>>>importre
>>>deftitlecase(s):
...returnre.sub(rb"[A-Za-z]+('[A-Za-z]+)?",
...lambdamo:mo.group(0)[0:1].upper()+
...mo.group(0)[1:].lower(),
...s)
...
>>>titlecase(b"they're bill's friends.")
b "They're Bill's Friends."

Note

The bytearray version of this method doesnotoperate in place - it always produces a new object, even if no changes were made.

bytes.upper()
bytearray.upper()

Return a copy of the sequence with all the lowercase ASCII characters converted to their corresponding uppercase counterpart.

For example:

>>>b'Hello World'.upper()
b'HELLO WORLD'

Lowercase ASCII characters are those byte values in the sequence b'abcdefghijklmnopqrstuvwxyz'.Uppercase ASCII characters are those byte values in the sequenceb'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.

Note

The bytearray version of this method doesnotoperate in place - it always produces a new object, even if no changes were made.

bytes.zfill(width)
bytearray.zfill(width)

Return a copy of the sequence left filled with ASCIIb'0'digits to make a sequence of lengthwidth.A leading sign prefix (b'+'/ b'-') is handled by inserting the paddingafterthe sign character rather than before. Forbytesobjects, the original sequence is returned ifwidthis less than or equal tolen(seq).

For example:

>>>b"42".zfill(5)
b'00042'
>>>b"-42".zfill(5)
b'-0042'

Note

The bytearray version of this method doesnotoperate in place - it always produces a new object, even if no changes were made.

printf-style Bytes Formatting

Note

The formatting operations described here exhibit a variety of quirks that lead to a number of common errors (such as failing to display tuples and dictionaries correctly). If the value being printed may be a tuple or dictionary, wrap it in a tuple.

Bytes objects (bytes/bytearray) have one unique built-in operation: the%operator (modulo). This is also known as the bytesformattingorinterpolationoperator. Givenformat%values(whereformatis a bytes object),%conversion specifications informatare replaced with zero or more elements ofvalues. The effect is similar to using thesprintf()in the C language.

Ifformatrequires a single argument,valuesmay be a single non-tuple object.[5]Otherwise,valuesmust be a tuple with exactly the number of items specified by the format bytes object, 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:

  1. The'%'character, which marks the start of the specifier.

  2. Mapping key (optional), consisting of a parenthesised sequence of characters (for example,(somename)).

  3. Conversion flags (optional), which affect the result of some conversion types.

  4. Minimum field width (optional). If specified as an'*'(asterisk), the actual width is read from the next element of the tuple invalues,and the object to convert comes after the minimum field width and optional precision.

  5. Precision (optional), given as a'.'(dot) followed by the precision. If specified as'*'(an asterisk), the actual precision is read from the next element of the tuple invalues,and the value to convert comes after the precision.

  6. Length modifier (optional).

  7. Conversion type.

When the right argument is a dictionary (or other mapping type), then the formats in the bytes objectmustinclude a parenthesised mapping key into that dictionary inserted immediately after the'%'character. The mapping key selects the value to be formatted from the mapping. For example:

>>>print(b'%(language)shas%(number)03dquote types.'%
...{b'language':b"Python",b"number":2})
b'Python has 002 quote types.'

In this case no*specifiers may occur in a format (since they require a sequential parameter list).

The conversion flag characters are:

Flag

Meaning

'#'

The value conversion will use the “alternate form” (where defined below).

'0'

The conversion will be zero padded for numeric values.

'-'

The converted value is left adjusted (overrides the'0' conversion if both are given).

''

(a space) A blank should be left before a positive number (or empty string) produced by a signed conversion.

'+'

A sign character ('+'or'-') will precede the conversion (overrides a “space” flag).

A length modifier (h,l,orL) may be present, but is ignored as it is not necessary for Python – so e.g.%ldis identical to%d.

The conversion types are:

Conversion

Meaning

Notes

'd'

Signed integer decimal.

'i'

Signed integer decimal.

'o'

Signed octal value.

(1)

'u'

Obsolete type – it is identical to'd'.

(8)

'x'

Signed hexadecimal (lowercase).

(2)

'X'

Signed hexadecimal (uppercase).

(2)

'e'

Floating-point exponential format (lowercase).

(3)

'E'

Floating-point exponential format (uppercase).

(3)

'f'

Floating-point decimal format.

(3)

'F'

Floating-point decimal format.

(3)

'g'

Floating-point format. Uses lowercase exponential format if exponent is less than -4 or not less than precision, decimal format otherwise.

(4)

'G'

Floating-point format. Uses uppercase exponential format if exponent is less than -4 or not less than precision, decimal format otherwise.

(4)

'c'

Single byte (accepts integer or single byte objects).

'b'

Bytes (any object that follows the buffer protocolor has __bytes__()).

(5)

's'

's'is an alias for'b'and should only be used for Python2/3 code bases.

(6)

'a'

Bytes (converts any Python object using repr(obj).encode('ascii','backslashreplace')).

(5)

'r'

'r'is an alias for'a'and should only be used for Python2/3 code bases.

(7)

'%'

No argument is converted, results in a'%' character in the result.

Notes:

  1. The alternate form causes a leading octal specifier ('0o') to be inserted before the first digit.

  2. The alternate form causes a leading'0x'or'0X'(depending on whether the'x'or'X'format was used) to be inserted before the first digit.

  3. 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.

  4. 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.

  5. If precision isN,the output is truncated toNcharacters.

  6. b'%s'is deprecated, but will not be removed during the 3.x series.

  7. b'%r'is deprecated, but will not be removed during the 3.x series.

  8. SeePEP 237.

Note

The bytearray version of this method doesnotoperate in place - it always produces a new object, even if no changes were made.

See also

PEP 461- Adding % formatting to bytes and bytearray

Added in version 3.5.

Memory Views

memoryviewobjects allow Python code to access the internal data of an object that supports thebuffer protocolwithout copying.

classmemoryview(object)

Create amemoryviewthat referencesobject.objectmust support the buffer protocol. Built-in objects that support the buffer protocol includebytesandbytearray.

Amemoryviewhas the notion of anelement,which is the atomic memory unit handled by the originatingobject.For many simple types such asbytesandbytearray,an element is a single byte, but other types such asarray.arraymay have bigger elements.

len(view)is equal to the length oftolist,which is the nested list representation of the view. Ifview.ndim=1, this is equal to the number of elements in the view.

Changed in version 3.12:Ifview.ndim==0,len(view)now raisesTypeErrorinstead of returning 1.

Theitemsizeattribute will give you the number of bytes in a single element.

Amemoryviewsupports slicing and inde xing to expose its data. One-dimensional slicing will result in a subview:

>>>v=memoryview(b'abcefg')
>>>v[1]
98
>>>v[-1]
103
>>>v[1:4]
<memory at 0x7f3ddc9f4350>
>>>bytes(v[1:4])
b'bce'

Ifformatis one of the native format specifiers from thestructmodule, inde xing with an integer or a tuple of integers is also supported and returns a singleelementwith the correct type. One-dimensional memoryviews can be indexed with an integer or a one-integer tuple. Multi-dimensional memoryviews can be indexed with tuples of exactlyndimintegers wherendimis the number of dimensions. Zero-dimensional memoryviews can be indexed with the empty tuple.

Here is an example with a non-byte format:

>>>importarray
>>>a=array.array('l',[-11111111,22222222,-33333333,44444444])
>>>m=memoryview(a)
>>>m[0]
-11111111
>>>m[-1]
44444444
>>>m[::2].tolist()
[-11111111, -33333333]

If the underlying object is writable, the memoryview supports one-dimensional slice assignment. Resizing is not allowed:

>>>data=bytearray(b'abcefg')
>>>v=memoryview(data)
>>>v.readonly
False
>>>v[0]=ord(b'z')
>>>data
bytearray(b'zbcefg')
>>>v[1:4]=b'123'
>>>data
bytearray(b'z123fg')
>>>v[2:3]=b'spam'
Traceback (most recent call last):
File"<stdin>",line1,in<module>
ValueError:memoryview assignment: lvalue and rvalue have different structures
>>>v[2:6]=b'spam'
>>>data
bytearray(b'z1spam')

One-dimensional memoryviews ofhashable(read-only) types with formats ‘B’, ‘b’ or ‘c’ are also hashable. The hash is defined as hash(m)==hash(m.tobytes()):

>>>v=memoryview(b'abcefg')
>>>hash(v)==hash(b'abcefg')
True
>>>hash(v[2:4])==hash(b'ce')
True
>>>hash(v[::-2])==hash(b'abcefg'[::-2])
True

Changed in version 3.3:One-dimensional memoryviews can now be sliced. One-dimensional memoryviews with formats ‘B’, ‘b’ or ‘c’ are nowhashable.

Changed in version 3.4:memoryview is now registered automatically with collections.abc.Sequence

Changed in version 3.5:memoryviews can now be indexed with tuple of integers.

memoryviewhas several methods:

__eq__(exporter)

A memoryview and aPEP 3118exporter are equal if their shapes are equivalent and if all corresponding values are equal when the operands’ respective format codes are interpreted usingstructsyntax.

For the subset ofstructformat strings currently supported by tolist(),vandware equal ifv.tolist()==w.tolist():

>>>importarray
>>>a=array.array('I',[1,2,3,4,5])
>>>b=array.array('d',[1.0,2.0,3.0,4.0,5.0])
>>>c=array.array('b',[5,3,1])
>>>x=memoryview(a)
>>>y=memoryview(b)
>>>x==a==y==b
True
>>>x.tolist()==a.tolist()==y.tolist()==b.tolist()
True
>>>z=y[::-2]
>>>z==c
True
>>>z.tolist()==c.tolist()
True

If either format string is not supported by thestructmodule, then the objects will always compare as unequal (even if the format strings and buffer contents are identical):

>>>fromctypesimportBigEndianStructure,c_long
>>>classBEPoint(BigEndianStructure):
..._fields_=[("x",c_long),("y",c_long)]
...
>>>point=BEPoint(100,200)
>>>a=memoryview(point)
>>>b=memoryview(point)
>>>a==point
False
>>>a==b
False

Note that, as with floating-point numbers,viswdoesnotimply v==wfor memoryview objects.

Changed in version 3.3:Previous versions compared the raw memory disregarding the item format and the logical array structure.

tobytes(order='C')

Return the data in the buffer as a bytestring. This is equivalent to calling thebytesconstructor on the memoryview.

>>>m=memoryview(b"abc")
>>>m.tobytes()
b'abc'
>>>bytes(m)
b'abc'

For non-contiguous arrays the result is equal to the flattened list representation with all elements converted to bytes.tobytes() supports all format strings, including those that are not in structmodule syntax.

Added in version 3.8:ordercan be {‘C’, ‘F’, ‘A’}. Whenorderis ‘C’ or ‘F’, the data of the original array is converted to C or Fortran order. For contiguous views, ‘A’ returns an exact copy of the physical memory. In particular, in-memory Fortran order is preserved. For non-contiguous views, the data is converted to C first.order=Noneis the same asorder=’C’.

hex([sep[,bytes_per_sep]])

Return a string object containing two hexadecimal digits for each byte in the buffer.

>>>m=memoryview(b"abc")
>>>m.hex()
'616263'

Added in version 3.5.

Changed in version 3.8:Similar tobytes.hex(),memoryview.hex()now supports optionalsepandbytes_per_sepparameters to insert separators between bytes in the hex output.

tolist()

Return the data in the buffer as a list of elements.

>>>memoryview(b'abc').tolist()
[97, 98, 99]
>>>importarray
>>>a=array.array('d',[1.1,2.2,3.3])
>>>m=memoryview(a)
>>>m.tolist()
[1.1, 2.2, 3.3]

Changed in version 3.3:tolist()now supports all single character native formats in structmodule syntax as well as multi-dimensional representations.

toreadonly()

Return a readonly version of the memoryview object. The original memoryview object is unchanged.

>>>m=memoryview(bytearray(b'abc'))
>>>mm=m.toreadonly()
>>>mm.tolist()
[97, 98, 99]
>>>mm[0]=42
Traceback (most recent call last):
File"<stdin>",line1,in<module>
TypeError:cannot modify read-only memory
>>>m[0]=43
>>>mm.tolist()
[43, 98, 99]

Added in version 3.8.

release()

Release the underlying buffer exposed by the memoryview object. Many objects take special actions when a view is held on them (for example, abytearraywould temporarily forbid resizing); therefore, calling release() is handy to remove these restrictions (and free any dangling resources) as soon as possible.

After this method has been called, any further operation on the view raises aValueError(exceptrelease()itself which can be called multiple times):

>>>m=memoryview(b'abc')
>>>m.release()
>>>m[0]
Traceback (most recent call last):
File"<stdin>",line1,in<module>
ValueError:operation forbidden on released memoryview object

The context management protocol can be used for a similar effect, using thewithstatement:

>>>withmemoryview(b'abc')asm:
...m[0]
...
97
>>>m[0]
Traceback (most recent call last):
File"<stdin>",line1,in<module>
ValueError:operation forbidden on released memoryview object

Added in version 3.2.

cast(format[,shape])

Cast a memoryview to a new format or shape.shapedefaults to [byte_length//new_itemsize],which means that the result view will be one-dimensional. The return value is a new memoryview, but the buffer itself is not copied. Supported casts are 1D -> C-contiguous and C-contiguous -> 1D.

The destination format is restricted to a single element native format in structsyntax. One of the formats must be a byte format (‘B’, ‘b’ or ‘c’). The byte length of the result must be the same as the original length. Note that all byte lengths may depend on the operating system.

Cast 1D/long to 1D/unsigned bytes:

>>>importarray
>>>a=array.array('l',[1,2,3])
>>>x=memoryview(a)
>>>x.format
'l'
>>>x.itemsize
8
>>>len(x)
3
>>>x.nbytes
24
>>>y=x.cast('B')
>>>y.format
'B'
>>>y.itemsize
1
>>>len(y)
24
>>>y.nbytes
24

Cast 1D/unsigned bytes to 1D/char:

>>>b=bytearray(b'zyz')
>>>x=memoryview(b)
>>>x[0]=b'a'
Traceback (most recent call last):
...
TypeError:memoryview: invalid type for format 'B'
>>>y=x.cast('c')
>>>y[0]=b'a'
>>>b
bytearray(b'ayz')

Cast 1D/bytes to 3D/ints to 1D/signed char:

>>>importstruct
>>>buf=struct.pack("i"*12,*list(range(12)))
>>>x=memoryview(buf)
>>>y=x.cast('i',shape=[2,2,3])
>>>y.tolist()
[[[0, 1, 2], [3, 4, 5]], [[6, 7, 8], [9, 10, 11]]]
>>>y.format
'i'
>>>y.itemsize
4
>>>len(y)
2
>>>y.nbytes
48
>>>z=y.cast('b')
>>>z.format
'b'
>>>z.itemsize
1
>>>len(z)
48
>>>z.nbytes
48

Cast 1D/unsigned long to 2D/unsigned long:

>>>buf=struct.pack("L"*6,*list(range(6)))
>>>x=memoryview(buf)
>>>y=x.cast('L',shape=[2,3])
>>>len(y)
2
>>>y.nbytes
48
>>>y.tolist()
[[0, 1, 2], [3, 4, 5]]

Added in version 3.3.

Changed in version 3.5:The source format is no longer restricted when casting to a byte view.

There are also several readonly attributes available:

obj

The underlying object of the memoryview:

>>>b=bytearray(b'xyz')
>>>m=memoryview(b)
>>>m.objisb
True

Added in version 3.3.

nbytes

nbytes==product(shape)*itemsize==len(m.tobytes()).This is the amount of space in bytes that the array would use in a contiguous representation. It is not necessarily equal tolen(m):

>>>importarray
>>>a=array.array('i',[1,2,3,4,5])
>>>m=memoryview(a)
>>>len(m)
5
>>>m.nbytes
20
>>>y=m[::2]
>>>len(y)
3
>>>y.nbytes
12
>>>len(y.tobytes())
12

Multi-dimensional arrays:

>>>importstruct
>>>buf=struct.pack("d"*12,*[1.5*xforxinrange(12)])
>>>x=memoryview(buf)
>>>y=x.cast('d',shape=[3,4])
>>>y.tolist()
[[0.0, 1.5, 3.0, 4.5], [6.0, 7.5, 9.0, 10.5], [12.0, 13.5, 15.0, 16.5]]
>>>len(y)
3
>>>y.nbytes
96

Added in version 3.3.

readonly

A bool indicating whether the memory is read only.

format

A string containing the format (instructmodule style) for each element in the view. A memoryview can be created from exporters with arbitrary format strings, but some methods (e.g.tolist()) are restricted to native single element formats.

Changed in version 3.3:format'B'is now handled according to the struct module syntax. This means thatmemoryview(b'abc')[0]==b'abc'[0]==97.

itemsize

The size in bytes of each element of the memoryview:

>>>importarray,struct
>>>m=memoryview(array.array('H',[32000,32001,32002]))
>>>m.itemsize
2
>>>m[0]
32000
>>>struct.calcsize('H')==m.itemsize
True
ndim

An integer indicating how many dimensions of a multi-dimensional array the memory represents.

shape

A tuple of integers the length ofndimgiving the shape of the memory as an N-dimensional array.

Changed in version 3.3:An empty tuple instead ofNonewhen ndim = 0.

strides

A tuple of integers the length ofndimgiving the size in bytes to access each element for each dimension of the array.

Changed in version 3.3:An empty tuple instead ofNonewhen ndim = 0.

suboffsets

Used internally for PIL-style arrays. The value is informational only.

c_contiguous

A bool indicating whether the memory is C-contiguous.

Added in version 3.3.

f_contiguous

A bool indicating whether the memory is Fortrancontiguous.

Added in version 3.3.

contiguous

A bool indicating whether the memory iscontiguous.

Added in version 3.3.

Set Types —set,frozenset

Asetobject is an unordered collection of distincthashableobjects. 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-indict,list, andtupleclasses, and thecollectionsmodule.)

Like other collections, sets supportxinset,len(set),andforxin set.Being an unordered collection, sets do not record element position or order of insertion. Accordingly, sets do not support inde xing, slicing, or other sequence-like behavior.

There are currently two built-in set types,setandfrozenset. Thesettype is mutable — the contents can be changed using methods likeadd()andremove().Since it is mutable, it has no hash value and cannot be used as either a dictionary key or as an element of another set. Thefrozensettype is immutable andhashable— its contents cannot be altered after it is created; it can therefore be used as a dictionary key or as an element of another set.

Non-empty sets (not frozensets) can be created by placing a comma-separated list of elements within braces, for example:{'jack','sjoerd'},in addition to the setconstructor.

The constructors for both classes work the same:

classset([iterable])
classfrozenset([iterable])

Return a new set or frozenset object whose elements are taken from iterable.The elements of a set must behashable.To represent sets of sets, the inner sets must befrozenset objects. Ifiterableis not specified, a new empty set is returned.

Sets can be created by several means:

  • Use a comma-separated list of elements within braces:{'jack','sjoerd'}

  • Use a set comprehension:{cforcin'abracadabra'ifcnotin'abc'}

  • Use the type constructor:set(),set('foobar'),set(['a','b','foo'])

Instances ofsetandfrozensetprovide the following operations:

len(s)

Return the number of elements in sets(cardinality ofs).

xins

Testxfor membership ins.

xnotins

Testxfor non-membership ins.

isdisjoint(other)

ReturnTrueif the set has no elements in common withother.Sets are disjoint if and only if their intersection is the empty set.

issubset(other)
set<=other

Test whether every element in the set is inother.

set<other

Test whether the set is a proper subset ofother,that is, set<=otherandset!=other.

issuperset(other)
set>=other

Test whether every element inotheris in the set.

set>other

Test whether the set is a proper superset ofother,that is,set>= otherandset!=other.

union(*others)
set|other|...

Return a new set with elements from the set and all others.

intersection(*others)
set&other&...

Return a new set with elements common to the set and all others.

difference(*others)
set-other-...

Return a new set with elements in the set that are not in the others.

symmetric_difference(other)
set^other

Return a new set with elements in either the set orotherbut not both.

copy()

Return a shallow copy of the set.

Note, the non-operator versions ofunion(),intersection(), difference(),symmetric_difference(),issubset(),and issuperset()methods will accept any iterable as an argument. In contrast, their operator based counterparts require their arguments to be sets. This precludes error-prone constructions likeset('abc')&'cbs' in favor of the more readableset('abc').intersection('cbs').

Bothsetandfrozensetsupport set to set comparisons. Two sets are equal if and only if every element of each set is contained in the other (each is a subset of the other). A set is less than another set if and only if the first set is a proper subset of the second set (is a subset, but is not equal). A set is greater than another set if and only if the first set is a proper superset of the second set (is a superset, but is not equal).

Instances ofsetare compared to instances offrozenset based on their members. For example,set('abc')==frozenset('abc') returnsTrueand so doesset('abc')inset([frozenset('abc')]).

The subset and equality comparisons do not generalize to a total ordering function. For example, any two nonempty disjoint sets are not equal and are not subsets of each other, soallof the following returnFalse:a<b, a==b,ora>b.

Since sets only define partial ordering (subset relationships), the output of thelist.sort()method is undefined for lists of sets.

Set elements, like dictionary keys, must behashable.

Binary operations that mixsetinstances withfrozenset return the type of the first operand. For example:frozenset('ab')| set('bc')returns an instance offrozenset.

The following table lists operations available forsetthat do not apply to immutable instances offrozenset:

update(*others)
set|=other|...

Update the set, adding elements from all others.

intersection_update(*others)
set&=other&...

Update the set, keeping only elements found in it and all others.

difference_update(*others)
set-=other|...

Update the set, removing elements found in others.

symmetric_difference_update(other)
set^=other

Update the set, keeping only elements found in either set, but not in both.

add(elem)

Add elementelemto the set.

remove(elem)

Remove elementelemfrom the set. RaisesKeyErrorifelemis not contained in the set.

discard(elem)

Remove elementelemfrom the set if it is present.

pop()

Remove and return an arbitrary element from the set. Raises KeyErrorif the set is empty.

clear()

Remove all elements from the set.

Note, the non-operator versions of theupdate(), intersection_update(),difference_update(),and symmetric_difference_update()methods will accept any iterable as an argument.

Note, theelemargument to the__contains__(), remove(),and discard()methods may be a set. To support searching for an equivalent frozenset, a temporary one is created fromelem.

Mapping Types —dict

Amappingobject mapshashablevalues to arbitrary objects. Mappings are mutable objects. There is currently only one standard mapping type, thedictionary.(For other containers see the built-in list,set,andtupleclasses, and the collectionsmodule.)

A dictionary’s keys arealmostarbitrary 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. Values that compare equal (such as1,1.0,andTrue) can be used interchangeably to index the same dictionary entry.

classdict(**kwargs)
classdict(mapping,**kwargs)
classdict(iterable,**kwargs)

Return a new dictionary initialized from an optional positional argument and a possibly empty set of keyword arguments.

Dictionaries can be created by several means:

  • Use a comma-separated list ofkey:valuepairs within braces: {'jack':4098,'sjoerd':4127}or{4098:'jack',4127:'sjoerd'}

  • Use a dict comprehension:{},{x:x**2forxinrange(10)}

  • Use the type constructor:dict(), dict([('foo',100),('bar',200)]),dict(foo=100,bar=200)

If no positional argument is given, an empty dictionary is created. If a positional argument is given and it defines akeys()method, a dictionary is created by calling__getitem__()on the argument with each returned key from the method. Otherwise, the positional argument must be an iterableobject. Each item in the iterable must itself be an iterable with exactly two elements. The first element of each item becomes a key in the new dictionary, and the second element 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 { "one":1,"two":2,"three":3}:

>>>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})
>>>f=dict({'one':1,'three':3},two=2)
>>>a==b==c==d==e==f
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.

These are the operations that dictionaries support (and therefore, custom mapping types should support too):

list(d)

Return a list of all the keys used in the dictionaryd.

len(d)

Return the number of items in the dictionaryd.

d[key]

Return the item ofdwith keykey.Raises aKeyErrorifkeyis not in the map.

If a subclass of dict defines a method__missing__()andkey is not present, thed[key]operation calls that method with the keykey as argument. Thed[key]operation then returns or raises whatever is returned or raised by the__missing__(key)call. No other operations or methods invoke__missing__().If __missing__()is not defined,KeyErroris raised. __missing__()must be a method; it cannot be an instance variable:

>>>classCounter(dict):
...def__missing__(self,key):
...return0
...
>>>c=Counter()
>>>c['red']
0
>>>c['red']+=1
>>>c['red']
1

The example above shows part of the implementation of collections.Counter.A different__missing__method is used bycollections.defaultdict.

d[key]=value

Setd[key]tovalue.

deld[key]

Removed[key]fromd.Raises aKeyErrorifkeyis not in the map.

keyind

ReturnTrueifdhas a keykey,elseFalse.

keynotind

Equivalent tonotkeyind.

iter(d)

Return an iterator over the keys of the dictionary. This is a shortcut foriter(d.keys()).

clear()

Remove all items from the dictionary.

copy()

Return a shallow copy of the dictionary.

classmethodfromkeys(iterable,value=None,/)

Create a new dictionary with keys fromiterableand values set tovalue.

fromkeys()is a class method that returns a new dictionary.value defaults toNone.All of the values refer to just a single instance, so it generally doesn’t make sense forvalueto be a mutable object such as an empty list. To get distinct values, use adict comprehensioninstead.

get(key,default=None)

Return the value forkeyifkeyis in the dictionary, elsedefault. Ifdefaultis not given, it defaults toNone,so that this method never raises aKeyError.

items()

Return a new view of the dictionary’s items ((key,value)pairs). See thedocumentation of view objects.

keys()

Return a new view of the dictionary’s keys. See thedocumentation of view objects.

pop(key[,default])

Ifkeyis in the dictionary, remove it and return its value, else return default.Ifdefaultis not given andkeyis not in the dictionary, aKeyErroris raised.

popitem()

Remove and return a(key,value)pair from the dictionary. Pairs are returned inLIFOorder.

popitem()is useful to destructively iterate over a dictionary, as often used in set algorithms. If the dictionary is empty, calling popitem()raises aKeyError.

Changed in version 3.7:LIFO order is now guaranteed. In prior versions,popitem()would return an arbitrary key/value pair.

reversed(d)

Return a reverse iterator over the keys of the dictionary. This is a shortcut forreversed(d.keys()).

Added in version 3.8.

setdefault(key,default=None)

Ifkeyis in the dictionary, return its value. If not, insertkey with a value ofdefaultand returndefault.defaultdefaults to None.

update([other])

Update the dictionary with the key/value pairs fromother,overwriting existing keys. ReturnNone.

update()accepts either another object with akeys()method (in which case__getitem__()is called with every key returned from the method) or an iterable of key/value pairs (as tuples or other iterables of length two). If keyword arguments are specified, the dictionary is then updated with those key/value pairs:d.update(red=1,blue=2).

values()

Return a new view of the dictionary’s values. See the documentation of view objects.

An equality comparison between onedict.values()view and another will always returnFalse.This also applies when comparing dict.values()to itself:

>>>d={'a':1}
>>>d.values()==d.values()
False
d|other

Create a new dictionary with the merged keys and values ofdand other,which must both be dictionaries. The values ofothertake priority whendandothershare keys.

Added in version 3.9.

d|=other

Update the dictionarydwith keys and values fromother,which may be either amappingor aniterableof key/value pairs. The values ofothertake priority whendandothershare keys.

Added in version 3.9.

Dictionaries compare equal if and only if they have the same(key, value)pairs (regardless of ordering). Order comparisons (‘<’, ‘<=’, ‘>=’, ‘>’) raise TypeError.

Dictionaries preserve insertion order. Note that updating a key does not affect the order. Keys added after deletion are inserted at the end.

>>>d={"one":1,"two":2,"three":3,"four":4}
>>>d
{'one': 1, 'two': 2, 'three': 3, 'four': 4}
>>>list(d)
['one', 'two', 'three', 'four']
>>>list(d.values())
[1, 2, 3, 4]
>>>d["one"]=42
>>>d
{'one': 42, 'two': 2, 'three': 3, 'four': 4}
>>>deld["two"]
>>>d["two"]=None
>>>d
{'one': 42, 'three': 3, 'four': 4, 'two': None}

Changed in version 3.7:Dictionary order is guaranteed to be insertion order. This behavior was an implementation detail of CPython from 3.6.

Dictionaries and dictionary views are reversible.

>>>d={"one":1,"two":2,"three":3,"four":4}
>>>d
{'one': 1, 'two': 2, 'three': 3, 'four': 4}
>>>list(reversed(d))
['four', 'three', 'two', 'one']
>>>list(reversed(d.values()))
[4, 3, 2, 1]
>>>list(reversed(d.items()))
[('four', 4), ('three', 3), ('two', 2), ('one', 1)]

Changed in version 3.8:Dictionaries are now reversible.

See also

types.MappingProxyTypecan be used to create a read-only view of adict.

Dictionary view objects

The objects returned bydict.keys(),dict.values()and dict.items()areview objects.They provide a dynamic view on the dictionary’s entries, which means that when the dictionary changes, the view reflects these changes.

Dictionary views can be iterated over to yield their respective data, and support membership tests:

len(dictview)

Return the number of entries in the dictionary.

iter(dictview)

Return an iterator over the keys, values or items (represented as tuples of (key,value)) in the dictionary.

Keys and values are iterated over in insertion order. This allows the creation of(value,key)pairs usingzip():pairs=zip(d.values(),d.keys()).Another way to create the same list ispairs=[(v,k)for(k,v)ind.items()].

Iterating views while adding or deleting entries in the dictionary may raise aRuntimeErroror fail to iterate over all entries.

Changed in version 3.7:Dictionary order is guaranteed to be insertion order.

xindictview

ReturnTrueifxis in the underlying dictionary’s keys, values or items (in the latter case,xshould be a(key,value)tuple).

reversed(dictview)

Return a reverse iterator over the keys, values or items of the dictionary. The view will be iterated in reverse order of the insertion.

Changed in version 3.8:Dictionary views are now reversible.

dictview.mapping

Return atypes.MappingProxyTypethat wraps the original dictionary to which the view refers.

Added in version 3.10.

Keys views are set-like since their entries are unique andhashable. Items views also have set-like operations since the (key, value) pairs are unique and the keys are hashable. If all values in an items view are hashable as well, then the items view can interoperate with other sets. (Values views are not treated as set-like since the entries are generally not unique.) For set-like views, all of the operations defined for the abstract base classcollections.abc.Setare available (for example,==,<,or^). While using set operators, set-like views accept any iterable as the other operand, unlike sets which only accept sets as the input.

An example of dictionary view usage:

>>>dishes={'eggs':2,'sausage':1,'bacon':1,'spam':500}
>>>keys=dishes.keys()
>>>values=dishes.values()

>>># iteration
>>>n=0
>>>forvalinvalues:
...n+=val
...
>>>print(n)
504

>>># keys and values are iterated over in the same order (insertion order)
>>>list(keys)
['eggs', 'sausage', 'bacon', 'spam']
>>>list(values)
[2, 1, 1, 500]

>>># view objects are dynamic and reflect dict changes
>>>deldishes['eggs']
>>>deldishes['sausage']
>>>list(keys)
['bacon', 'spam']

>>># set operations
>>>keys&{'eggs','bacon','salad'}
{'bacon'}
>>>keys^{'sausage','juice'}=={'juice','sausage','bacon','spam'}
True
>>>keys|['juice','juice','juice']=={'bacon','spam','juice'}
True

>>># get back a read-only proxy for the original dictionary
>>>values.mapping
mappingproxy({'bacon': 1, 'spam': 500})
>>>values.mapping['spam']
500

Context Manager Types

Python’swithstatement supports the concept of a runtime context defined by a context manager. This is implemented using a pair of methods that allow user-defined classes to define a runtime context that is entered before the statement body is executed and exited when the statement ends:

contextmanager.__enter__()

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 theasclause ofwithstatements using this context manager.

An example of a context manager that returns itself is afile object. File objects return themselves from __enter__() to allowopen()to be used as the context expression in awithstatement.

An example of a context manager that returns a related object is the one returned bydecimal.localcontext().These managers set the active decimal context to a copy of the original decimal context and then return the copy. This allows changes to be made to the current decimal context in the body of thewithstatement without affecting code outside the withstatement.

contextmanager.__exit__(exc_type,exc_val,exc_tb)

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 thewithstatement, the arguments contain the exception type, value and traceback information. Otherwise, all three arguments areNone.

Returning a true value from this method will cause thewithstatement to suppress the exception and continue execution with the statement immediately following thewithstatement. Otherwise the exception continues propagating after this method has finished executing. Exceptions that occur during execution of this method will replace any exception that occurred in the body of thewithstatement.

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 to easily detect whether or not an__exit__() method has actually failed.

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 contextlibmodule for some examples.

Python’sgenerators and thecontextlib.contextmanagerdecorator provide a convenient way to implement these protocols. If a generator function is decorated with thecontextlib.contextmanagerdecorator, it will return a context manager implementing the necessary__enter__()and __exit__()methods, rather than the iterator produced by an undecorated generator function.

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.

Type Annotation Types —Generic Alias,Union

The core built-in types fortype annotationsare Generic AliasandUnion.

Generic Alias Type

GenericAliasobjects are generally created by subscriptinga class. They are most often used with container classes,such aslistor dict.For example,list[int]is aGenericAliasobject created by subscripting thelistclass with the argumentint. GenericAliasobjects are intended primarily for use with type annotations.

Note

It is generally only possible to subscript a class if the class implements the special method__class_getitem__().

AGenericAliasobject acts as a proxy for ageneric type, implementingparameterized generics.

For a container class, the argument(s) supplied to asubscriptionof the class may indicate the type(s) of the elements an object contains. For example, set[bytes]can be used in type annotations to signify asetin which all the elements are of typebytes.

For a class which defines__class_getitem__()but is not a container, the argument(s) supplied to a subscription of the class will often indicate the return type(s) of one or more methods defined on an object. For example,regularexpressionscan be used on both thestrdata type and thebytesdata type:

  • Ifx=re.search('foo','foo'),xwill be a re.Matchobject where the return values of x.group(0)andx[0]will both be of typestr.We can represent this kind of object in type annotations with theGenericAlias re.Match[str].

  • Ify=re.search(b'bar',b'bar'),(note thebforbytes), ywill also be an instance ofre.Match,but the return values ofy.group(0)andy[0]will both be of type bytes.In type annotations, we would represent this variety ofre.Matchobjects withre.Match[bytes].

GenericAliasobjects are instances of the class types.GenericAlias,which can also be used to createGenericAlias objects directly.

T[X,Y,...]

Creates aGenericAliasrepresenting a typeTparameterized by types X,Y,and more depending on theTused. For example, a function expecting alistcontaining floatelements:

defaverage(values:list[float])->float:
returnsum(values)/len(values)

Another example formappingobjects, using adict,which is a generic type expecting two type parameters representing the key type and the value type. In this example, the function expects adictwith keys of typestrand values of typeint:

defsend_post_request(url:str,body:dict[str,int])->None:
...

The builtin functionsisinstance()andissubclass()do not accept GenericAliastypes for their second argument:

>>>isinstance([1,2],list[str])
Traceback (most recent call last):
File"<stdin>",line1,in<module>
TypeError:isinstance() argument 2 cannot be a parameterized generic

The Python runtime does not enforcetype annotations. This extends to generic types and their type parameters. When creating a container object from aGenericAlias,the elements in the container are not checked against their type. For example, the following code is discouraged, but will run without errors:

>>>t=list[str]
>>>t([1,2,3])
[1, 2, 3]

Furthermore, parameterized generics erase type parameters during object creation:

>>>t=list[str]
>>>type(t)
<class 'types.GenericAlias'>

>>>l=t()
>>>type(l)
<class 'list'>

Callingrepr()orstr()on a generic shows the parameterized type:

>>>repr(list[int])
'list[int]'

>>>str(list[int])
'list[int]'

The__getitem__()method of generic containers will raise an exception to disallow mistakes likedict[str][str]:

>>>dict[str][str]
Traceback (most recent call last):
...
TypeError:dict[str] is not a generic class

However, such expressions are valid whentype variablesare used. The index must have as many elements as there are type variable items in theGenericAliasobject’s__args__.

>>>fromtypingimportTypeVar
>>>Y=TypeVar('Y')
>>>dict[str,Y][int]
dict[str, int]

Standard Generic Classes

The following standard library classes support parameterized generics. This list is non-exhaustive.

Special Attributes ofGenericAliasobjects

All parameterized generics implement special read-only attributes.

genericalias.__origin__

This attribute points at the non-parameterized generic class:

>>>list[int].__origin__
<class 'list'>
genericalias.__args__

This attribute is atuple(possibly of length 1) of generic types passed to the original__class_getitem__()of the generic class:

>>>dict[str,list[int]].__args__
(<class 'str'>, list[int])
genericalias.__parameters__

This attribute is a lazily computed tuple (possibly empty) of unique type variables found in__args__:

>>>fromtypingimportTypeVar

>>>T=TypeVar('T')
>>>list[T].__parameters__
(~T,)

Note

AGenericAliasobject withtyping.ParamSpecparameters may not have correct__parameters__after substitution because typing.ParamSpecis intended primarily for static type checking.

genericalias.__unpacked__

A boolean that is true if the alias has been unpacked using the *operator (seeTypeVarTuple).

Added in version 3.11.

See also

PEP 484- Type Hints

Introducing Python’s framework for type annotations.

PEP 585- Type Hinting Generics In Standard Collections

Introducing the ability to natively parameterize standard-library classes, provided they implement the special class method __class_getitem__().

Generics,user-defined genericsandtyping.Generic

Documentation on how to implement generic classes that can be parameterized at runtime and understood by static type-checkers.

Added in version 3.9.

Union Type

A union object holds the value of the|(bitwise or) operation on multipletype objects.These types are intended primarily fortype annotations.The union type expression enables cleaner type hinting syntax compared totyping.Union.

X|Y|...

Defines a union object which holds typesX,Y,and so forth.X|Y means either X or Y. It is equivalent totyping.Union[X,Y]. For example, the following function expects an argument of type intorfloat:

defsquare(number:int|float)->int|float:
returnnumber**2

Note

The|operand cannot be used at runtime to define unions where one or more members is a forward reference. For example,int|"Foo",where "Foo"is a reference to a class not yet defined, will fail at runtime. For unions which include forward references, present the whole expression as a string, e.g."int|Foo ".

union_object==other

Union objects can be tested for equality with other union objects. Details:

  • Unions of unions are flattened:

    (int|str)|float==int|str|float
    
  • Redundant types are removed:

    int|str|int==int|str
    
  • When comparing unions, the order is ignored:

    int|str==str|int
    
  • It is compatible withtyping.Union:

    int|str==typing.Union[int,str]
    
  • Optional types can be spelled as a union withNone:

    str|None==typing.Optional[str]
    
isinstance(obj,union_object)
issubclass(obj,union_object)

Calls toisinstance()andissubclass()are also supported with a union object:

>>>isinstance("",int|str)
True

However,parameterized genericsin union objects cannot be checked:

>>>isinstance(1,int|list[int])# short-circuit evaluation
True
>>>isinstance([1],int|list[int])
Traceback (most recent call last):
...
TypeError:isinstance() argument 2 cannot be a parameterized generic

The user-exposed type for the union object can be accessed from types.UnionTypeand used forisinstance()checks. An object cannot be instantiated from the type:

>>>importtypes
>>>isinstance(int|str,types.UnionType)
True
>>>types.UnionType()
Traceback (most recent call last):
File"<stdin>",line1,in<module>
TypeError:cannot create 'types.UnionType' instances

Note

The__or__()method for type objects was added to support the syntax X|Y.If a metaclass implements__or__(),the Union may override it:

>>>classM(type):
...def__or__(self,other):
...return"Hello"
...
>>>classC(metaclass=M):
...pass
...
>>>C|int
'Hello'
>>>int|C
int | C

See also

PEP 604– PEP proposing theX|Ysyntax and the Union type.

Added in version 3.10.

Other Built-in Types

The interpreter supports several other kinds of objects. Most of these support only one or two operations.

Modules

The only special operation on a module is attribute access:m.name,where mis a module andnameaccesses a name defined inm’s symbol table. Module attributes can be assigned to. (Note that theimport statement is not, strictly speaking, an operation on a module object;import foodoes not require a module object namedfooto exist, rather it requires an (external)definitionfor a module namedfoosomewhere.)

A special attribute of every module is__dict__.This is the dictionary containing the module’s symbol table. Modifying this dictionary will actually change the module’s symbol table, but direct assignment to the __dict__attribute is not possible (you can write m.__dict__['a']=1,which definesm.ato be1,but you can’t write m.__dict__={}). Modifying__dict__directly is not recommended.

Modules built into the interpreter are written like this:<module'sys' (built-in)>.If loaded from a file, they are written as<module'os'from '/usr/local/lib/ Python X.Y/os.pyc'>.

Classes and Class Instances

SeeObjects, values and typesandClass definitionsfor these.

Functions

Function objects are created by function definitions. The only operation on a function object is to call it:func(argument-list).

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.

SeeFunction definitionsfor more information.

Methods

Methods are functions that are called using the attribute notation. There are two flavors:built-in methods(such asappend() on lists) andclass instance method. Built-in methods are described with the types that support them.

If you access a method (a function defined in a class namespace) through an instance, you get a special object: abound method(also called instance method) object. When called, it will add theselfargument to the argument list. Bound methods have two special read-only attributes: m.__self__is the object on which the method operates, andm.__func__is the function implementing the method. Callingm(arg-1,arg-2,...,arg-n) is completely equivalent to callingm.__func__(m.__self__,arg-1,arg-2,..., arg-n).

Likefunction objects,bound method objects support getting arbitrary attributes. However, since method attributes are actually stored on the underlying function object (method.__func__), setting method attributes on bound methods is disallowed. Attempting to set an attribute on a method results in anAttributeErrorbeing raised. In order to set a method attribute, you need to explicitly set it on the underlying function object:

>>>classC:
...defmethod(self):
...pass
...
>>>c=C()
>>>c.method.whoami='my name is method'# can't set on the method
Traceback (most recent call last):
File"<stdin>",line1,in<module>
AttributeError:'method' object has no attribute 'whoami'
>>>c.method.__func__.whoami='my name is method'
>>>c.method.whoami
'my name is method'

SeeInstance methodsfor more information.

Code Objects

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-incompile()function and can be extracted from function objects through their __code__attribute. See also thecodemodule.

Accessing__code__raises anauditing event object.__getattr__with argumentsobjand"__code__".

A code object can be executed or evaluated by passing it (instead of a source string) to theexec()oreval()built-in functions.

SeeThe standard type hierarchyfor more information.

Type Objects

Type objects represent the various object types. An object’s type is accessed by the built-in functiontype().There are no special operations on types. The standard moduletypesdefines names for all standard built-in types.

Types are written like this:<class'int'>.

The Null Object

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 None(a built-in name).type(None)()produces the same singleton.

It is written asNone.

The Ellipsis Object

This object is commonly used by slicing (seeSlicings). It supports no special operations. There is exactly one ellipsis object, named Ellipsis(a built-in name).type(Ellipsis)()produces the Ellipsissingleton.

It is written asEllipsisor....

The NotImplemented Object

This object is returned from comparisons and binary operations when they are asked to operate on types they don’t support. SeeComparisonsfor more information. There is exactly oneNotImplementedobject. type(NotImplemented)()produces the singleton instance.

It is written asNotImplemented.

Internal Objects

SeeThe standard type hierarchyfor this information. It describes stack frame objects, traceback objects,and slice objects.

Special Attributes

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 dir()built-in function.

definition.__name__

The name of the class, function, method, descriptor, or generator instance.

definition.__qualname__

Thequalified nameof the class, function, method, descriptor, or generator instance.

Added in version 3.3.

definition.__module__

The name of the module in which a class or function was defined.

definition.__doc__

The documentation string of a class or function, orNoneif undefined.

definition.__type_params__

Thetype parametersof generic classes, functions, andtype aliases.For classes and functions that are not generic, this will be an empty tuple.

Added in version 3.12.

Integer string conversion length limitation

CPython has a global limit for converting betweenintandstr to mitigate denial of service attacks. This limitonlyapplies to decimal or other non-power-of-two number bases. Hexadecimal, octal, and binary conversions are unlimited. The limit can be configured.

Theinttype in CPython is an arbitrary length number stored in binary form (commonly known as a “bignum” ). There exists no algorithm that can convert a string to a binary integer or a binary integer to a string in linear time, unlessthe base is a power of 2. Even the best known algorithms for base 10 have sub-quadratic complexity. Converting a large value such asint('1'* 500_000)can take over a second on a fast CPU.

Limiting conversion size offers a practical way to avoidCVE 2020-10735.

The limit is applied to the number of digit characters in the input or output string when a non-linear conversion algorithm would be involved. Underscores and the sign are not counted towards the limit.

When an operation would exceed the limit, aValueErroris raised:

>>>importsys
>>>sys.set_int_max_str_digits(4300)# Illustrative, this is the default.
>>>_=int('2'*5432)
Traceback (most recent call last):
...
ValueError:Exceeds the limit (4300 digits) for integer string conversion: value has 5432 digits; use sys.set_int_max_str_digits() to increase the limit
>>>i=int('2'*4300)
>>>len(str(i))
4300
>>>i_squared=i*i
>>>len(str(i_squared))
Traceback (most recent call last):
...
ValueError:Exceeds the limit (4300 digits) for integer string conversion; use sys.set_int_max_str_digits() to increase the limit
>>>len(hex(i_squared))
7144
>>>assertint(hex(i_squared),base=16)==i*i# Hexadecimal is unlimited.

The default limit is 4300 digits as provided in sys.int_info.default_max_str_digits. The lowest limit that can be configured is 640 digits as provided in sys.int_info.str_digits_check_threshold.

Verification:

>>>importsys
>>>assertsys.int_info.default_max_str_digits==4300,sys.int_info
>>>assertsys.int_info.str_digits_check_threshold==640,sys.int_info
>>>msg=int('578966293710682886880994035146873798396722250538762761564'
...'9252925514383915483333812743580549779436104706260696366600'
...'571186405732').to_bytes(53,'big')
...

Added in version 3.11.

Affected APIs

The limitation only applies to potentially slow conversions betweenint andstrorbytes:

  • int(string)with default base 10.

  • int(string,base)for all bases that are not a power of 2.

  • str(integer).

  • repr(integer).

  • any other string conversion to base 10, for examplef "{integer}", "{}".format(integer),orb "%d"%integer.

The limitations do not apply to functions with a linear algorithm:

Configuring the limit

Before Python starts up you can use an environment variable or an interpreter command line flag to configure the limit:

From code, you can inspect the current limit and set a new one using these sysAPIs:

Information about the default and minimum can be found insys.int_info:

Added in version 3.11.

Caution

Setting a low limitcanlead to problems. While rare, code exists that contains integer constants in decimal in their source that exceed the minimum threshold. A consequence of setting the limit is that Python source code containing decimal integer literals longer than the limit will encounter an error during parsing, usually at startup time or import time or even at installation time - anytime an up to date.pycdoes not already exist for the code. A workaround for source that contains such large constants is to convert them to0xhexadecimal form as it has no limit.

Test your application thoroughly if you use a low limit. Ensure your tests run with the limit set early via the environment or flag so that it applies during startup and even during any installation step that may invoke Python to precompile.pysources to.pycfiles.