You are on page 1of 67

16/12/2016 4.BuiltinTypesPython3.5.

2documentation

4.BuiltinTypes
Thefollowingsectionsdescribethestandardtypesthatarebuiltintotheinterpreter.

The principal builtin types are numerics, sequences, mappings, classes, instances and
exceptions.

Some collection classes are mutable. The methods that add, subtract, or rearrange their
membersinplace,anddontreturnaspecificitem,neverreturnthecollectioninstanceitself
but None .

Some operations are supported by several object types in particular, practically all objects
canbecompared,testedfortruthvalue,andconvertedtoastring(withthe repr() functionor
the slightly different str() function). The latter function is implicitly used when an object is
writtenbythe print() function.

4.1.TruthValueTesting
Anyobjectcanbetestedfortruthvalue,foruseinan if or while conditionorasoperandof
theBooleanoperationsbelow.Thefollowingvaluesareconsideredfalse:

None

False

zeroofanynumerictype,forexample, 0 , 0.0 , 0j .

anyemptysequence,forexample, '' , () , [] .

anyemptymapping,forexample, {} .

instances of userdefined classes, if the class defines a __bool__() or __len__()


method,whenthatmethodreturnstheintegerzeroor bool value False .[1]

Allothervaluesareconsideredtruesoobjectsofmanytypesarealwaystrue.

OperationsandbuiltinfunctionsthathaveaBooleanresultalwaysreturn 0 or False forfalse


and 1 or True fortrue,unlessotherwisestated.(Importantexception:theBooleanoperations
or and and alwaysreturnoneoftheiroperands.)

4.2.BooleanOperations and , or , not


ThesearetheBooleanoperations,orderedbyascendingpriority:

Operation Result Notes


xory ifxisfalse,theny,elsex (1)
xandy ifxisfalse,thenx,elsey (2)

https://docs.python.org/3/library/stdtypes.html#iteratortypes 1/67
16/12/2016 4.BuiltinTypesPython3.5.2documentation

Operation Result Notes


notx ifxisfalse,then True ,else False (3)

Notes:

1.Thisisashortcircuitoperator,soitonlyevaluatesthesecondargumentifthefirstone
is False .
2.Thisisashortcircuitoperator,soitonlyevaluatesthesecondargumentifthefirstone
is True .
3. not hasalowerprioritythannonBooleanoperators,so nota==b is interpreted as
not(a==b) ,and a==notb isasyntaxerror.

4.3.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<=z is equivalent to x<yand y <= z , except that y is evaluated only
once(butinbothcaseszisnotevaluatedatallwhen x<y isfoundtobefalse).

Thistablesummarizesthecomparisonoperations:

Operation Meaning
< strictlylessthan
<= lessthanorequal
> strictlygreaterthan
>= greaterthanorequal
== equal
!= notequal
is objectidentity
isnot negatedobjectidentity

Objectsofdifferenttypes,exceptdifferentnumerictypes,nevercompareequal.Furthermore,
some types (for example, function objects) support only a degenerate notion of comparison
where any two objects of that type are unequal. The < , <= , > and >= operators will raise a
TypeError exceptionwhencomparingacomplexnumberwithanotherbuiltinnumerictype,
when the objects are of different types that cannot be compared, or in other cases where
thereisnodefinedordering.

Nonidentical instances of a class normally compare as nonequal unless the class defines
the __eq__() method.

Instancesofaclasscannotbeorderedwithrespecttootherinstancesofthesameclass,or
othertypesofobject,unlesstheclassdefinesenoughofthemethods __lt__() , __le__() ,
__gt__() ,and __ge__() (ingeneral, __lt__() and __eq__() aresufficient,ifyouwantthe
conventionalmeaningsofthecomparisonoperators).

https://docs.python.org/3/library/stdtypes.html#iteratortypes 2/67
16/12/2016 4.BuiltinTypesPython3.5.2documentation

Thebehaviorofthe is and isnot operatorscannotbecustomizedalsotheycanbeapplied


toanytwoobjectsandneverraiseanexception.

Twomoreoperationswiththesamesyntacticpriority, in and notin ,aresupportedonlyby


sequencetypes(below).

4.4.NumericTypes int , float , complex


There are three distinct numeric types: integers, floating point numbers, and complex
numbers.Inaddition,Booleansareasubtypeofintegers.Integers have unlimited precision.
Floating point numbers are usually implemented using double in C information about the
precisionandinternalrepresentationoffloatingpointnumbersforthemachineonwhichyour
program is running is available in sys.float_info . Complex numbers have a real and
imaginarypart,whichareeachafloatingpointnumber.Toextractthesepartsfromacomplex
numberz,use z.real and z.imag .(Thestandardlibraryincludesadditionalnumerictypes,
fractions that hold rationals, and decimal that hold floatingpoint numbers with user
definableprecision.)

Numbers are created by numeric literals or as the result of builtin functions and operators.
Unadorned integer literals (including hex, octal and binary numbers) yield integers. Numeric
literalscontainingadecimalpointoranexponentsignyieldfloatingpointnumbers.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
imaginaryparts.

Python fully supports mixed arithmetic: when a binary arithmetic operator has operands of
differentnumerictypes,theoperandwiththenarrowertypeiswidenedtothatoftheother,
whereintegerisnarrowerthanfloatingpoint,whichisnarrowerthancomplex.Comparisons
betweennumbersofmixedtypeusethesamerule.[2]Theconstructors int() , float() ,and
complex() canbeusedtoproducenumbersofaspecifictype.

All numeric types (except complex) support the following operations, sorted by ascending
priority(allnumericoperationshaveahigherprioritythancomparisonoperations):

Full
Operation Result Notes documentation
x+y sumofxandy
xy differenceofxandy
x*y productofxandy
x/y quotientofxandy
x//y flooredquotientofxandy (1)
x%y remainderof x/y (2)
x xnegated
+x xunchanged
abs(x) absolutevalueormagnitudeofx abs()
int(x) xconvertedtointeger (3)(6) int()
https://docs.python.org/3/library/stdtypes.html#iteratortypes 3/67
16/12/2016 4.BuiltinTypesPython3.5.2documentation

Full
Operation Result Notes documentation
float(x) xconvertedtofloatingpoint (4)(6) float()
complex(re,im) acomplexnumberwithrealpart (6) complex()
re,imaginarypartim.imdefaults
tozero.
c.conjugate() conjugateofthecomplexnumber
c
divmod(x,y) thepair (x//y,x%y) (2) divmod()
pow(x,y) xtothepowery (5) pow()
x**y xtothepowery (5)

Notes:

1.Also referred to as integer division. The resultant value is a whole integer, though the
resultstypeisnotnecessarilyint.Theresultisalwaysroundedtowardsminusinfinity:
1//2 is 0 , (1)//2 is 1 , 1//(2) is 1 ,and (1)//(2) is 0 .

2.Notforcomplexnumbers.Insteadconverttofloatsusing abs() ifappropriate.

3.Conversion from floating point to integer may round or truncate as in C see functions
math.floor() and math.ceil() forwelldefinedconversions.

4.float also accepts the strings nan and inf with an optional prefix + or for Not a
Number(NaN)andpositiveornegativeinfinity.

5.Python defines pow(0, 0) and 0 ** 0 to be 1 , as is common for programming


languages.

6.Thenumericliteralsacceptedincludethedigits 0 to 9 oranyUnicodeequivalent(code
pointswiththe Nd property).

See http://www.unicode.org/Public/8.0.0/ucd/extracted/DerivedNumericType.txt for a


completelistofcodepointswiththe Nd property.

All numbers.Real types( int and float )alsoincludethefollowingoperations:

Operation Result
math.trunc(x) xtruncatedto Integral
round(x[,n]) xroundedtondigits,roundinghalftoeven.Ifnisomitted,it
defaultsto0.
math.floor(x) thegreatest Integral <=x
math.ceil(x) theleast Integral >=x

Foradditionalnumericoperationsseethe math and cmath modules.

4.4.1.BitwiseOperationsonIntegerTypes

https://docs.python.org/3/library/stdtypes.html#iteratortypes 4/67
16/12/2016 4.BuiltinTypesPython3.5.2documentation

Bitwise operations only make sense for integers. Negative numbers are treated as their 2s
complementvalue(thisassumesthatthereareenoughbitssothatnooverflowoccursduring
theoperation).

The priorities of the binary bitwise operations are all lower than the numeric operations and
higherthanthecomparisonstheunaryoperation ~ hasthesamepriorityastheotherunary
numericoperations( + and ).

Thistableliststhebitwiseoperationssortedinascendingpriority:

Operation Result Notes


x|y bitwiseorofxandy
x^y bitwiseexclusiveorofxandy
x&y bitwiseandofxandy
x<<n xshiftedleftbynbits (1)(2)
x>>n xshiftedrightbynbits (1)(3)
~x thebitsofxinverted

Notes:

1.Negativeshiftcountsareillegalandcausea ValueError toberaised.


2.Aleftshiftbynbitsisequivalenttomultiplicationby pow(2,n) withoutoverflowcheck.
3.Arightshiftbynbitsisequivalenttodivisionby pow(2,n) withoutoverflowcheck.

4.4.2.AdditionalMethodsonIntegerTypes
Theinttypeimplementsthe numbers.Integral abstractbaseclass.Inaddition,itprovidesa
fewmoremethods:

int. bit_length()
Returnthenumberofbitsnecessarytorepresentanintegerinbinary,excludingthesign
andleadingzeros:

>>>n=37 >>>
>>>bin(n)
'0b100101'
>>>n.bit_length()
6

More precisely, if x is nonzero, then x.bit_length() is the unique positive integer k


suchthat 2**(k1)<=abs(x)<2**k . Equivalently, when abs(x) is small enough to
have a correctly rounded logarithm, then k=1+ int(log(abs(x), 2)) . If x is zero,
then x.bit_length() returns 0 .

Equivalentto:

defbit_length(self):
s=bin(self)#binaryrepresentation:bin(37)>'0b100101'

https://docs.python.org/3/library/stdtypes.html#iteratortypes 5/67
16/12/2016 4.BuiltinTypesPython3.5.2documentation

s=s.lstrip('0b')#removeleadingzerosandminussign
returnlen(s)#len('100101')>6

Newinversion3.1.

int. to_bytes(length,byteorder,*,signed=False)
Returnanarrayofbytesrepresentinganinteger.

>>>(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'

Theintegerisrepresentedusinglengthbytes.An OverflowError israisediftheinteger


isnotrepresentablewiththegivennumberofbytes.

The byteorder argument determines the byte order used to represent the integer. If
byteorder is "big" , the most significant byte is at the beginning of the byte array. If
byteorderis "little" ,themostsignificantbyteisattheendofthebytearray.Torequest
thenativebyteorderofthehostsystem,use sys.byteorder asthebyteordervalue.

The signed argument determines whether twos complement is used to represent the
integer.Ifsignedis False andanegativeintegerisgiven,an OverflowError israised.
Thedefaultvalueforsignedis False .

Newinversion3.2.

classmethod int. from_bytes(bytes,byteorder,*,signed=False)


Returntheintegerrepresentedbythegivenarrayofbytes.

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

Theargumentbytesmusteitherbeabyteslikeobjectoraniterableproducingbytes.

The byteorder argument determines the byte order used to represent the integer. If
byteorder is "big" , the most significant byte is at the beginning of the byte array. If

https://docs.python.org/3/library/stdtypes.html#iteratortypes 6/67
16/12/2016 4.BuiltinTypesPython3.5.2documentation

byteorderis "little" ,themostsignificantbyteisattheendofthebytearray.Torequest


thenativebyteorderofthehostsystem,use sys.byteorder asthebyteordervalue.

The signed argument indicates whether twos complement is used to represent the
integer.

Newinversion3.2.

4.4.3.AdditionalMethodsonFloat
Thefloattypeimplementsthe numbers.Real abstractbaseclass.floatalsohasthefollowing
additionalmethods.

float. as_integer_ratio()
Return a pair of integers whose ratio is exactly equal to the original float and with a
positivedenominator.Raises OverflowError oninfinitiesanda ValueError onNaNs.

float. is_integer()
Return True ifthefloatinstanceisfinitewithintegralvalue,and False otherwise:

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

Twomethodssupportconversiontoandfromhexadecimalstrings.SincePythonsfloatsare
stored internally as binary numbers, converting a float to or from a decimal string usually
involves a small rounding error. In contrast, hexadecimal strings allow exact representation
and specification of floatingpoint numbers. This can be useful when debugging, and in
numericalwork.

float. hex()
Return a representation of a floatingpoint number as a hexadecimal string. For finite
floatingpointnumbers,thisrepresentationwillalwaysincludealeading 0x andatrailing
p andexponent.

classmethod float. fromhex(s)


Classmethodtoreturnthefloatrepresentedbyahexadecimalstrings.Thestringsmay
haveleadingandtrailingwhitespace.

Notethat float.hex() isaninstancemethod,while float.fromhex() isaclassmethod.

Ahexadecimalstringtakestheform:

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

where the optional sign may by either + or , integer and fraction are strings of
hexadecimaldigits,and exponent isadecimalintegerwithanoptionalleadingsign.Caseis
not significant, and there must be at least one hexadecimal digit in either the integer or the

https://docs.python.org/3/library/stdtypes.html#iteratortypes 7/67
16/12/2016 4.BuiltinTypesPython3.5.2documentation

fraction.Thissyntaxissimilartothesyntaxspecifiedinsection6.4.4.2oftheC99standard,
andalsotothesyntaxusedinJava1.5onwards.Inparticular,theoutputof float.hex() is
usable as a hexadecimal floatingpoint literal in C or Java code, and hexadecimal strings
produced by Cs %a format character or Javas Double.toHexString are 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 string
0x3.a7p10 representsthefloatingpointnumber (3+10./16+7./16**2) * 2.0**10 , or
3740.0 :

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

Applyingthereverseconversionto 3740.0 givesadifferenthexadecimalstringrepresenting


thesamenumber:

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

4.4.4.Hashingofnumerictypes

Fornumbers x and y ,possiblyofdifferenttypes,itsarequirementthat hash(x)==hash(y)


whenever x==y (seethe __hash__() methoddocumentationformoredetails).Foreaseof
implementation and efficiency across a variety of numeric types (including int , float ,
decimal.Decimal and fractions.Fraction )Pythonshashfornumerictypesisbasedona
singlemathematicalfunctionthatsdefinedforanyrationalnumber,andhenceappliestoall
instances of int and fractions.Fraction , and all finite instances of float and
decimal.Decimal .Essentially,thisfunctionisgivenbyreductionmodulo P forafixedprime
P .Thevalueof P ismadeavailabletoPythonasthe modulus attributeof sys.hash_info .

CPythonimplementationdetail:Currently,theprimeusedis P=2**311 onmachines


with32bitClongsand P=2**611 onmachineswith64bitClongs.

Herearetherulesindetail:

If x = m / n is a nonnegative rational number and n is not divisible by P , define


hash(x) as m * invmod(n, P) % P , where invmod(n, P) gives the inverse of n
modulo P .
If x=m/n isanonnegativerationalnumberand n isdivisibleby P (but m isnot)then
n has no inverse modulo P and the rule above doesnt apply in this case define
hash(x) tobetheconstantvalue sys.hash_info.inf .
If x = m / n is a negative rational number define hash(x) as hash(x) . If the
resultinghashis 1 ,replaceitwith 2 .
The particular values sys.hash_info.inf , sys.hash_info.inf and
sys.hash_info.nan are used as hash values for positive infinity, negative infinity, or
nans(respectively).(Allhashablenanshavethesamehashvalue.)
Fora complex number z ,thehashvaluesoftherealandimaginarypartsarecombined
by computing hash(z.real) + sys.hash_info.imag * hash(z.imag) , reduced
modulo 2**sys.hash_info.width sothatitliesin range(2**(sys.hash_info.width
https://docs.python.org/3/library/stdtypes.html#iteratortypes 8/67
16/12/2016 4.BuiltinTypesPython3.5.2documentation

1),2**(sys.hash_info.width 1)) . Again, if the result is 1 , its replaced with


2 .

Toclarifytheaboverules,heressomeexamplePythoncode,equivalenttothebuiltinhash,
forcomputingthehashofarationalnumber, float ,or complex :

importsys,math

defhash_fraction(m,n):
"""Computethehashofarationalnumberm/n.

Assumesmandnareintegers,withnpositive.
Equivalenttohash(fractions.Fraction(m,n)).

"""
P=sys.hash_info.modulus
#RemovecommonfactorsofP.(Unnecessaryifmandnalreadycoprime.)
whilem%P==n%P==0:
m,n=m//P,n//P

ifn%P==0:
hash_value=sys.hash_info.inf
else:
#Fermat'sLittleTheorem:pow(n,P1,P)is1,so
#pow(n,P2,P)givestheinverseofnmoduloP.
hash_value=(abs(m)%P)*pow(n,P2,P)%P
ifm<0:
hash_value=hash_value
ifhash_value==1:
hash_value=2
returnhash_value

defhash_float(x):
"""Computethehashofafloatx."""

ifmath.isnan(x):
returnsys.hash_info.nan
elifmath.isinf(x):
returnsys.hash_info.infifx>0elsesys.hash_info.inf
else:
returnhash_fraction(*x.as_integer_ratio())

defhash_complex(z):
"""Computethehashofacomplexnumberz."""

hash_value=hash_float(z.real)+sys.hash_info.imag*hash_float(z.imag)
#doasignedreductionmodulo2**sys.hash_info.width
M=2**(sys.hash_info.width1)
hash_value=(hash_value&(M1))(hash_value&M)
ifhash_value==1:
hash_value=2
returnhash_value

4.5.IteratorTypes

https://docs.python.org/3/library/stdtypes.html#iteratortypes 9/67
16/12/2016 4.BuiltinTypesPython3.5.2documentation

Pythonsupportsaconceptofiterationovercontainers.Thisisimplementedusingtwodistinct
methods these are used to allow userdefined classes to support iteration. Sequences,
describedbelowinmoredetail,alwayssupporttheiterationmethods.

Onemethodneedstobedefinedforcontainerobjectstoprovideiterationsupport:

container. __iter__()
Returnaniteratorobject.Theobjectisrequiredtosupporttheiteratorprotocoldescribed
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
objectsupportingmultipleformsofiterationwouldbeatreestructurewhichsupportsboth
breadthfirst and depthfirst traversal.) This method corresponds to the tp_iter slot of
thetypestructureforPythonobjectsinthePython/CAPI.

The iterator objects themselves are required to support the following two methods, which
togetherformtheiteratorprotocol:

iterator. __iter__()
Returntheiteratorobjectitself.Thisisrequiredtoallowbothcontainersanditeratorsto
beusedwiththe for and in statements.Thismethodcorrespondstothe tp_iter slotof
thetypestructureforPythonobjectsinthePython/CAPI.

iterator. __next__()
Return the next item from the container. If there are no further items, raise the
StopIteration exception.Thismethodcorrespondstothe tp_iternext slotofthetype
structureforPythonobjectsinthePython/CAPI.

Pythondefinesseveraliteratorobjectstosupportiterationovergeneralandspecificsequence
types, dictionaries, and other more specialized forms. The specific types are not important
beyondtheirimplementationoftheiteratorprotocol.

Onceaniterators __next__() method raises StopIteration , it must continue to do so on


subsequentcalls.Implementationsthatdonotobeythispropertyaredeemedbroken.

4.5.1.GeneratorTypes
Pythons generators provide a convenient way to implement the iterator protocol. If a
container objects __iter__() method is implemented as a generator, it will automatically
return an iterator object (technically, a generator object) supplying the __iter__() and
__next__() methods.Moreinformationaboutgeneratorscanbefoundinthedocumentation
fortheyieldexpression.

4.6.SequenceTypes list , tuple , range


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

https://docs.python.org/3/library/stdtypes.html#iteratortypes 10/67
16/12/2016 4.BuiltinTypesPython3.5.2documentation

4.6.1.CommonSequenceOperations
The operations in the following table are supported by most sequence types, both mutable
and immutable. The collections.abc.Sequence ABC is provided to make it easier to
correctlyimplementtheseoperationsoncustomsequencetypes.

Thistableliststhesequenceoperationssortedinascendingpriority.Inthetable,sandtare
sequencesofthesametype,n,i,jandkareintegersandxisanarbitraryobjectthatmeets
anytypeandvaluerestrictionsimposedbys.

The in and notin operationshavethesameprioritiesasthecomparisonoperations.The +


(concatenation) and * (repetition) operations have the same priority as the corresponding
numericoperations.

Operation Result Notes


xins True ifanitemofsisequaltox,else (1)
False
xnotins False ifanitemofsisequaltox,else (1)
True
s+t theconcatenationofsandt (6)(7)
s*n or n*s equivalenttoaddingstoitselfntimes (2)(7)
s[i] ithitemofs,origin0 (3)
s[i:j] sliceofsfromitoj (3)(4)
s[i:j:k] sliceofsfromitojwithstepk (3)(5)
len(s) lengthofs
min(s) smallestitemofs
max(s) largestitemofs
s.index(x[,i[,j]]) indexofthefirstoccurrenceofxins(at (8)
orafterindexiandbeforeindexj)
s.count(x) totalnumberofoccurrencesofxins

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 see Comparisons in the language
reference.)

Notes:

1.Whilethe in and notin operationsareusedonlyforsimplecontainmenttestinginthe


generalcase,somespecialisedsequences(suchas str , bytes and bytearray ) also
usethemforsubsequencetesting:

>>>"gg"in"eggs" >>>
True

https://docs.python.org/3/library/stdtypes.html#iteratortypes 11/67
16/12/2016 4.BuiltinTypesPython3.5.2documentation

2.Valuesofnlessthan 0 aretreatedas 0 (whichyieldsanemptysequenceofthesame


type as s). Note that items in the sequence s are not copied they are referenced
multipletimes.ThisoftenhauntsnewPythonprogrammersconsider:

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

What has happened is that [[]] is a oneelement list containing an empty list, so all
threeelementsof [[]]*3 arereferencestothissingleemptylist.Modifyinganyofthe
elementsof lists modifiesthissinglelist.Youcancreatealistofdifferentliststhisway:

>>>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.Ifiorjisnegative,theindexisrelativetotheendofthestring: len(s)+i or len(s)+


j issubstituted.Butnotethat 0 isstill 0 .

4.Thesliceofsfromitojisdefinedasthesequenceofitemswithindexksuchthat i<=
k<j .Ifiorjisgreaterthan len(s) ,use len(s) .Ifiisomittedor None ,use 0 .Ifj is
omittedor None ,use len(s) .Ifiisgreaterthanorequaltoj,thesliceisempty.

5.Thesliceofsfromitojwithstepkisdefinedasthesequenceofitemswithindex x=i
+ n*k such that 0 <= n < (ji)/k . In other words, the indices are i , i+k , i+2*k ,
i+3*k andsoon,stoppingwhenjisreached(butneverincludingj).Ifiorj is greater
than len(s) ,use len(s) .Ifiorjareomittedor None ,theybecomeendvalues(which
enddependsonthesignofk).Note,kcannotbezero.Ifkis None ,itistreatedlike 1 .

6.Concatenating immutable sequences always results in a new object. This means that
buildingupasequencebyrepeatedconcatenationwillhaveaquadraticruntimecostin
the total sequence length. To get a linear runtime cost, you must switch to one of the
alternativesbelow:

ifconcatenating str objects,youcanbuildalistanduse str.join() attheend


orelsewritetoan io.StringIO instanceandretrieveitsvaluewhencomplete
if concatenating bytes objects, you can similarly use bytes.join() or
io.BytesIO , or you can do inplace concatenation with a bytearray object.
bytearray objectsaremutableandhaveanefficientoverallocationmechanism
ifconcatenating tuple objects,extenda list instead
forothertypes,investigatetherelevantclassdocumentation

https://docs.python.org/3/library/stdtypes.html#iteratortypes 12/67
16/12/2016 4.BuiltinTypesPython3.5.2documentation

7.Somesequencetypes(suchas range )onlysupportitemsequencesthatfollowspecific


patterns,andhencedontsupportsequenceconcatenationorrepetition.

8. index raises ValueError when x is not found in s. When supported, the additional
argumentstotheindexmethodallowefficientsearchingofsubsectionsofthesequence.
Passing the extra arguments is roughly equivalent to using s[i:j].index(x) , only
without copying any data and with the returned index being relative to the start of the
sequenceratherthanthestartoftheslice.

4.6.2.ImmutableSequenceTypes
The only operation that immutable sequence types generally implement that is not also
implementedbymutablesequencetypesissupportforthe hash() builtin.

Thissupportallowsimmutablesequences,suchas tuple instances,tobeusedas dict keys


andstoredin set and frozenset instances.

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

4.6.3.MutableSequenceTypes

The operations in the following table are defined on mutable sequence types. The
collections.abc.MutableSequence ABC is provided to make it easier to correctly
implementtheseoperationsoncustomsequencetypes.

Inthetablesisaninstanceofamutablesequencetype,tisanyiterableobjectandxisan
arbitrary object that meets any type and value restrictions imposed by s (for example,
bytearray onlyacceptsintegersthatmeetthevaluerestriction 0<=x<=255 ).

Operation Result Notes


s[i]=x itemiofsisreplacedbyx
s[i:j]=t sliceofsfromitojisreplacedby
thecontentsoftheiterablet
dels[i:j] sameas s[i:j]=[]
s[i:j:k]=t theelementsof s[i:j:k] are (1)
replacedbythoseoft
dels[i:j:k] removestheelementsof
s[i:j:k] fromthelist
s.append(x) appendsxtotheendofthe
sequence(sameas
s[len(s):len(s)]=[x] )
s.clear() removesallitemsfrom s (same (5)
as dels[:] )
s.copy() createsashallowcopyof s (5)
(sameas s[:] )

https://docs.python.org/3/library/stdtypes.html#iteratortypes 13/67
16/12/2016 4.BuiltinTypesPython3.5.2documentation

Operation Result Notes


s.extend(t) or s+=t extendsswiththecontentsoft
(forthemostpartthesameas
s[len(s):len(s)]=t )
s*=n updatesswithitscontents (6)
repeatedntimes
s.insert(i,x) insertsxintosattheindexgiven
byi(sameas s[i:i]=[x] )
s.pop([i]) retrievestheitematiandalso (2)
removesitfroms
s.remove(x) removethefirstitemfroms (3)
where s[i]==x
s.reverse() reversestheitemsofsinplace (4)

Notes:

1.tmusthavethesamelengthasthesliceitisreplacing.

2.Theoptionalargumentidefaultsto 1 ,sothatbydefaultthelastitemisremovedand
returned.

3. remove raises ValueError whenxisnotfoundins.

4.The reverse() method modifies the sequence in place for economy of space when
reversingalargesequence.Toremindusersthatitoperatesbysideeffect,itdoesnot
returnthereversedsequence.

5. clear() and copy() are included for consistency with the interfaces of mutable
containersthatdontsupportslicingoperations(suchas dict and set )

Newinversion3.3: clear() and copy() methods.

6.Thevaluen is an integer, or an object implementing __index__() .Zero and negative


values of n clear the sequence. Items in the sequence are not copied they are
referenced multiple times, as explained for s * n under Common Sequence
Operations.

4.6.4.Lists
Listsaremutablesequences,typicallyusedtostorecollectionsofhomogeneousitems(where
theprecisedegreeofsimilaritywillvarybyapplication).

class list([iterable])
Listsmaybeconstructedinseveralways:

Usingapairofsquarebracketstodenotetheemptylist: []
Usingsquarebrackets,separatingitemswithcommas: [a] , [a,b,c]
Usingalistcomprehension: [xforxiniterable]
Usingthetypeconstructor: list() or list(iterable)

https://docs.python.org/3/library/stdtypes.html#iteratortypes 14/67
16/12/2016 4.BuiltinTypesPython3.5.2documentation

The constructor builds a list whose items are the same and in the same order as
iterablesitems.iterablemaybeeitherasequence,acontainerthatsupportsiteration,or
an iterator object. If iterable is already a list, a copy is made and returned, similar to
iterable[:] .Forexample, 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, [] .

Manyotheroperationsalsoproducelists,includingthe sorted() builtin.

Listsimplementallofthecommonandmutablesequenceoperations.Listsalsoprovide
thefollowingadditionalmethod:

sort(*,key=None,reverse=None)
This method sorts the list in place, using only < comparisons between items.
Exceptions are not suppressed if any comparison operations fail, the entire sort
operationwillfail(andthelistwilllikelybeleftinapartiallymodifiedstate).

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

key specifies a function of one argument that is used to extract a comparison key
fromeachlistelement(forexample, key=str.lower ).Thekeycorrespondingtoeach
item in the list is calculated once and then used for the entire sorting process. The
default value of None means that list items are sorted directly without calculating a
separatekeyvalue.

The functools.cmp_to_key() utilityisavailabletoconverta2.xstylecmp function


toakeyfunction.

reverseisabooleanvalue.Ifsetto True ,thenthelistelementsaresortedasifeach


comparisonwerereversed.

This method modifies the sequence in place for economy of space when sorting a
largesequence.Toremindusersthatitoperatesbysideeffect,itdoesnotreturnthe
sortedsequence(use sorted() toexplicitlyrequestanewsortedlistinstance).

The sort() methodisguaranteedtobestable.Asortisstableifitguaranteesnotto


changetherelativeorderofelementsthatcompareequalthisishelpfulforsorting
inmultiplepasses(forexample,sortbydepartment,thenbysalarygrade).

CPythonimplementationdetail:Whilealistisbeingsorted,theeffectofattempting
to mutate, or even inspect, the list is undefined. The C implementation of Python
makesthelistappearemptyfortheduration,andraises ValueError ifitcandetect
thatthelisthasbeenmutatedduringasort.

4.6.5.Tuples
Tuples are immutable sequences, typically used to store collections of heterogeneous data
(suchasthe2tuplesproducedbythe enumerate() builtin).Tuplesarealsousedforcases

https://docs.python.org/3/library/stdtypes.html#iteratortypes 15/67
16/12/2016 4.BuiltinTypesPython3.5.2documentation

whereanimmutablesequenceofhomogeneousdataisneeded(suchasallowingstoragein
a set or dict instance).

class tuple([iterable])
Tuplesmaybeconstructedinanumberofways:

Usingapairofparenthesestodenotetheemptytuple: ()
Usingatrailingcommaforasingletontuple: a, or (a,)
Separatingitemswithcommas: a,b,c or (a,b,c)
Usingthe tuple() builtin: tuple() or tuple(iterable)
The constructor builds a tuple whose items are the same and in the same order as
iterablesitems.iterablemaybeeitherasequence,acontainerthatsupportsiteration,or
an iterator object. If iterable 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) .
Ifnoargumentisgiven,theconstructorcreatesanewemptytuple, () .

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)) isafunctioncallwitha3tupleasthesoleargument.

Tuplesimplementallofthecommonsequenceoperations.

Forheterogeneouscollectionsofdatawhereaccessbynameisclearerthanaccessbyindex,
collections.namedtuple() maybeamoreappropriatechoicethanasimpletupleobject.

4.6.6.Ranges
The range type represents an immutable sequence of numbers and is commonly used for
loopingaspecificnumberoftimesin for loops.

class range(stop)
class range(start,stop[,step])
Theargumentstotherangeconstructormustbeintegers(eitherbuiltin int oranyobject
that implements the __index__ special method). If the step argument is omitted, it
defaultsto 1 .Ifthestartargumentisomitted,itdefaultsto 0 .Ifstepiszero, ValueError
israised.

For a positive step, the contents of a range r are determined by the formula r[i] =
start+step*i where i>=0 and r[i]<stop .

Foranegativestep,thecontentsoftherangearestilldeterminedbytheformula r[i]=
start+step*i ,buttheconstraintsare i>=0 and r[i]>stop .

A range object will be empty if r[0] does not meet the value constraint. Ranges do
support negative indices, but these are interpreted as indexing from the end of the
sequencedeterminedbythepositiveindices.

https://docs.python.org/3/library/stdtypes.html#iteratortypes 16/67
16/12/2016 4.BuiltinTypesPython3.5.2documentation

Ranges containing absolute values larger than sys.maxsize are permitted but some
features(suchas len() )mayraise OverflowError .

Rangeexamples:

>>>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 the common sequence operations except concatenation and
repetition(duetothefactthatrangeobjectscanonlyrepresentsequencesthatfollowa
strictpatternandrepetitionandconcatenationwillusuallyviolatethatpattern).

start
Thevalueofthestartparameter(or 0 iftheparameterwasnotsupplied)

stop
Thevalueofthestopparameter

step
Thevalueofthestepparameter(or 1 iftheparameterwasnotsupplied)

The advantage of the range type over a regular list or tuple is that a range object will
alwaystakethesame(small)amountofmemory,nomatterthesizeoftherangeitrepresents
(as it only stores the start , stop and step values, calculating individual items and
subrangesasneeded).

Range objects implement the collections.abc.Sequence ABC, and provide features such
as containment tests, element index lookup, slicing and support for negative indices (see
SequenceTypeslist,tuple,range):

>>>
>>>r=range(0,20,2)
>>>r
range(0,20,2)
>>>11inr
False
>>>10inr
True
>>>r.index(10)
5
>>>r[5]
10
https://docs.python.org/3/library/stdtypes.html#iteratortypes 17/67
16/12/2016 4.BuiltinTypesPython3.5.2documentation

>>>r[:5]
range(0,10,2)
>>>r[1]
18

Testingrangeobjectsforequalitywith == and != comparesthemassequences.Thatis,two


rangeobjectsareconsideredequaliftheyrepresentthesamesequenceofvalues.(Notethat
tworangeobjectsthatcompareequalmighthavedifferent start , stop and step attributes,
forexample range(0)==range(2,1,3) or range(0,3,2)==range(0,4,2) .)

Changedinversion3.2:ImplementtheSequenceABC.Supportslicingandnegativeindices.
Test int objectsformembershipinconstanttimeinsteadofiteratingthroughallitems.

Changedinversion3.3:Define==and!=tocomparerangeobjectsbasedonthesequence
ofvaluestheydefine(insteadofcomparingbasedonobjectidentity).

Newinversion3.3:The start , stop and step attributes.

4.7.TextSequenceType str
Textual data in Python is handled with str objects, or strings. Strings are immutable
sequencesofUnicodecodepoints.Stringliteralsarewritteninavarietyofways:

Singlequotes: 'allowsembedded"double"quotes'
Doublequotes: "allowsembedded'single'quotes" .
Triplequoted: '''Threesinglequotes''' , """Threedoublequotes"""

Triple quoted strings may span multiple lines all associated whitespace will be included in
thestringliteral.

Stringliteralsthatarepartofasingleexpressionandhaveonlywhitespacebetweenthemwill
beimplicitlyconvertedtoasinglestringliteral.Thatis, ("spam""eggs")=="spameggs" .

See String and Bytes literals for more about the various forms of string literal, including
supportedescape sequences, and the r (raw) prefix that disables most escape sequence
processing.

Stringsmayalsobecreatedfromotherobjectsusingthe str constructor.

Since there is no separate character type, indexing a string produces strings of length 1.
Thatis,foranonemptystrings, s[0]==s[0:1] .

There is also no mutable string type, but str.join() or io.StringIO can be used to
efficientlyconstructstringsfrommultiplefragments.

Changedinversion3.3:ForbackwardscompatibilitywiththePython2series,the u prefixis
once again permitted on string literals. It has no effect on the meaning of string literals and
cannotbecombinedwiththe r prefix.

class str(object='')
class str(object=b'',encoding='utf8',errors='strict')
https://docs.python.org/3/library/stdtypes.html#iteratortypes 18/67
16/12/2016 4.BuiltinTypesPython3.5.2documentation

Return a string version of object. If object is not provided, returns the empty string.
Otherwise, the behavior of str() depends on whether encoding or errors is given, as
follows.

Ifneitherencodingnorerrorsisgiven, str(object) returns object.__str__() ,whichis


theinformalornicelyprintablestringrepresentationofobject.Forstringobjects,thisis
the string itself. If object does not have a __str__() method, then str() falls back to
returning repr(object) .

If at least one of encoding or errors is given, object should be a byteslike object (e.g.
bytes or bytearray ). In this case, if object is a bytes (or bytearray ) object, then
str(bytes, encoding, errors) is equivalent to bytes.decode(encoding, errors) .
Otherwise, the bytes object underlying the buffer object is obtained before calling
bytes.decode() . See Binary Sequence Types bytes, bytearray, memoryview and
BufferProtocolforinformationonbufferobjects.

Passinga bytes objectto str() withouttheencodingorerrorsargumentsfallsunderthe


first case of returning the informal string representation (see also the b commandline
optiontoPython).Forexample:

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

Formoreinformationonthe str classanditsmethods,seeTextSequenceTypestr


andtheStringMethodssectionbelow.Tooutputformattedstrings,seetheFormatString
Syntaxsection.Inaddition,seetheTextProcessingServicessection.

4.7.1.StringMethods

Stringsimplementallofthecommonsequenceoperations,alongwiththeadditionalmethods
describedbelow.

Stringsalsosupporttwostylesofstringformatting,oneprovidingalargedegreeofflexibility
andcustomization(see str.format() ,FormatStringSyntaxandCustomStringFormatting)
andtheotherbasedonC printf styleformattingthathandlesanarrowerrangeoftypesand
is slightly harder to use correctly, but is often faster for the cases it can handle (printfstyle
StringFormatting).

The Text Processing Services section of the standard library covers a number of other
modulesthatprovidevarioustextrelatedutilities(includingregularexpressionsupportinthe
re module).

str. capitalize()
Returnacopyofthestringwithitsfirstcharactercapitalizedandtherestlowercased.

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

https://docs.python.org/3/library/stdtypes.html#iteratortypes 19/67
16/12/2016 4.BuiltinTypesPython3.5.2documentation

Casefolding is similar to lowercasing but more aggressive because it is intended to


removeallcasedistinctionsinastring.Forexample,theGermanlowercaseletter '' is
equivalent to "ss" . Since it is already lowercase, lower() would do nothing to ''
casefold() convertsitto "ss" .

Thecasefoldingalgorithmisdescribedinsection3.13oftheUnicodeStandard.

Newinversion3.3.

str. center(width[,fillchar])
Return centered in a string of length width. Padding is done using the specified fillchar
(defaultisanASCIIspace).Theoriginalstringisreturnedifwidthislessthanorequalto
len(s) .

str. count(sub[,start[,end]])
Return the number of nonoverlapping occurrences of substring sub in the range [start,
end].Optionalargumentsstartandendareinterpretedasinslicenotation.

str. encode(encoding="utf8",errors="strict")
Returnanencodedversionofthestringasabytesobject.Defaultencodingis 'utf8' .
errors may be given to set a different error handling scheme. The default for errors is
'strict' , meaning that encoding errors raise a UnicodeError . Other possible values
are 'ignore' , 'replace' , 'xmlcharrefreplace' , 'backslashreplace' and any other
nameregisteredvia codecs.register_error() ,seesectionErrorHandlers.Foralistof
possibleencodings,seesectionStandardEncodings.

Changedinversion3.1:Supportforkeywordargumentsadded.

str. endswith(suffix[,start[,end]])
Return True ifthestringendswiththespecifiedsuffix,otherwisereturn False .suffixcan
alsobeatupleofsuffixestolookfor.Withoptionalstart, testbeginningat that position.
Withoptionalend,stopcomparingatthatposition.

str. expandtabs(tabsize=8)
Returnacopyofthestringwherealltabcharactersarereplacedbyoneormorespaces,
depending on the current column and the given tab size. Tab positions occur every
tabsize characters (default is 8, giving tab positions at columns 0, 8, 16 and so on). To
expandthestring,thecurrentcolumnissettozeroandthestringisexaminedcharacter
bycharacter.Ifthecharacterisatab( \t ),oneormorespacecharactersareinsertedin
the result until the current column is equal to the next tab position. (The tab character
itselfisnotcopied.)Ifthecharacterisanewline( \n )orreturn( \r ),itiscopiedandthe
currentcolumnisresettozero.Anyothercharacteriscopiedunchangedandthecurrent
column is incremented by one regardless of how the character is represented when
printed.

>>>'01\t012\t0123\t01234'.expandtabs() >>>
'01012012301234'
>>>'01\t012\t0123\t01234'.expandtabs(4)
'01012012301234'
https://docs.python.org/3/library/stdtypes.html#iteratortypes 20/67
16/12/2016 4.BuiltinTypesPython3.5.2documentation

str. find(sub[,start[,end]])
Return the lowest index in the string where substring sub is found within the slice
s[start:end] . Optional arguments start and end are interpreted as in slice notation.
Return 1 ifsubisnotfound.

Note: The find() method should be used only if you need to know the position of
sub.Tocheckifsubisasubstringornot,usethe in operator:

>>>'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.Returnsacopyofthestringwhereeachreplacementfieldisreplacedwiththe
stringvalueofthecorrespondingargument.

>>>"Thesumof1+2is{0}".format(1+2) >>>
'Thesumof1+2is3'

SeeFormatStringSyntaxforadescriptionofthevariousformattingoptionsthatcanbe
specifiedinformatstrings.

str. format_map(mapping)
Similarto str.format(**mapping) ,exceptthat mapping isuseddirectlyandnotcopied
toa dict .Thisisusefulifforexample mapping isadictsubclass:

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

Newinversion3.2.

str. index(sub[,start[,end]])
Like find() ,butraise ValueError whenthesubstringisnotfound.

str. isalnum()
Return true if all characters in the string are alphanumeric and there is at least one
character, false otherwise. Acharacter c is alphanumeric if one of the following returns
True : c.isalpha() , c.isdecimal() , c.isdigit() ,or c.isnumeric() .

str. isalpha()
Returntrueifallcharactersinthestringarealphabeticandthereisatleastonecharacter,
false otherwise. Alphabetic characters are those characters defined in the Unicode

https://docs.python.org/3/library/stdtypes.html#iteratortypes 21/67
16/12/2016 4.BuiltinTypesPython3.5.2documentation

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 the Alphabetic property
definedintheUnicodeStandard.

str. isdecimal()
Returntrueifallcharactersinthestringaredecimalcharactersandthereisatleastone
character, false otherwise. Decimal characters are those that can be used to form
numbers in base 10, e.g. U+0660, ARABICINDIC DIGIT ZERO. Formally a decimal
characterisacharacterintheUnicodeGeneralCategoryNd.

str. isdigit()
Return true if 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
formnumbersinbase10,liketheKharosthinumbers.Formally,adigitisacharacterthat
hasthepropertyvalueNumeric_Type=DigitorNumeric_Type=Decimal.

str. isidentifier()
Return true if the string is a valid identifier according to the language definition, section
Identifiersandkeywords.

Use keyword.iskeyword() totestforreservedidentifierssuchas def and class .

str. islower()
Returntrueifallcasedcharacters[4]inthestringarelowercaseandthereisatleastone
casedcharacter,falseotherwise.

str. isnumeric()
Returntrueifallcharactersinthestringarenumericcharacters,andthereisatleastone
character,falseotherwise.Numericcharactersincludedigitcharacters,andallcharacters
thathavetheUnicodenumericvalueproperty,e.g.U+2155,VULGARFRACTIONONE
FIFTH. Formally, numeric characters are those with the property value
Numeric_Type=Digit,Numeric_Type=DecimalorNumeric_Type=Numeric.

str. isprintable()
Return true if all characters in the string are printable or the string is empty, false
otherwise.NonprintablecharactersarethosecharactersdefinedintheUnicodecharacter
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
handlingofstringswrittento sys.stdout or sys.stderr .)

str. isspace()
Returntrueifthereareonlywhitespacecharactersinthestringandthereisatleastone
character, false otherwise. Whitespace characters are those characters defined in the
Unicode character database as Other or Separator and those with bidirectional
propertybeingoneofWS,B,orS.

https://docs.python.org/3/library/stdtypes.html#iteratortypes 22/67
16/12/2016 4.BuiltinTypesPython3.5.2documentation

str. istitle()
Return true if the string is a titlecased string and there is at least one character, for
example uppercase characters may only follow uncased characters and lowercase
charactersonlycasedones.Returnfalseotherwise.

str. isupper()
Returntrueifallcasedcharacters[4]inthestringareuppercaseandthereisatleastone
casedcharacter,falseotherwise.

str. join(iterable)
Return a string which is the concatenation of the strings in the iterable iterable. A
TypeError will be raised if there are any nonstring values in iterable, including bytes
objects.Theseparatorbetweenelementsisthestringprovidingthismethod.

str. ljust(width[,fillchar])
Return the string left justified in a string of length width. Padding is done using the
specifiedfillchar(defaultisanASCIIspace).Theoriginalstringisreturnedifwidthisless
thanorequalto len(s) .

str. lower()
Returnacopyofthestringwithallthecasedcharacters[4]convertedtolowercase.

Thelowercasingalgorithmusedisdescribedinsection3.13oftheUnicodeStandard.

str. lstrip([chars])
Return a copy of the string with leading characters removed. The chars argument is a
string specifying the set of characters to be removed. If omitted or None , the chars
argumentdefaultstoremovingwhitespace.Thecharsargumentisnotaprefixrather,all
combinationsofitsvaluesarestripped:

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

static str. maketrans(x[,y[,z]])


Thisstaticmethodreturnsatranslationtableusablefor str.translate() .

Ifthereisonlyoneargument,itmustbeadictionarymappingUnicodeordinals(integers)
or characters (strings of length 1) to Unicode ordinals, strings (of arbitrary lengths) or
None .Characterkeyswillthenbeconvertedtoordinals.

If there are two arguments, they must be strings of equal length, and in the resulting
dictionary,eachcharacterinxwillbemappedtothecharacteratthesamepositioniny.If
thereisathirdargument,itmustbeastring,whosecharacterswillbemappedto None in
theresult.

str. partition(sep)

https://docs.python.org/3/library/stdtypes.html#iteratortypes 23/67
16/12/2016 4.BuiltinTypesPython3.5.2documentation

Split the string at the first occurrence of sep, and return a 3tuple containing the part
beforetheseparator,theseparatoritself,andthepartaftertheseparator.Iftheseparator
isnotfound,returna3tuplecontainingthestringitself,followedbytwoemptystrings.

str. replace(old,new[,count])
Returnacopyofthestringwithalloccurrencesofsubstringoldreplacedbynew.If the
optionalargumentcountisgiven,onlythefirstcountoccurrencesarereplaced.

str. rfind(sub[,start[,end]])
Return the highest index in the string where substring sub is found, such that sub is
containedwithin s[start:end] .Optionalargumentsstart and end are interpreted as in
slicenotation.Return 1 onfailure.

str. rindex(sub[,start[,end]])
Like rfind() butraises ValueError whenthesubstringsubisnotfound.

str. rjust(width[,fillchar])
Return the string right justified in a string of length width. Padding is done using the
specifiedfillchar(defaultisanASCIIspace).Theoriginalstringisreturnedifwidthisless
thanorequalto len(s) .

str. rpartition(sep)
Split the string at the last occurrence of sep, and return a 3tuple containing the part
beforetheseparator,theseparatoritself,andthepartaftertheseparator.Iftheseparator
isnotfound,returna3tuplecontainingtwoemptystrings,followedbythestringitself.

str. rsplit(sep=None,maxsplit=1)
Return a list of the words in the string, using sep as the delimiter string. If maxsplit is
given,atmostmaxsplitsplitsaredone,therightmostones.Ifsepisnotspecifiedor None ,
any whitespace string is a separator. Except for splitting from the right, rsplit()
behaveslike split() whichisdescribedindetailbelow.

str. rstrip([chars])
Return a copy of the string with trailing characters removed. The chars argument is a
string specifying the set of characters to be removed. If omitted or None , the chars
argumentdefaultstoremovingwhitespace.Thecharsargumentisnotasuffixrather,all
combinationsofitsvaluesarestripped:

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

str. split(sep=None,maxsplit=1)
Return a list of the words in the string, using sep as the delimiter string. If maxsplit is
given, at most maxsplit splits are done (thus, the list will have at most maxsplit+1
elements).Ifmaxsplitisnotspecifiedor 1 ,thenthereisnolimitonthenumberofsplits
(allpossiblesplitsaremade).
https://docs.python.org/3/library/stdtypes.html#iteratortypes 24/67
16/12/2016 4.BuiltinTypesPython3.5.2documentation

Ifsepisgiven,consecutivedelimitersarenotgroupedtogetherandaredeemedtodelimit
empty strings (for example, '1,,2'.split(',') returns ['1', '', '2'] ). The sep
argument may consist of multiple characters (for example, '1<>2<>3'.split('<>')
returns ['1', '2', '3'] ). Splitting an empty string with a specified separator returns
[''] .

Forexample:

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

If sep is not specified or is None , a different splitting algorithm is applied: runs of


consecutivewhitespaceareregardedasasingleseparator,andtheresultwillcontainno
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 a
None separatorreturns [] .

Forexample:

>>>'123'.split() >>>
['1','2','3']
>>>'123'.split(maxsplit=1)
['1','23']
>>>'123'.split()
['1','2','3']

str. splitlines([keepends])
Return a list of the lines in the string, breaking at line boundaries. Line breaks are not
includedintheresultinglistunlesskeependsisgivenandtrue.

This method splits on the following line boundaries. In particular, the boundaries are a
supersetofuniversalnewlines.

Representation Description
\n LineFeed
\r CarriageReturn
\r\n CarriageReturn+Line
Feed
\v or \x0b LineTabulation
\f or \x0c FormFeed
\x1c FileSeparator
\x1d GroupSeparator
\x1e RecordSeparator

https://docs.python.org/3/library/stdtypes.html#iteratortypes 25/67
16/12/2016 4.BuiltinTypesPython3.5.2documentation

Representation Description
\x85 NextLine(C1ControlCode)
\u2028 LineSeparator
\u2029 ParagraphSeparator

Changedinversion3.2: \v and \f addedtolistoflineboundaries.

Forexample:

>>>'abc\n\ndefg\rkl\r\n'.splitlines() >>>
['abc','','defg','kl']
>>>'abc\n\ndefg\rkl\r\n'.splitlines(keepends=True)
['abc\n','\n','defg\r','kl\r\n']

Unlike split() whenadelimiterstringsepisgiven,thismethodreturnsanemptylistfor


theemptystring,andaterminallinebreakdoesnotresultinanextraline:

>>>"".splitlines() >>>
[]
>>>"Oneline\n".splitlines()
['Oneline']

Forcomparison, split('\n') gives:

>>>''.split('\n') >>>
['']
>>>'Twolines\n'.split('\n')
['Twolines','']

str. startswith(prefix[,start[,end]])
Return True if string starts with the prefix, otherwise return False .prefix can also be a
tupleofprefixestolookfor.Withoptionalstart,teststringbeginningatthatposition.With
optionalend,stopcomparingstringatthatposition.

str. strip([chars])
Return a copy of the string with the leading and trailing characters removed.The chars
argument is a string specifying the set of characters to be removed. If omitted or None ,
thecharsargumentdefaultstoremovingwhitespace.Thecharsargumentisnotaprefix
orsuffixrather,allcombinationsofitsvaluesarestripped:

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

The outermost leading and trailing chars argument values are stripped from the string.
Charactersareremovedfromtheleadingenduntilreachingastringcharacterthatisnot
containedinthesetofcharactersinchars.Asimilaractiontakesplaceonthetrailingend.
Forexample:

https://docs.python.org/3/library/stdtypes.html#iteratortypes 26/67
16/12/2016 4.BuiltinTypesPython3.5.2documentation

>>>comment_string='#.......Section3.2.1Issue#32.......' >>>
>>>comment_string.strip('.#!')
'Section3.2.1Issue#32'

str. swapcase()
Return a copy of the string with uppercase characters converted to lowercase and vice
versa.Notethatitisnotnecessarilytruethat s.swapcase().swapcase()==s .

str. title()
Return a titlecased version of the string where words start with an uppercase character
andtheremainingcharactersarelowercase.

Forexample:

>>>'Helloworld'.title() >>>
'HelloWorld'

The algorithm uses a simple languageindependent definition of a word as groups of


consecutiveletters.Thedefinitionworksinmanycontextsbutitmeansthatapostrophes
in contractions and possessives form word boundaries, which may not be the desired
result:

>>>"they'rebill'sfriendsfromtheUK".title() >>>
"They'ReBill'SFriendsFromTheUk"

Aworkaroundforapostrophescanbeconstructedusingregularexpressions:

>>>importre >>>
>>>deftitlecase(s):
...returnre.sub(r"[AZaz]+('[AZaz]+)?",
...lambdamo:mo.group(0)[0].upper()+
...mo.group(0)[1:].lower(),
...s)
...
>>>titlecase("they'rebill'sfriends.")
"They'reBill'sFriends."

str. translate(table)
Returnacopyofthestringinwhicheachcharacterhasbeenmappedthroughthegiven
translation table. The table must be an object that implements indexing via
__getitem__() , typically a mapping or 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,tomapthecharactertooneormoreothercharactersreturn None , to delete the
characterfromthereturnstringorraisea LookupError exception,tomapthecharacter
toitself.

You can use str.maketrans() to create a translation map from charactertocharacter


mappingsindifferentformats.

Seealsothe codecs moduleforamoreflexibleapproachtocustomcharactermappings.

https://docs.python.org/3/library/stdtypes.html#iteratortypes 27/67
16/12/2016 4.BuiltinTypesPython3.5.2documentation

str. upper()
Returnacopyofthestringwithallthecasedcharacters[4]convertedtouppercase.Note
that str.upper().isupper() mightbe False if s containsuncasedcharactersorifthe
Unicodecategoryoftheresultingcharacter(s)isnotLu(Letter,uppercase),bute.g.Lt
(Letter,titlecase).

Theuppercasingalgorithmusedisdescribedinsection3.13oftheUnicodeStandard.

str. zfill(width)
ReturnacopyofthestringleftfilledwithASCII '0' digitstomakeastringoflengthwidth.
A leading sign prefix ( '+' / '' ) is handled by inserting the padding after the sign
characterratherthanbefore.Theoriginalstringisreturnedifwidthislessthanorequalto
len(s) .

Forexample:

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

4.7.2. printf styleStringFormatting

Note: Theformattingoperationsdescribedhereexhibitavarietyofquirksthatleadtoa
numberofcommonerrors(suchasfailingtodisplaytuplesanddictionariescorrectly).
Usingthenewer str.format() interfacehelpsavoidtheseerrors,andalsoprovidesa
generallymorepowerful,flexibleandextensibleapproachtoformattingtext.

Stringobjectshaveoneuniquebuiltinoperation:the % operator(modulo).Thisisalsoknown
asthestringformattingorinterpolationoperator.Given format%values (whereformatisa
string), % conversion specifications in format are replaced with zero or more elements of
values.Theeffectissimilartousingthe sprintf() intheClanguage.

Ifformatrequiresasingleargument,valuesmaybeasinglenontupleobject.[5]Otherwise,
valuesmustbeatuplewithexactlythenumberofitemsspecifiedbytheformatstring,ora
singlemappingobject(forexample,adictionary).

A conversion specifier contains two or more characters and has the following components,
whichmustoccurinthisorder:

1.The '%' character,whichmarksthestartofthespecifier.


2.Mapping key (optional), consisting of a parenthesised sequence of characters (for
example, (somename) ).
3.Conversionflags(optional),whichaffecttheresultofsomeconversiontypes.
4.Minimumfieldwidth(optional).Ifspecifiedasan '*' (asterisk),theactualwidthisread
fromthenextelementofthetupleinvalues,andtheobjecttoconvertcomesafterthe
minimumfieldwidthandoptionalprecision.
5.Precision(optional),givenasa '.' (dot)followedbytheprecision.Ifspecifiedas '*'
(anasterisk),theactualprecisionisreadfromthenextelementofthetupleinvalues,

https://docs.python.org/3/library/stdtypes.html#iteratortypes 28/67
16/12/2016 4.BuiltinTypesPython3.5.2documentation

andthevaluetoconvertcomesaftertheprecision.
6.Lengthmodifier(optional).
7.Conversiontype.

Whentherightargumentisadictionary(orothermappingtype),thentheformatsinthestring
mustincludeaparenthesisedmappingkeyintothatdictionaryinsertedimmediatelyafterthe
'%' character. The mapping key selects the value to be formatted from the mapping. For
example:

>>>
>>>print('%(language)shas%(number)03dquotetypes.'%
...{'language':"Python","number":2})
Pythonhas002quotetypes.

Inthiscaseno * specifiersmayoccurinaformat(sincetheyrequireasequentialparameter
list).

Theconversionflagcharactersare:

Flag Meaning
'#' Thevalueconversionwillusethealternateform(wheredefinedbelow).
'0' Theconversionwillbezeropaddedfornumericvalues.
'' Theconvertedvalueisleftadjusted(overridesthe '0' conversionifbothare
given).
'' (aspace)Ablankshouldbeleftbeforeapositivenumber(oremptystring)
producedbyasignedconversion.
'+' Asigncharacter( '+' or '' )willprecedetheconversion(overridesaspace
flag).

Alengthmodifier( h , l ,or L )maybepresent,butisignoredasitisnotnecessaryforPython


soe.g. %ld isidenticalto %d .

Theconversiontypesare:

Conversion Meaning Notes


'd' Signedintegerdecimal.
'i' Signedintegerdecimal.
'o' Signedoctalvalue. (1)
'u' Obsoletetypeitisidenticalto 'd' . (6)
'x' Signedhexadecimal(lowercase). (2)
'X' Signedhexadecimal(uppercase). (2)
'e' Floatingpointexponentialformat(lowercase). (3)
'E' Floatingpointexponentialformat(uppercase). (3)
'f' Floatingpointdecimalformat. (3)
'F' Floatingpointdecimalformat. (3)

https://docs.python.org/3/library/stdtypes.html#iteratortypes 29/67
16/12/2016 4.BuiltinTypesPython3.5.2documentation

Conversion Meaning Notes


'g' Floatingpointformat.Useslowercaseexponentialformatif (4)
exponentislessthan4ornotlessthanprecision,decimalformat
otherwise.
'G' Floatingpointformat.Usesuppercaseexponentialformatif (4)
exponentislessthan4ornotlessthanprecision,decimalformat
otherwise.
'c' Singlecharacter(acceptsintegerorsinglecharacterstring).
'r' String(convertsanyPythonobjectusing repr() ). (5)
's' String(convertsanyPythonobjectusing str() ). (5)
'a' String(convertsanyPythonobjectusing ascii() ). (5)
'%' Noargumentisconverted,resultsina '%' characterintheresult.

Notes:

1.Thealternateformcausesaleadingoctalspecifier( '0o' )tobeinsertedbeforethefirst


digit.

2.The alternate form causes a leading '0x' or '0X' (depending on whether the 'x' or
'X' formatwasused)tobeinsertedbeforethefirstdigit.

3.Thealternateformcausestheresulttoalwayscontainadecimalpoint,evenifnodigits
followit.

Theprecisiondeterminesthenumberofdigitsafterthedecimalpointanddefaultsto6.

4.The alternate form causes the result to always contain a decimal point, and trailing
zeroesarenotremovedastheywouldotherwisebe.

The precision determines the number of significant digits before and after the decimal
pointanddefaultsto6.

5.Ifprecisionis N ,theoutputistruncatedto N characters.

6.SeePEP237.

SincePythonstringshaveanexplicitlength, %s conversionsdonotassumethat '\0' isthe


endofthestring.

Changedinversion3.1: %f conversionsfornumberswhoseabsolutevalueisover1e50are
nolongerreplacedby %g conversions.

4.8.BinarySequenceTypes bytes , bytearray ,


memoryview
The core builtin types for manipulating binary data are bytes and bytearray . They are
supported by memoryview which uses the buffer protocol to access the memory of other
binaryobjectswithoutneedingtomakeacopy.

https://docs.python.org/3/library/stdtypes.html#iteratortypes 30/67
16/12/2016 4.BuiltinTypesPython3.5.2documentation

The array module supports efficient storage of basic data types like 32bit integers and
IEEE754doubleprecisionfloatingvalues.

4.8.1.Bytes
Bytes objects are immutable sequences of single bytes. Since many major binary protocols
arebasedontheASCIItextencoding,bytesobjectsofferseveralmethodsthatareonlyvalid
whenworkingwithASCIIcompatibledataandarecloselyrelatedtostringobjectsinavariety
ofotherways.

Firstly,thesyntaxforbytesliteralsislargelythesameasthatforstringliterals,exceptthata b
prefixisadded:

Singlequotes: b'stillallowsembedded"double"quotes'
Doublequotes: b"stillallowsembedded'single'quotes" .
Triplequoted: b'''3singlequotes''' , b"""3doublequotes"""

OnlyASCIIcharactersarepermittedinbytesliterals(regardlessofthedeclaredsourcecode
encoding). Any binary values over 127 must be entered into bytes literals using the
appropriateescapesequence.

Aswithstringliterals,bytesliteralsmayalsousea r prefixtodisableprocessingofescape
sequences. See String and Bytes literals for more about the various forms of bytes literal,
includingsupportedescapesequences.

While bytes literals and representations are based on ASCII text, bytes objects actually
behavelikeimmutablesequencesofintegers,witheachvalueinthesequencerestrictedsuch
that 0<=x<256 (attempts to violate this restriction will trigger ValueError . This is done
deliberatelytoemphasisethatwhilemanybinaryformatsincludeASCIIbasedelementsand
canbeusefullymanipulatedwithsometextorientedalgorithms,thisisnotgenerallythecase
forarbitrarybinarydata(blindlyapplyingtextprocessingalgorithmstobinarydataformatsthat
arenotASCIIcompatiblewillusuallyleadtodatacorruption).

Inadditiontotheliteralforms,bytesobjectscanbecreatedinanumberofotherways:

Azerofilledbytesobjectofaspecifiedlength: bytes(10)
Fromaniterableofintegers: bytes(range(20))
Copyingexistingbinarydataviathebufferprotocol: bytes(obj)

Alsoseethebytesbuiltin.

Since2hexadecimaldigitscorrespondpreciselytoasinglebyte,hexadecimalnumbersarea
commonly used format for describing binary data. Accordingly, the bytes type has an
additionalclassmethodtoreaddatainthatformat:

classmethod bytes. fromhex(string)


This bytes class method returns a bytes object, decoding the given string object. The
stringmustcontaintwohexadecimaldigitsperbyte,withASCIIspacesbeingignored.

https://docs.python.org/3/library/stdtypes.html#iteratortypes 31/67
16/12/2016 4.BuiltinTypesPython3.5.2documentation

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

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

bytes. hex()
Returnastringobjectcontainingtwohexadecimaldigitsforeachbyteintheinstance.

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

Newinversion3.5.

Sincebytesobjectsaresequencesofintegers(akintoatuple),forabytesobjectb, b[0] will


beaninteger,while b[0:1] willbeabytesobjectoflength1.(Thiscontrastswithtextstrings,
wherebothindexingandslicingwillproduceastringoflength1)

The representation of bytes objects uses the literal format ( b'...' ) since it is often more
usefulthane.g. bytes([46,46,46]) .Youcanalwaysconvert a bytes object into a list of
integersusing list(b) .

Note: ForPython2.xusers:InthePython2.xseries,avarietyofimplicitconversions
between8bitstrings(theclosestthing2.xofferstoabuiltinbinarydatatype)andUnicode
stringswerepermitted.Thiswasabackwardscompatibilityworkaroundtoaccountforthe
factthatPythonoriginallyonlysupported8bittext,andUnicodetextwasalateraddition.In
Python3.x,thoseimplicitconversionsaregoneconversionsbetween8bitbinarydataand
Unicodetextmustbeexplicit,andbytesandstringobjectswillalwayscompareunequal.

4.8.2.BytearrayObjects

bytearray objectsareamutablecounterpartto bytes objects.Thereisnodedicatedliteral


syntaxforbytearrayobjects,insteadtheyarealwayscreatedbycallingtheconstructor:

Creatinganemptyinstance: bytearray()
Creatingazerofilledinstancewithagivenlength: bytearray(10)
Fromaniterableofintegers: bytearray(range(20))
Copyingexistingbinarydataviathebufferprotocol: bytearray(b'Hi!')

Asbytearrayobjectsaremutable,theysupportthemutablesequenceoperationsinaddition
tothecommonbytesandbytearrayoperationsdescribedinBytesandBytearrayOperations.

Alsoseethebytearraybuiltin.

Since2hexadecimaldigitscorrespondpreciselytoasinglebyte,hexadecimalnumbersarea
commonly used format for describing binary data. Accordingly, the bytearray type has an
additionalclassmethodtoreaddatainthatformat:

classmethod bytearray. fromhex(string)

https://docs.python.org/3/library/stdtypes.html#iteratortypes 32/67
16/12/2016 4.BuiltinTypesPython3.5.2documentation

This bytearray classmethodreturnsbytearrayobject,decodingthegivenstringobject.


The string must contain two hexadecimal digits per byte, with ASCII spaces being
ignored.

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

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

bytearray. hex()
Returnastringobjectcontainingtwohexadecimaldigitsforeachbyteintheinstance.

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

Newinversion3.5.

Since bytearray objects are sequences of integers (akin to a list), for a bytearray object b,
b[0] will be an integer, while b[0:1] will be a bytearray object of length 1. (This contrasts
withtextstrings,wherebothindexingandslicingwillproduceastringoflength1)

The representation of bytearray objects uses the bytes literal format ( bytearray(b'...') )
sinceitisoftenmoreusefulthane.g. bytearray([46,46,46]) .Youcanalwaysconverta
bytearrayobjectintoalistofintegersusing list(b) .

4.8.3.BytesandBytearrayOperations

Both bytes and bytearray objects support the common sequence operations. They
interoperate not just with operands of the same type, but with any byteslike object. Due to
this flexibility, they can be freely mixed in operations without causing errors. However, the
returntypeoftheresultmaydependontheorderofoperands.

Note: Themethodsonbytesandbytearrayobjectsdontacceptstringsastheir
arguments,justasthemethodsonstringsdontacceptbytesastheirarguments.For
example,youhavetowrite:

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,
andhenceshouldbeavoidedwhenworkingwitharbitrarybinarydata.Theserestrictionsare
coveredbelow.

https://docs.python.org/3/library/stdtypes.html#iteratortypes 33/67
16/12/2016 4.BuiltinTypesPython3.5.2documentation

Note: UsingtheseASCIIbasedoperationstomanipulatebinarydatathatisnotstoredin
anASCIIbasedformatmayleadtodatacorruption.

Thefollowingmethodsonbytesandbytearrayobjectscanbeusedwitharbitrarybinarydata.

bytes. count(sub[,start[,end]])
bytearray. count(sub[,start[,end]])
Return the number of nonoverlapping occurrences of subsequence sub in the range
[start,end].Optionalargumentsstartandendareinterpretedasinslicenotation.

Thesubsequencetosearchformaybeanybyteslikeobjectoranintegerintherange0
to255.

Changedinversion3.3:Alsoacceptanintegerintherange0to255asthesubsequence.

bytes. decode(encoding="utf8",errors="strict")
bytearray. decode(encoding="utf8",errors="strict")
Returnastringdecodedfromthegivenbytes.Default encoding is 'utf8' .errors may
be given to set a different error handling scheme. The default for errors is 'strict' ,
meaning that encoding errors raise a UnicodeError . Other possible values are
'ignore' , 'replace' and any other name registered via codecs.register_error() ,
see section Error Handlers. For a list of possible encodings, see section Standard
Encodings.

Note: Passing the encoding argument to str allows decoding any byteslike object
directly,withoutneedingtomakeatemporarybytesorbytearrayobject.

Changedinversion3.1:Addedsupportforkeywordarguments.

bytes. endswith(suffix[,start[,end]])
bytearray. endswith(suffix[,start[,end]])
Return True if the binary data ends with the specified suffix, otherwise return False .
suffixcanalsobeatupleofsuffixestolookfor.Withoptionalstart,testbeginningatthat
position.Withoptionalend,stopcomparingatthatposition.

Thesuffix(es)tosearchformaybeanybyteslikeobject.

bytes. find(sub[,start[,end]])
bytearray. find(sub[,start[,end]])
Returnthelowestindexinthedatawherethesubsequencesubisfound,suchthatsubis
containedintheslice s[start:end] .Optionalargumentsstartandendareinterpretedas
inslicenotation.Return 1 ifsubisnotfound.

Thesubsequencetosearchformaybeanybyteslikeobjectoranintegerintherange0
to255.

Note: The find() method should be used only if you need to know the position of
sub.Tocheckifsubisasubstringornot,usethe in operator:
https://docs.python.org/3/library/stdtypes.html#iteratortypes 34/67
16/12/2016 4.BuiltinTypesPython3.5.2documentation

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

Changedinversion3.3:Alsoacceptanintegerintherange0to255asthesubsequence.

bytes. index(sub[,start[,end]])
bytearray. index(sub[,start[,end]])
Like find() ,butraise ValueError whenthesubsequenceisnotfound.

Thesubsequencetosearchformaybeanybyteslikeobjectoranintegerintherange0
to255.

Changedinversion3.3:Alsoacceptanintegerintherange0to255asthesubsequence.

bytes. join(iterable)
bytearray. join(iterable)
Return a bytes or bytearray object which is the concatenation of the binary data
sequencesintheiterableiterable.A TypeError will be raised if there are any values in
iterable that are not byteslike objects, including str objects. The separator between
elementsisthecontentsofthebytesorbytearrayobjectprovidingthismethod.

static bytes. maketrans(from,to)


static bytearray. maketrans(from,to)
Thisstaticmethodreturnsatranslationtableusablefor bytes.translate() thatwillmap
eachcharacterinfromintothecharacteratthesamepositionintofromandtomustboth
bebyteslikeobjectsandhavethesamelength.

Newinversion3.1.

bytes. partition(sep)
bytearray. partition(sep)
Splitthesequenceatthefirstoccurrenceofsep,andreturna3tuplecontainingthepart
beforetheseparator,theseparator,andthepartaftertheseparator.Iftheseparatorisnot
found,returna3tuplecontainingacopyoftheoriginalsequence,followedbytwoempty
bytesorbytearrayobjects.

Theseparatortosearchformaybeanybyteslikeobject.

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

Thesubsequencetosearchforanditsreplacementmaybeanybyteslikeobject.

Note: The bytearray version of this method does not operate in place it always
producesanewobject,evenifnochangesweremade.

https://docs.python.org/3/library/stdtypes.html#iteratortypes 35/67
16/12/2016 4.BuiltinTypesPython3.5.2documentation

bytes. rfind(sub[,start[,end]])
bytearray. rfind(sub[,start[,end]])
Returnthehighestindexinthesequencewherethesubsequencesubisfound,suchthat
subiscontainedwithin s[start:end] .Optionalargumentsstartandendareinterpreted
asinslicenotation.Return 1 onfailure.

Thesubsequencetosearchformaybeanybyteslikeobjectoranintegerintherange0
to255.

Changedinversion3.3:Alsoacceptanintegerintherange0to255asthesubsequence.

bytes. rindex(sub[,start[,end]])
bytearray. rindex(sub[,start[,end]])
Like rfind() butraises ValueError whenthesubsequencesubisnotfound.

Thesubsequencetosearchformaybeanybyteslikeobjectoranintegerintherange0
to255.

Changedinversion3.3:Alsoacceptanintegerintherange0to255asthesubsequence.

bytes. rpartition(sep)
bytearray. rpartition(sep)
Splitthesequenceatthelastoccurrenceofsep,andreturna3tuplecontainingthepart
beforetheseparator,theseparator,andthepartaftertheseparator.Iftheseparatorisnot
found,returna3tuplecontainingacopyoftheoriginalsequence,followedbytwoempty
bytesorbytearrayobjects.

Theseparatortosearchformaybeanybyteslikeobject.

bytes. startswith(prefix[,start[,end]])
bytearray. startswith(prefix[,start[,end]])
Return True if the binary data starts with the specified prefix, otherwise return False .
prefixcanalsobeatupleofprefixestolookfor.Withoptionalstart,testbeginningatthat
position.Withoptionalend,stopcomparingatthatposition.

Theprefix(es)tosearchformaybeanybyteslikeobject.

bytes. translate(table[,delete])
bytearray. translate(table[,delete])
Return a copy of the bytes or bytearray object where all bytes occurring in the optional
argumentdelete are removed, and the remaining bytes have been mapped through the
giventranslationtable,whichmustbeabytesobjectoflength256.

Youcanusethe bytes.maketrans() methodtocreateatranslationtable.

Setthetableargumentto None fortranslationsthatonlydeletecharacters:

>>>b'readthisshorttext'.translate(None,b'aeiou') >>>
b'rdthsshrttxt'

https://docs.python.org/3/library/stdtypes.html#iteratortypes 36/67
16/12/2016 4.BuiltinTypesPython3.5.2documentation

Thefollowingmethodsonbytesandbytearrayobjectshavedefaultbehavioursthatassume
theuseofASCIIcompatiblebinaryformats,butcanstillbeusedwitharbitrarybinarydataby
passingappropriatearguments.Notethatallofthebytearraymethodsinthissectiondonot
operateinplace,andinsteadproducenewobjects.

bytes. center(width[,fillbyte])
bytearray. center(width[,fillbyte])
Return a copy of the object centered in a sequence of length width. Padding is done
using the specified fillbyte (default is an ASCII space). For bytes objects, the original
sequenceisreturnedifwidthislessthanorequalto len(s) .

Note: The bytearray version of this method does not operate in place it always
producesanewobject,evenifnochangesweremade.

bytes. ljust(width[,fillbyte])
bytearray. ljust(width[,fillbyte])
Returnacopyoftheobjectleftjustifiedinasequenceoflengthwidth.Paddingisdone
using the specified fillbyte (default is an ASCII space). For bytes objects, the original
sequenceisreturnedifwidthislessthanorequalto len(s) .

Note: The bytearray version of this method does not operate in place it always
producesanewobject,evenifnochangesweremade.

bytes. lstrip([chars])
bytearray. lstrip([chars])
Return a copy of the sequence with specified leading bytes removed. The chars
argument is a binary sequence specifying the set of byte values to be removed the
name refers to the fact this method is usually used withASCII characters. If omitted or
None ,thecharsargumentdefaultstoremovingASCIIwhitespace.Thecharsargumentis
notaprefixrather,allcombinationsofitsvaluesarestripped:

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

Thebinarysequenceofbytevaluestoremovemaybeanybyteslikeobject.

Note: The bytearray version of this method does not operate in place it always
producesanewobject,evenifnochangesweremade.

bytes. rjust(width[,fillbyte])
bytearray. rjust(width[,fillbyte])
Returnacopyoftheobjectrightjustifiedinasequenceoflengthwidth.Paddingisdone
using the specified fillbyte (default is an ASCII space). For bytes objects, the original
sequenceisreturnedifwidthislessthanorequalto len(s) .

https://docs.python.org/3/library/stdtypes.html#iteratortypes 37/67
16/12/2016 4.BuiltinTypesPython3.5.2documentation

Note: The bytearray version of this method does not operate in place it always
producesanewobject,evenifnochangesweremade.

bytes. rsplit(sep=None,maxsplit=1)
bytearray. rsplit(sep=None,maxsplit=1)
Splitthebinarysequenceintosubsequencesofthesametype,usingsepasthedelimiter
string.Ifmaxsplitisgiven,atmostmaxsplitsplitsaredone,therightmostones.Ifsep is
not specified or None , any subsequence consisting solely of ASCII whitespace is a
separator. Except for splitting from the right, rsplit() behaves like split() which is
describedindetailbelow.

bytes. rstrip([chars])
bytearray. rstrip([chars])
Returnacopyofthesequencewithspecifiedtrailingbytesremoved.Thecharsargument
isabinarysequencespecifyingthesetofbytevaluestoberemovedthenamerefersto
thefactthismethodisusuallyusedwithASCIIcharacters.Ifomittedor None ,thechars
argument defaults to removing ASCII whitespace. The chars argument is not a suffix
rather,allcombinationsofitsvaluesarestripped:

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

Thebinarysequenceofbytevaluestoremovemaybeanybyteslikeobject.

Note: The bytearray version of this method does not operate in place it always
producesanewobject,evenifnochangesweremade.

bytes. split(sep=None,maxsplit=1)
bytearray. split(sep=None,maxsplit=1)
Splitthebinarysequenceintosubsequencesofthesametype,usingsepasthedelimiter
string.Ifmaxsplitisgivenandnonnegative,atmostmaxsplitsplitsaredone(thus,thelist
willhaveatmost maxsplit+1 elements).Ifmaxsplitisnotspecifiedoris 1 ,thenthereis
nolimitonthenumberofsplits(allpossiblesplitsaremade).

Ifsepisgiven,consecutivedelimitersarenotgroupedtogetherandaredeemedtodelimit
emptysubsequences(forexample, b'1,,2'.split(b',') returns [b'1',b'',b'2'] ).
The sep argument may consist of a multibyte sequence (for example,
b'1<>2<>3'.split(b'<>') returns [b'1',b'2',b'3'] ).Splittinganemptysequence
withaspecifiedseparatorreturns [b''] or [bytearray(b'')] dependingonthetypeof
objectbeingsplit.Thesepargumentmaybeanybyteslikeobject.

Forexample:

>>>b'1,2,3'.split(b',') >>>
[b'1',b'2',b'3']
>>>b'1,2,3'.split(b',',maxsplit=1)
https://docs.python.org/3/library/stdtypes.html#iteratortypes 38/67
16/12/2016 4.BuiltinTypesPython3.5.2documentation

[b'1',b'2,3']
>>>b'1,2,,3,'.split(b',')
[b'1',b'2',b'',b'3',b'']

If sep is not specified or is None , 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
ofASCIIwhitespacewithoutaspecifiedseparatorreturns [] .

Forexample:

>>>b'123'.split() >>>
[b'1',b'2',b'3']
>>>b'123'.split(maxsplit=1)
[b'1',b'23']
>>>b'123'.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. The
chars argument is a binary sequence specifying the set of byte values to be removed
thenamereferstothefactthismethodisusuallyusedwithASCIIcharacters.Ifomittedor
None ,thecharsargumentdefaultstoremovingASCIIwhitespace.Thecharsargumentis
notaprefixorsuffixrather,allcombinationsofitsvaluesarestripped:

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

Thebinarysequenceofbytevaluestoremovemaybeanybyteslikeobject.

Note: The bytearray version of this method does not operate in place it always
producesanewobject,evenifnochangesweremade.

ThefollowingmethodsonbytesandbytearrayobjectsassumetheuseofASCIIcompatible
binaryformatsandshouldnotbeappliedtoarbitrarybinarydata.Notethatallofthebytearray
methodsinthissectiondonotoperateinplace,andinsteadproducenewobjects.

bytes. capitalize()
bytearray. capitalize()
ReturnacopyofthesequencewitheachbyteinterpretedasanASCIIcharacter,andthe
firstbytecapitalizedandtherestlowercased.NonASCIIbytevaluesarepassedthrough
unchanged.

Note: The bytearray version of this method does not operate in place it always
producesanewobject,evenifnochangesweremade.

https://docs.python.org/3/library/stdtypes.html#iteratortypes 39/67
16/12/2016 4.BuiltinTypesPython3.5.2documentation

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
positionsoccureverytabsizebytes(defaultis8,givingtabpositionsatcolumns0,8,16
andsoon).Toexpandthesequence,thecurrentcolumnissettozeroandthesequence
is examined byte by byte. If the byte is an ASCII tab character ( b'\t' ), one or more
spacecharactersareinsertedintheresultuntilthecurrentcolumnisequaltothenexttab
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.
Anyotherbytevalueiscopiedunchangedandthecurrentcolumnisincrementedbyone
regardlessofhowthebytevalueisrepresentedwhenprinted:

>>>b'01\t012\t0123\t01234'.expandtabs() >>>
b'01012012301234'
>>>b'01\t012\t0123\t01234'.expandtabs(4)
b'01012012301234'

Note: The bytearray version of this method does not operate in place it always
producesanewobject,evenifnochangesweremade.

bytes. isalnum()
bytearray. isalnum()
Return true if all bytes in the sequence are alphabetical ASCII characters or ASCII
decimal digits and the sequence is not empty, false otherwise. Alphabetic ASCII
characters are those byte values in the sequence
b'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' . ASCII decimal digits
arethosebytevaluesinthesequence b'0123456789' .

Forexample:

>>>b'ABCabc1'.isalnum() >>>
True
>>>b'ABCabc1'.isalnum()
False

bytes. isalpha()
bytearray. isalpha()
ReturntrueifallbytesinthesequencearealphabeticASCIIcharactersandthesequence
is not empty, false otherwise. Alphabetic ASCII characters are those byte values in the
sequence b'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' .

Forexample:

>>>b'ABCabc'.isalpha() >>>
True
>>>b'ABCabc1'.isalpha()
False

https://docs.python.org/3/library/stdtypes.html#iteratortypes 40/67
16/12/2016 4.BuiltinTypesPython3.5.2documentation

bytes. isdigit()
bytearray. isdigit()
ReturntrueifallbytesinthesequenceareASCIIdecimaldigitsandthesequenceisnot
empty, false otherwise. ASCII decimal digits are those byte values in the sequence
b'0123456789' .

Forexample:

>>>b'1234'.isdigit() >>>
True
>>>b'1.23'.isdigit()
False

bytes. islower()
bytearray. islower()
Return true if there is at least one lowercase ASCII character in the sequence and no
uppercaseASCIIcharacters,falseotherwise.

Forexample:

>>>b'helloworld'.islower() >>>
True
>>>b'Helloworld'.islower()
False

Lowercase ASCII characters are those byte values in the sequence


b'abcdefghijklmnopqrstuvwxyz' .UppercaseASCIIcharactersarethosebytevaluesin
thesequence b'ABCDEFGHIJKLMNOPQRSTUVWXYZ' .

bytes. isspace()
bytearray. isspace()
Return true if all bytes in the sequence are ASCII whitespace and the sequence is not
empty, false otherwise. ASCII whitespace characters are those byte values in the
sequence b' \t\n\r\x0b\f' (space, tab, newline, carriage return, vertical tab, form
feed).

bytes. istitle()
bytearray. istitle()
Return true if the sequence is ASCII titlecase and the sequence is not empty, false
otherwise.See bytes.title() formoredetailsonthedefinitionoftitlecase.

Forexample:

>>>b'HelloWorld'.istitle() >>>
True
>>>b'Helloworld'.istitle()
False

bytes. isupper()
bytearray. isupper()
https://docs.python.org/3/library/stdtypes.html#iteratortypes 41/67
16/12/2016 4.BuiltinTypesPython3.5.2documentation

ReturntrueifthereisatleastoneuppercasealphabeticASCIIcharacterinthesequence
andnolowercaseASCIIcharacters,falseotherwise.

Forexample:

>>>b'HELLOWORLD'.isupper() >>>
True
>>>b'Helloworld'.isupper()
False

Lowercase ASCII characters are those byte values in the sequence


b'abcdefghijklmnopqrstuvwxyz' .UppercaseASCIIcharactersarethosebytevaluesin
thesequence b'ABCDEFGHIJKLMNOPQRSTUVWXYZ' .

bytes. lower()
bytearray. lower()
ReturnacopyofthesequencewithalltheuppercaseASCIIcharactersconvertedtotheir
correspondinglowercasecounterpart.

Forexample:

>>>b'HelloWorld'.lower() >>>
b'helloworld'

Lowercase ASCII characters are those byte values in the sequence


b'abcdefghijklmnopqrstuvwxyz' .UppercaseASCIIcharactersarethosebytevaluesin
thesequence b'ABCDEFGHIJKLMNOPQRSTUVWXYZ' .

Note: The bytearray version of this method does not operate in place it always
producesanewobject,evenifnochangesweremade.

bytes. splitlines(keepends=False)
bytearray. splitlines(keepends=False)
Returnalistofthelinesinthebinarysequence,breakingatASCIIlineboundaries.This
method uses the universal newlines approach to splitting lines. Line breaks are not
includedintheresultinglistunlesskeependsisgivenandtrue.

Forexample:

>>>b'abc\n\ndefg\rkl\r\n'.splitlines() >>>
[b'abc',b'',b'defg',b'kl']
>>>b'abc\n\ndefg\rkl\r\n'.splitlines(keepends=True)
[b'abc\n',b'\n',b'defg\r',b'kl\r\n']

Unlike split() whenadelimiterstringsepisgiven,thismethodreturnsanemptylistfor


theemptystring,andaterminallinebreakdoesnotresultinanextraline:

>>>b"".split(b'\n'),b"Twolines\n".split(b'\n') >>>
([b''],[b'Twolines',b''])

https://docs.python.org/3/library/stdtypes.html#iteratortypes 42/67
16/12/2016 4.BuiltinTypesPython3.5.2documentation

>>>b"".splitlines(),b"Oneline\n".splitlines()
([],[b'Oneline'])

bytes. swapcase()
bytearray. swapcase()
ReturnacopyofthesequencewithallthelowercaseASCIIcharactersconvertedtotheir
correspondinguppercasecounterpartandviceversa.

Forexample:

>>>b'HelloWorld'.swapcase() >>>
b'hELLOwORLD'

Lowercase ASCII characters are those byte values in the sequence


b'abcdefghijklmnopqrstuvwxyz' .UppercaseASCIIcharactersarethosebytevaluesin
thesequence b'ABCDEFGHIJKLMNOPQRSTUVWXYZ' .

Unlike str.swapcase() ,itisalwaysthecasethat bin.swapcase().swapcase()==bin


forthebinaryversions.CaseconversionsaresymmetricalinASCII,eventhoughthatis
notgenerallytrueforarbitraryUnicodecodepoints.

Note: The bytearray version of this method does not operate in place it always
producesanewobject,evenifnochangesweremade.

bytes. title()
bytearray. title()
Returnatitlecasedversionofthebinarysequencewherewordsstartwithanuppercase
ASCII character and the remaining characters are lowercase. Uncased byte values are
leftunmodified.

Forexample:

>>>b'Helloworld'.title() >>>
b'HelloWorld'

Lowercase ASCII characters are those byte values in the sequence


b'abcdefghijklmnopqrstuvwxyz' .UppercaseASCIIcharactersarethosebytevaluesin
thesequence b'ABCDEFGHIJKLMNOPQRSTUVWXYZ' .Allotherbytevaluesareuncased.

The algorithm uses a simple languageindependent definition of a word as groups of


consecutiveletters.Thedefinitionworksinmanycontextsbutitmeansthatapostrophes
in contractions and possessives form word boundaries, which may not be the desired
result:

>>>b"they'rebill'sfriendsfromtheUK".title() >>>
b"They'ReBill'SFriendsFromTheUk"

Aworkaroundforapostrophescanbeconstructedusingregularexpressions:

https://docs.python.org/3/library/stdtypes.html#iteratortypes 43/67
16/12/2016 4.BuiltinTypesPython3.5.2documentation

>>>importre >>>
>>>deftitlecase(s):
...returnre.sub(rb"[AZaz]+('[AZaz]+)?",
...lambdamo:mo.group(0)[0:1].upper()+
...mo.group(0)[1:].lower(),
...s)
...
>>>titlecase(b"they'rebill'sfriends.")
b"They'reBill'sFriends."

Note: The bytearray version of this method does not operate in place it always
producesanewobject,evenifnochangesweremade.

bytes. upper()
bytearray. upper()
ReturnacopyofthesequencewithallthelowercaseASCIIcharactersconvertedtotheir
correspondinguppercasecounterpart.

Forexample:

>>>b'HelloWorld'.upper() >>>
b'HELLOWORLD'

Lowercase ASCII characters are those byte values in the sequence


b'abcdefghijklmnopqrstuvwxyz' .UppercaseASCIIcharactersarethosebytevaluesin
thesequence b'ABCDEFGHIJKLMNOPQRSTUVWXYZ' .

Note: The bytearray version of this method does not operate in place it always
producesanewobject,evenifnochangesweremade.

bytes. zfill(width)
bytearray. zfill(width)
Returnacopyofthe sequence left filled with ASCII b'0' digits to make a sequence of
lengthwidth.Aleadingsignprefix( b'+' / b'' ishandledbyinsertingthepaddingafter
the sign character rather than before. For bytes objects, the original sequence is
returnedifwidthislessthanorequalto len(seq) .

Forexample:

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

Note: The bytearray version of this method does not operate in place it always
producesanewobject,evenifnochangesweremade.

4.8.4. printf styleBytesFormatting


https://docs.python.org/3/library/stdtypes.html#iteratortypes 44/67
16/12/2016 4.BuiltinTypesPython3.5.2documentation

Note: Theformattingoperationsdescribedhereexhibitavarietyofquirksthatleadtoa
numberofcommonerrors(suchasfailingtodisplaytuplesanddictionariescorrectly).Ifthe
valuebeingprintedmaybeatupleordictionary,wrapitinatuple.

Bytesobjects( bytes / bytearray )haveoneuniquebuiltinoperation:the % operator(modulo).


Thisisalsoknownasthebytesformattingorinterpolationoperator.Given format%values
(whereformatisabytesobject), % conversionspecificationsinformatarereplacedwithzero
ormoreelementsofvalues.Theeffectissimilartousingthe sprintf() intheClanguage.

Ifformatrequiresasingleargument,valuesmaybeasinglenontupleobject.[5]Otherwise,
valuesmustbeatuplewithexactlythenumberofitemsspecifiedbytheformatbytesobject,
orasinglemappingobject(forexample,adictionary).

A conversion specifier contains two or more characters and has the following components,
whichmustoccurinthisorder:

1.The '%' character,whichmarksthestartofthespecifier.


2.Mapping key (optional), consisting of a parenthesised sequence of characters (for
example, (somename) ).
3.Conversionflags(optional),whichaffecttheresultofsomeconversiontypes.
4.Minimumfieldwidth(optional).Ifspecifiedasan '*' (asterisk),theactualwidthisread
fromthenextelementofthetupleinvalues,andtheobjecttoconvertcomesafterthe
minimumfieldwidthandoptionalprecision.
5.Precision(optional),givenasa '.' (dot)followedbytheprecision.Ifspecifiedas '*'
(anasterisk),theactualprecisionisreadfromthenextelementofthetupleinvalues,
andthevaluetoconvertcomesaftertheprecision.
6.Lengthmodifier(optional).
7.Conversiontype.

Whentherightargumentisadictionary(orothermappingtype),thentheformatsinthebytes
object must include a parenthesised mapping key into that dictionary inserted immediately
afterthe '%' character.Themappingkeyselectsthevaluetobeformattedfromthemapping.
Forexample:

>>>
>>>print(b'%(language)shas%(number)03dquotetypes.'%
...{b'language':b"Python",b"number":2})
b'Pythonhas002quotetypes.'

Inthiscaseno * specifiersmayoccurinaformat(sincetheyrequireasequentialparameter
list).

Theconversionflagcharactersare:

Flag Meaning
'#' Thevalueconversionwillusethealternateform(wheredefinedbelow).
'0' Theconversionwillbezeropaddedfornumericvalues.
'' Theconvertedvalueisleftadjusted(overridesthe '0' conversionifbothare
given).

https://docs.python.org/3/library/stdtypes.html#iteratortypes 45/67
16/12/2016 4.BuiltinTypesPython3.5.2documentation

Flag Meaning
'' (aspace)Ablankshouldbeleftbeforeapositivenumber(oremptystring)
producedbyasignedconversion.
'+' Asigncharacter( '+' or '' )willprecedetheconversion(overridesaspace
flag).

Alengthmodifier( h , l ,or L )maybepresent,butisignoredasitisnotnecessaryforPython


soe.g. %ld isidenticalto %d .

Theconversiontypesare:

Conversion Meaning Notes


'd' Signedintegerdecimal.
'i' Signedintegerdecimal.
'o' Signedoctalvalue. (1)
'u' Obsoletetypeitisidenticalto 'd' . (8)
'x' Signedhexadecimal(lowercase). (2)
'X' Signedhexadecimal(uppercase). (2)
'e' Floatingpointexponentialformat(lowercase). (3)
'E' Floatingpointexponentialformat(uppercase). (3)
'f' Floatingpointdecimalformat. (3)
'F' Floatingpointdecimalformat. (3)
'g' Floatingpointformat.Useslowercaseexponentialformatif (4)
exponentislessthan4ornotlessthanprecision,decimalformat
otherwise.
'G' Floatingpointformat.Usesuppercaseexponentialformatif (4)
exponentislessthan4ornotlessthanprecision,decimalformat
otherwise.
'c' Singlebyte(acceptsintegerorsinglebyteobjects).
'b' Bytes(anyobjectthatfollowsthebufferprotocolorhas (5)
__bytes__() ).
's' 's' isanaliasfor 'b' andshouldonlybeusedforPython2/3 (6)
codebases.
'a' Bytes(convertsanyPythonobjectusing (5)
repr(obj).encode('ascii','backslashreplace) ).
'r' 'r' isanaliasfor 'a' andshouldonlybeusedforPython2/3 (7)
codebases.
'%' Noargumentisconverted,resultsina '%' characterintheresult.

Notes:

1.Thealternateformcausesaleadingoctalspecifier( '0o' )tobeinsertedbeforethefirst


digit.

https://docs.python.org/3/library/stdtypes.html#iteratortypes 46/67
16/12/2016 4.BuiltinTypesPython3.5.2documentation

2.The alternate form causes a leading '0x' or '0X' (depending on whether the 'x' or
'X' formatwasused)tobeinsertedbeforethefirstdigit.

3.Thealternateformcausestheresulttoalwayscontainadecimalpoint,evenifnodigits
followit.

Theprecisiondeterminesthenumberofdigitsafterthedecimalpointanddefaultsto6.

4.The alternate form causes the result to always contain a decimal point, and trailing
zeroesarenotremovedastheywouldotherwisebe.

The precision determines the number of significant digits before and after the decimal
pointanddefaultsto6.

5.Ifprecisionis N ,theoutputistruncatedto N characters.

6. b'%s' isdeprecated,butwillnotberemovedduringthe3.xseries.

7. b'%r' isdeprecated,butwillnotberemovedduringthe3.xseries.

8.SeePEP237.

Note: Thebytearrayversionofthismethoddoesnotoperateinplaceitalwaysproduces
anewobject,evenifnochangesweremade.

Seealso: PEP461.

Newinversion3.5.

4.8.5.MemoryViews
memoryview objectsallowPythoncodetoaccesstheinternaldataofanobjectthatsupports
thebufferprotocolwithoutcopying.

class memoryview(obj)
Create a memoryview that references obj. obj must support the buffer protocol. Builtin
objectsthatsupportthebufferprotocolinclude bytes and bytearray .

A memoryview hasthenotionofanelement,whichistheatomicmemoryunithandledby
the originating object obj. For many simple types such as bytes and bytearray , an
element is a single byte, but other types such as array.array may have bigger
elements.

len(view) is equal to the length of tolist . If view.ndim = 0 , the length is 1. If


view.ndim = 1 , the length is equal to the number of elements in the view. For higher
dimensions,thelengthisequaltothelengthofthenestedlistrepresentationoftheview.
The itemsize attributewillgiveyouthenumberofbytesinasingleelement.

A memoryview supportsslicingandindexingtoexposeitsdata.Onedimensionalslicing
willresultinasubview:
https://docs.python.org/3/library/stdtypes.html#iteratortypes 47/67
16/12/2016 4.BuiltinTypesPython3.5.2documentation

>>>v=memoryview(b'abcefg') >>>
>>>v[1]
98
>>>v[1]
103
>>>v[1:4]
<memoryat0x7f3ddc9f4350>
>>>bytes(v[1:4])
b'bce'

If format isoneofthenativeformatspecifiersfromthe struct module,indexingwithan


integer or a tuple of integers is also supported and returns a single element with the
correct type. Onedimensional memoryviews can be indexed with an integer or a one
integertuple.Multidimensionalmemoryviewscanbeindexedwithtuplesofexactlyndim
integers where ndim is the number of dimensions. Zerodimensional memoryviews can
beindexedwiththeemptytuple.

Hereisanexamplewithanonbyteformat:

>>>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 onedimensional slice


assignment.Resizingisnotallowed:

>>>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(mostrecentcalllast):
File"<stdin>",line1,in<module>
ValueError:memoryviewassignment:lvalueandrvaluehavedifferentstructures
>>>v[2:6]=b'spam'
>>>data
bytearray(b'z1spam')

Onedimensional memoryviews of hashable (readonly) types with formats B, b or c


arealsohashable.Thehashisdefinedas hash(m)==hash(m.tobytes()) :

https://docs.python.org/3/library/stdtypes.html#iteratortypes 48/67
16/12/2016 4.BuiltinTypesPython3.5.2documentation

>>>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: Onedimensional memoryviews can now be sliced. One


dimensionalmemoryviewswithformatsB,borcarenowhashable.

Changed in version 3.4: memoryview is now registered automatically with


collections.abc.Sequence

Changedinversion3.5:memoryviewscannowbeindexedwithtupleofintegers.

memoryview hasseveralmethods:

__eq__(exporter)
AmemoryviewandaPEP3118exporterareequaliftheirshapesareequivalentand
ifallcorrespondingvaluesareequalwhentheoperandsrespectiveformatcodesare
interpretedusing struct syntax.

For the subset of struct format strings currently supported by tolist() , v and w
areequalif v.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 the struct module, 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
https://docs.python.org/3/library/stdtypes.html#iteratortypes 49/67
16/12/2016 4.BuiltinTypesPython3.5.2documentation

False
>>>a==b
False

Note that, as with floating point numbers, v is w does not imply v == w for
memoryviewobjects.

Changed in version 3.3: Previous versions compared the raw memory disregarding
theitemformatandthelogicalarraystructure.

tobytes()
Returnthedatainthebufferasabytestring.Thisisequivalenttocallingthe bytes
constructoronthememoryview.

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

Fornoncontiguousarraystheresultisequaltotheflattenedlistrepresentationwith
all elements converted to bytes. tobytes() supports all format strings, including
thosethatarenotin struct modulesyntax.

hex()
Returnastringobjectcontainingtwohexadecimaldigitsforeachbyteinthebuffer.

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

Newinversion3.5.

tolist()
Returnthedatainthebufferasalistofelements.

>>>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]

Changedinversion3.3: tolist() nowsupportsallsinglecharacternativeformatsin


struct modulesyntaxaswellasmultidimensionalrepresentations.

release()
Releasetheunderlyingbufferexposedbythememoryviewobject.Manyobjectstake
special actions when a view is held on them (for example, a bytearray would

https://docs.python.org/3/library/stdtypes.html#iteratortypes 50/67
16/12/2016 4.BuiltinTypesPython3.5.2documentation

temporarily forbid resizing) therefore, calling release() is handy to remove these


restrictions(andfreeanydanglingresources)assoonaspossible.

After this method has been called, any further operation on the view raises a
ValueError (except release() itselfwhichcanbecalledmultipletimes):

>>>m=memoryview(b'abc') >>>
>>>m.release()
>>>m[0]
Traceback(mostrecentcalllast):
File"<stdin>",line1,in<module>
ValueError:operationforbiddenonreleasedmemoryviewobject

The context management protocol can be used for a similar effect, using the with
statement:

>>>withmemoryview(b'abc')asm: >>>
...m[0]
...
97
>>>m[0]
Traceback(mostrecentcalllast):
File"<stdin>",line1,in<module>
ValueError:operationforbiddenonreleasedmemoryviewobject

Newinversion3.2.

cast(format[,shape])
Cast a memoryview to a new format or shape. shape defaults 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.Supportedcastsare1D>CcontiguousandCcontiguous>1D.

The destination format is restricted to a single element native format in struct


syntax.Oneoftheformatsmustbeabyteformat(B,borc).Thebytelengthof
theresultmustbethesameastheoriginallength.

Cast1D/longto1D/unsignedbytes:

>>>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'

https://docs.python.org/3/library/stdtypes.html#iteratortypes 51/67
16/12/2016 4.BuiltinTypesPython3.5.2documentation

>>>y.itemsize
1
>>>len(y)
24
>>>y.nbytes
24

Cast1D/unsignedbytesto1D/char:

>>>b=bytearray(b'zyz') >>>
>>>x=memoryview(b)
>>>x[0]=b'a'
Traceback(mostrecentcalllast):
File"<stdin>",line1,in<module>
ValueError:memoryview:invalidvalueforformat"B"
>>>y=x.cast('c')
>>>y[0]=b'a'
>>>b
bytearray(b'ayz')

Cast1D/bytesto3D/intsto1D/signedchar:

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

Cast1D/unsignedcharto2D/unsignedlong:

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

https://docs.python.org/3/library/stdtypes.html#iteratortypes 52/67
16/12/2016 4.BuiltinTypesPython3.5.2documentation

>>>y.tolist()
[[0,1,2],[3,4,5]]

Newinversion3.3.

Changedinversion3.5:Thesourceformatisnolongerrestrictedwhencastingtoa
byteview.

Therearealsoseveralreadonlyattributesavailable:

obj
Theunderlyingobjectofthememoryview:

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

Newinversion3.3.

nbytes
nbytes == product(shape) * itemsize == len(m.tobytes()) . This is the
amountofspaceinbytesthatthearraywoulduseinacontiguousrepresentation.Itis
notnecessarilyequaltolen(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

Multidimensionalarrays:

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

https://docs.python.org/3/library/stdtypes.html#iteratortypes 53/67
16/12/2016 4.BuiltinTypesPython3.5.2documentation

Newinversion3.3.

readonly
Aboolindicatingwhetherthememoryisreadonly.

format
Astringcontainingtheformat(in struct modulestyle)foreachelementintheview.
Amemoryviewcanbecreatedfromexporterswitharbitraryformatstrings,butsome
methods(e.g. tolist() )arerestrictedtonativesingleelementformats.

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

itemsize
Thesizeinbytesofeachelementofthememoryview:

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

ndim
Anintegerindicatinghowmanydimensionsofamultidimensionalarraythememory
represents.

shape
A tuple of integers the length of ndim giving the shape of the memory as an N
dimensionalarray.

Changedinversion3.3:Anemptytupleinsteadof None whenndim=0.

strides
Atupleofintegersthelengthof ndim givingthesizeinbytestoaccesseachelement
foreachdimensionofthearray.

Changedinversion3.3:Anemptytupleinsteadof None whenndim=0.

suboffsets
UsedinternallyforPILstylearrays.Thevalueisinformationalonly.

c_contiguous
AboolindicatingwhetherthememoryisCcontiguous.

Newinversion3.3.

f_contiguous
AboolindicatingwhetherthememoryisFortrancontiguous.
https://docs.python.org/3/library/stdtypes.html#iteratortypes 54/67
16/12/2016 4.BuiltinTypesPython3.5.2documentation

Newinversion3.3.

contiguous
Aboolindicatingwhetherthememoryiscontiguous.

Newinversion3.3.

4.9.SetTypes set , frozenset


A set object is an unordered collection of distinct hashable objects. Common uses include
membership testing, removing duplicates from a sequence, and computing mathematical
operations such as intersection, union, difference, and symmetric difference. (For other
containersseethebuiltin dict , list ,and tuple classes,andthe collections module.)

Like other collections, sets support x in set , len(set) , and for x in set . Being an
unordered collection, sets do not record element position or order of insertion. Accordingly,
setsdonotsupportindexing,slicing,orothersequencelikebehavior.

Therearecurrentlytwobuiltinsettypes, set and frozenset .The set typeismutablethe


contentscanbechangedusingmethodslike add() and remove() .Sinceitismutable,ithas
nohashvalueandcannotbeusedaseitheradictionarykeyorasanelementofanotherset.
The frozenset type is immutable and hashable its contents cannot be altered after it is
createditcanthereforebeusedasadictionarykeyorasanelementofanotherset.

Nonempty sets (not frozensets) can be created by placing a commaseparated list of


elementswithinbraces,forexample: {'jack','sjoerd'} ,inadditiontothe set constructor.

Theconstructorsforbothclassesworkthesame:

class set([iterable])
class frozenset([iterable])
Return a new set or frozenset object whose elements are taken from iterable. The
elements of a set must be hashable. To represent sets of sets, the inner sets must be
frozenset objects.Ifiterableisnotspecified,anewemptysetisreturned.

Instancesof set and frozenset providethefollowingoperations:

len(s)
Returnthenumberofelementsinsets(cardinalityofs).

xins
Testxformembershipins.

xnotins
Testxfornonmembershipins.

isdisjoint(other)
Return True ifthesethasnoelementsincommonwithother.Setsaredisjointifand
onlyiftheirintersectionistheemptyset.

issubset( other )
https://docs.python.org/3/library/stdtypes.html#iteratortypes 55/67
16/12/2016 4.BuiltinTypesPython3.5.2documentation

issubset(other)
set<=other
Testwhethereveryelementinthesetisinother.

set<other
Testwhetherthesetisapropersubsetofother,thatis, set<=otherandset!=
other .

issuperset(other)
set>=other
Testwhethereveryelementinotherisintheset.

set>other
Testwhetherthesetisapropersupersetofother,thatis, set>=otherandset!=
other .

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

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

difference(*others)
setother...
Returnanewsetwithelementsinthesetthatarenotintheothers.

symmetric_difference(other)
set^other
Returnanewsetwithelementsineitherthesetorotherbutnotboth.

copy()
Returnanewsetwithashallowcopyofs.

Note, the nonoperator versions of union() , intersection() , difference() , and


symmetric_difference() , issubset() , and issuperset() methods will accept any
iterable as an argument. In contrast, their operator based counterparts require their
argumentstobesets.Thisprecludeserrorproneconstructionslike set('abc')&'cbs'
infavorofthemorereadable set('abc').intersection('cbs') .

Both set and frozenset supportsettosetcomparisons.Twosetsareequalifandonlyif


everyelementofeachsetiscontainedintheother(eachisasubsetoftheother).Asetis
lessthananothersetifandonlyifthefirstsetisapropersubsetofthesecondset(isa
subset,butisnotequal).Asetisgreaterthananothersetifandonlyifthefirstsetisa
propersupersetofthesecondset(isasuperset,butisnotequal).

Instancesof set arecomparedtoinstancesof frozenset basedontheirmembers.For


example, set('abc')==frozenset('abc') returns True andsodoes set('abc')in
set([frozenset('abc')]) .
https://docs.python.org/3/library/stdtypes.html#iteratortypes 56/67
16/12/2016 4.BuiltinTypesPython3.5.2documentation

The subset and equality comparisons do not generalize to a total ordering function. For
example,anytwononemptydisjointsetsarenotequalandarenotsubsetsofeachother,
soallofthefollowingreturn False : a<b , a==b ,or a>b .

Since sets only define partial ordering (subset relationships), the output of the
list.sort() methodisundefinedforlistsofsets.

Setelements,likedictionarykeys,mustbehashable.

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

The following table lists operations available for set that do not apply to immutable
instancesof frozenset :

update(*others)
set|=other|...
Updatetheset,addingelementsfromallothers.

intersection_update(*others)
set&=other&...
Updatetheset,keepingonlyelementsfoundinitandallothers.

difference_update(*others)
set=other|...
Updatetheset,removingelementsfoundinothers.

symmetric_difference_update(other)
set^=other
Updatetheset,keepingonlyelementsfoundineitherset,butnotinboth.

add(elem)
Addelementelemtotheset.

remove(elem)
Removeelementelemfromtheset.Raises KeyError ifelemisnotcontainedinthe
set.

discard(elem)
Removeelementelemfromthesetifitispresent.

pop()
Removeandreturnanarbitraryelementfromtheset.Raises KeyError if the set is
empty.

clear()
Removeallelementsfromtheset.

https://docs.python.org/3/library/stdtypes.html#iteratortypes 57/67
16/12/2016 4.BuiltinTypesPython3.5.2documentation

Note, the nonoperator versions of the update() , intersection_update() ,


difference_update() ,and symmetric_difference_update() methods will accept any
iterableasanargument.

Note, the elem argument to the __contains__() , remove() , and discard() methods
may be a set. To support searching for an equivalent frozenset, the elem set is
temporarilymutatedduringthesearchandthenrestored.Duringthesearch,theelemset
shouldnotbereadormutatedsinceitdoesnothaveameaningfulvalue.

4.10.MappingTypes dict
Amappingobjectmapshashablevaluestoarbitraryobjects.Mappingsaremutableobjects.
Thereiscurrentlyonlyonestandardmappingtype,thedictionary.(For other containers see
thebuiltin list , set ,and tuple classes,andthe collections module.)

Adictionaryskeysarealmostarbitraryvalues.Values that are not hashable, that is, values


containinglists,dictionariesorothermutabletypes(thatarecomparedbyvalueratherthanby
objectidentity)maynotbeusedaskeys.Numerictypesusedforkeysobeythenormalrules
fornumericcomparison:iftwonumberscompareequal(suchas 1 and 1.0 )thentheycanbe
usedinterchangeablytoindexthesamedictionaryentry.(Notehowever,thatsincecomputers
storefloatingpointnumbersasapproximationsitisusuallyunwisetousethemasdictionary
keys.)

Dictionaries can be created by placing a commaseparated list of key: value pairs within
braces, for example: {'jack': 4098, 'sjoerd': 4127} or {4098: 'jack', 4127:
'sjoerd'} ,orbythe dict constructor.

class dict(**kwarg)
class dict(mapping,**kwarg)
class dict(iterable,**kwarg)
Return a new dictionary initialized from an optional positional argument and a possibly
emptysetofkeywordarguments.

Ifnopositionalargumentisgiven,anemptydictionaryiscreated.Ifapositionalargument
isgivenanditisamappingobject,adictionaryiscreatedwiththesamekeyvaluepairs
as the mapping object. Otherwise, the positional argument must be an iterable object.
Eachitemintheiterablemustitselfbeaniterablewithexactlytwoobjects.Thefirstobject
of each item becomes a key in the new dictionary, and the second object the
correspondingvalue.Ifakeyoccursmorethanonce,thelastvalueforthatkeybecomes
thecorrespondingvalueinthenewdictionary.

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.

Toillustrate,thefollowingexamplesallreturnadictionaryequalto {"one": 1, "two":


2,"three":3} :

https://docs.python.org/3/library/stdtypes.html#iteratortypes 58/67
16/12/2016 4.BuiltinTypesPython3.5.2documentation

>>>a=dict(one=1,two=2,three=3) >>>
>>>b={'one':1,'two':2,'three':3}
>>>c=dict(zip(['one','two','three'],[1,2,3]))
>>>d=dict([('two',2),('one',1),('three',3)])
>>>e=dict({'three':3,'one':1,'two':2})
>>>a==b==c==d==e
True

Providing keyword arguments as in the first example only works for keys that are valid
Pythonidentifiers.Otherwise,anyvalidkeyscanbeused.

Thesearetheoperationsthatdictionariessupport(andtherefore,custommappingtypes
shouldsupporttoo):

len(d)
Returnthenumberofitemsinthedictionaryd.

d[key]
Returntheitemofdwithkeykey.Raisesa KeyError ifkeyisnotinthemap.

If a subclass of dict defines a method __missing__() and key is not present, the
d[key] operation calls that method with the key key as argument. The d[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, KeyError is raised. __missing__() must be a
methoditcannotbeaninstancevariable:

>>>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__ methodisusedby collections.defaultdict .

d[key]=value
Set d[key] tovalue.

deld[key]
Remove d[key] fromd.Raisesa KeyError ifkeyisnotinthemap.

keyind
Return True ifdhasakeykey,else False .

keynotind
Equivalentto notkeyind .

iter(d)
https://docs.python.org/3/library/stdtypes.html#iteratortypes 59/67
16/12/2016 4.BuiltinTypesPython3.5.2documentation

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

clear()
Removeallitemsfromthedictionary.

copy()
Returnashallowcopyofthedictionary.

classmethod fromkeys(seq[,value])
Createanewdictionarywithkeysfromseqandvaluessettovalue.

fromkeys() isaclassmethodthatreturnsanewdictionary.valuedefaultsto None .

get(key[,default])
Returnthevalueforkeyifkeyisinthedictionary,elsedefault.Ifdefaultisnotgiven,
itdefaultsto None ,sothatthismethodneverraisesa KeyError .

items()
Return a new view of the dictionarys items ( (key, value) pairs). See the
documentationofviewobjects.

keys()
Returnanewviewofthedictionaryskeys.Seethedocumentationofviewobjects.

pop(key[,default])
Ifkeyisinthedictionary,removeitandreturnitsvalue,elsereturndefault.Ifdefault
isnotgivenandkeyisnotinthedictionary,a KeyError israised.

popitem()
Removeandreturnanarbitrary (key,value) pairfromthedictionary.

popitem() is useful to destructively iterate over a dictionary, as often used in set


algorithms.Ifthedictionaryisempty,calling popitem() raisesa KeyError .

setdefault(key[,default])
Ifkeyisinthedictionary,returnitsvalue.Ifnot,insertkeywithavalueofdefaultand
returndefault.defaultdefaultsto None .

update([other])
Update the dictionary with the key/value pairs from other, overwriting existing keys.
Return None .

update() accepts either another dictionary object or an iterable of key/value pairs


(as tuples or other iterables of length two). If keyword arguments are specified, the
dictionaryisthenupdatedwiththosekey/valuepairs: d.update(red=1,blue=2) .

values()
https://docs.python.org/3/library/stdtypes.html#iteratortypes 60/67
16/12/2016 4.BuiltinTypesPython3.5.2documentation

Returnanewviewofthedictionarysvalues.Seethedocumentationofviewobjects.

Dictionariescompareequalifandonlyiftheyhavethesame (key,value) pairs.Order


comparisons(<,<=,>=,>)raise TypeError .

Seealso: types.MappingProxyType canbeusedtocreateareadonlyviewofa dict .

4.10.1.Dictionaryviewobjects
Theobjectsreturnedby dict.keys() , dict.values() and dict.items() areviewobjects.
They provide a dynamic view on the dictionarys entries, which means that when the
dictionarychanges,theviewreflectsthesechanges.

Dictionaryviewscanbeiteratedovertoyieldtheirrespectivedata,andsupportmembership
tests:

len(dictview)
Returnthenumberofentriesinthedictionary.

iter(dictview)
Returnaniteratoroverthekeys,valuesoritems(representedastuplesof (key,value) )
inthedictionary.

Keys and values are iterated over in an arbitrary order which is nonrandom, varies
acrossPythonimplementations,anddependsonthedictionaryshistoryofinsertionsand
deletions. If keys, values and items views are iterated over with no intervening
modificationstothedictionary,theorderofitemswilldirectlycorrespond.Thisallowsthe
creation of (value, key) pairs using zip() : pairs = zip(d.values(), d.keys()) .
Anotherwaytocreatethesamelistis pairs=[(v,k)for(k,v)ind.items()] .

Iterating views while adding or deleting entries in the dictionary may raise a
RuntimeError orfailtoiterateoverallentries.

xindictview
Return True ifxisintheunderlyingdictionaryskeys,valuesoritems(inthelattercase,x
shouldbea (key,value) tuple).

Keysviewsaresetlikesincetheirentriesareuniqueandhashable.Ifallvaluesarehashable,
so that (key, value) pairs are unique and hashable, then the items view is also setlike.
(Valuesviewsarenottreatedassetlikesincetheentriesaregenerallynotunique.)Forset
likeviews,alloftheoperationsdefinedfortheabstractbaseclass collections.abc.Set are
available(forexample, == , < ,or ^ ).

Anexampleofdictionaryviewusage:

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

https://docs.python.org/3/library/stdtypes.html#iteratortypes 61/67
16/12/2016 4.BuiltinTypesPython3.5.2documentation

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

>>>#keysandvaluesareiteratedoverinthesameorder
>>>list(keys)
['eggs','bacon','sausage','spam']
>>>list(values)
[2,1,1,500]

>>>#viewobjectsaredynamicandreflectdictchanges
>>>deldishes['eggs']
>>>deldishes['sausage']
>>>list(keys)
['spam','bacon']

>>>#setoperations
>>>keys&{'eggs','bacon','salad'}
{'bacon'}
>>>keys^{'sausage','juice'}
{'juice','sausage','bacon','spam'}

4.11.ContextManagerTypes
Pythons with statement supports the concept of a runtime context defined by a context
manager. This is implemented using a pair of methods that allow userdefined classes to
define a runtime context that is entered before the statement body is executed and exited
whenthestatementends:

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 the as
clauseof with statementsusingthiscontextmanager.

An example of a context manager that returns itself is a file object. File objects return
themselvesfrom__enter__()toallow open() tobeusedasthecontextexpressionina
with statement.

An example of a context manager that returns a related object is the one returned by
decimal.localcontext() .Thesemanagerssettheactivedecimalcontexttoacopyof
theoriginaldecimalcontextandthenreturnthecopy.Thisallowschangestobemadeto
the current decimal context in the body of the with statement without affecting code
outsidethe with statement.

contextmanager. __exit__(exc_type,exc_val,exc_tb)
Exit the runtime context and return a Boolean flag indicating if any exception that
occurredshouldbesuppressed.Ifanexceptionoccurredwhileexecutingthebodyofthe

https://docs.python.org/3/library/stdtypes.html#iteratortypes 62/67
16/12/2016 4.BuiltinTypesPython3.5.2documentation

with statement, the arguments contain the exception type, value and traceback
information.Otherwise,allthreeargumentsare None .

Returning a true value from this method will cause the with statement to suppress the
exception and continue execution with the statement immediately following the with
statement.Otherwisetheexceptioncontinuespropagatingafterthismethodhasfinished
executing. Exceptions that occur during execution of this method will replace any
exceptionthatoccurredinthebodyofthe with statement.

Theexceptionpassedinshouldneverbereraisedexplicitlyinstead,thismethodshould
returnafalsevaluetoindicatethatthemethodcompletedsuccessfullyanddoesnotwant
tosuppresstheraisedexception.Thisallowscontextmanagementcodetoeasilydetect
whetherornotan __exit__() methodhasactuallyfailed.

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
contextmanagementprotocol.Seethe contextlib moduleforsomeexamples.

Pythons generators and the contextlib.contextmanager decorator provide a convenient


way to implement these protocols. If a generator function is decorated with the
contextlib.contextmanager decorator, it will return a context manager implementing the
necessary __enter__() and __exit__() methods, rather than the iterator produced by an
undecoratedgeneratorfunction.

Note that there is no specific slot for any of these methods in the type structure for Python
objectsinthePython/CAPI.Extensiontypeswantingtodefinethesemethodsmustprovide
them as a normal Python accessible method. Compared to the overhead of setting up the
runtimecontext,theoverheadofasingleclassdictionarylookupisnegligible.

4.12.OtherBuiltinTypes
Theinterpretersupportsseveralotherkindsofobjects.Mostofthesesupportonlyoneortwo
operations.

4.12.1.Modules

Theonlyspecialoperationonamoduleisattributeaccess: m.name ,wheremisamoduleand


name accesses a name defined in ms symbol table. Module attributes can be assigned to.
(Note that the import statement is not, strictly speaking, an operation on a module object
import foo does not require a module object named foo to exist, rather it requires an
(external)definitionforamodulenamedfoosomewhere.)

Aspecialattributeofeverymoduleis __dict__ .Thisisthedictionarycontainingthemodules


symbol table. Modifying this dictionary will actually change the modules symbol table, but
directassignmenttothe __dict__ attributeisnotpossible(youcanwrite m.__dict__['a']
=1 ,whichdefines m.a tobe 1 ,butyoucantwrite m.__dict__={} ).Modifying __dict__
directlyisnotrecommended.
https://docs.python.org/3/library/stdtypes.html#iteratortypes 63/67
16/12/2016 4.BuiltinTypesPython3.5.2documentation

Modulesbuiltintotheinterpreterarewrittenlikethis: <module'sys'(builtin)> .Ifloaded


fromafile,theyarewrittenas <module'os'from'/usr/local/lib/pythonX.Y/os.pyc'> .

4.12.2.ClassesandClassInstances
SeeObjects,valuesandtypesandClassdefinitionsforthese.

4.12.3.Functions

Functionobjectsarecreatedbyfunctiondefinitions.Theonlyoperationonafunctionobjectis
tocallit: func(argumentlist) .

Therearereallytwoflavorsoffunctionobjects:builtinfunctionsanduserdefinedfunctions.
Both support the same operation (to call the function), but the implementation is different,
hencethedifferentobjecttypes.

SeeFunctiondefinitionsformoreinformation.

4.12.4.Methods
Methodsarefunctionsthatarecalledusingtheattributenotation.Therearetwoflavors:built
in methods (such as append() on lists) and class instance methods. Builtin methods are
describedwiththetypesthatsupportthem.

Ifyouaccessamethod(afunctiondefinedinaclassnamespace)throughaninstance,you
getaspecialobject:aboundmethod(alsocalledinstancemethod)object.Whencalled,itwill
add the self argument to the argument list. Bound methods have two special readonly
attributes: m.__self__ is the object on which the method operates, and m.__func__ is the
function implementing the method. Calling m(arg1, arg2, ..., argn) is completely
equivalenttocalling m.__func__(m.__self__,arg1,arg2,...,argn) .

Like function objects, bound method objects support getting arbitrary attributes. However,
since method attributes are actually stored on the underlying function object
( meth.__func__ ), setting method attributes on bound methods is disallowed. Attempting to
set an attribute on a method results in an AttributeError being raised. In order to set a
methodattribute,youneedtoexplicitlysetitontheunderlyingfunctionobject:

>>>
>>>classC:
...defmethod(self):
...pass
...
>>>c=C()
>>>c.method.whoami='mynameismethod'#can'tsetonthemethod
Traceback(mostrecentcalllast):
File"<stdin>",line1,in<module>
AttributeError:'method'objecthasnoattribute'whoami'
>>>c.method.__func__.whoami='mynameismethod'
>>>c.method.whoami
'mynameismethod'

https://docs.python.org/3/library/stdtypes.html#iteratortypes 64/67
16/12/2016 4.BuiltinTypesPython3.5.2documentation

SeeThestandardtypehierarchyformoreinformation.

4.12.5.CodeObjects
Code objects are used by the implementation to represent pseudocompiled executable
Python code such as a function body. They differ from function objects because they dont
containareferencetotheirglobalexecutionenvironment.Codeobjectsare returned by the
builtin compile() functionandcanbeextractedfromfunctionobjectsthroughtheir __code__
attribute.Seealsothe code module.

Acodeobjectcanbeexecutedorevaluatedbypassingit(insteadofasourcestring)tothe
exec() or eval() builtinfunctions.

SeeThestandardtypehierarchyformoreinformation.

4.12.6.TypeObjects

Typeobjectsrepresentthevariousobjecttypes.Anobjectstypeisaccessedbythebuiltin
function type() . There are no special operations on types. The standard module types
definesnamesforallstandardbuiltintypes.

Typesarewrittenlikethis: <class'int'> .

4.12.7.TheNullObject
Thisobjectisreturnedbyfunctionsthatdontexplicitlyreturnavalue.It supports no special
operations. There is exactly one null object, named None (a builtin name). type(None)()
producesthesamesingleton.

Itiswrittenas None .

4.12.8.TheEllipsisObject

This object is commonly used by slicing (see Slicings). It supports no special operations.
There is exactly one ellipsis object, named Ellipsis (a builtin name). type(Ellipsis)()
producesthe Ellipsis singleton.

Itiswrittenas Ellipsis or ... .

4.12.9.TheNotImplementedObject
This object is returned from comparisons and binary operations when they are asked to
operateontypestheydontsupport.SeeComparisonsformoreinformation.Thereisexactly
one NotImplemented object. type(NotImplemented)() producesthesingletoninstance.

Itiswrittenas NotImplemented .

https://docs.python.org/3/library/stdtypes.html#iteratortypes 65/67
16/12/2016 4.BuiltinTypesPython3.5.2documentation

4.12.10.BooleanValues
Boolean values are the two constant objects False and True . They are used to represent
truthvalues(althoughothervaluescanalsobeconsideredfalseortrue).Innumericcontexts
(for example when used as the argument to an arithmetic operator), they behave like the
integers0and1,respectively.Thebuiltinfunction bool() canbeusedtoconvertanyvalue
toaBoolean,ifthevaluecanbeinterpretedasatruthvalue(seesectionTruthValueTesting
above).

Theyarewrittenas False and True ,respectively.

4.12.11.InternalObjects

See The standard type hierarchy for this information. It describes stack frame objects,
tracebackobjects,andsliceobjects.

4.13.SpecialAttributes
The implementation adds a few special readonly attributes to several object types, where
theyarerelevant.Someofthesearenotreportedbythe dir() builtinfunction.

object. __dict__
Adictionaryorothermappingobjectusedtostoreanobjects(writable)attributes.

instance. __class__
Theclasstowhichaclassinstancebelongs.

class. __bases__
Thetupleofbaseclassesofaclassobject.

definition. __name__
Thenameoftheclass,function,method,descriptor,orgeneratorinstance.

definition. __qualname__
Thequalifiednameoftheclass,function,method,descriptor,orgeneratorinstance.

Newinversion3.3.

class. __mro__
This attribute is a tuple of classes that are considered when looking for base classes
duringmethodresolution.

class. mro()
Thismethodcanbeoverriddenbyametaclasstocustomizethemethodresolutionorder
foritsinstances.Itiscalledatclassinstantiation,anditsresultisstoredin __mro__ .

class. __subclasses__()

https://docs.python.org/3/library/stdtypes.html#iteratortypes 66/67
16/12/2016 4.BuiltinTypesPython3.5.2documentation

Each class keeps a list of weak references to its immediate subclasses. This method
returnsalistofallthosereferencesstillalive.Example:

>>>int.__subclasses__() >>>
[<class'bool'>]

Footnotes

[1] AdditionalinformationonthesespecialmethodsmaybefoundinthePython
ReferenceManual(Basiccustomization).

[2] Asaconsequence,thelist [1,2] isconsideredequalto [1.0,2.0] ,andsimilarly


fortuples.

[3] Theymusthavesincetheparsercanttellthetypeoftheoperands.

[4] (1,2,3,4)Casedcharactersarethosewithgeneralcategorypropertybeingoneof
Lu(Letter,uppercase),Ll(Letter,lowercase),orLt(Letter,titlecase).

[5] (1,2)Toformatonlyatupleyoushouldthereforeprovideasingletontuplewhoseonly
elementisthetupletobeformatted.

https://docs.python.org/3/library/stdtypes.html#iteratortypes 67/67

You might also like