Download as pdf or txt
Download as pdf or txt
You are on page 1of 27

8/31/2016

2.BuiltinFunctionsPython2.7.12documentation

2. Builtin Functions
ThePythoninterpreterhasanumberoffunctionsbuiltintoitthatarealwaysavailable.They are
listedhereinalphabeticalorder.
Builtin
Functions
abs()

divmod()

input()

open()

staticmethod()

all()

enumerate()

int()

ord()

str()

any()

eval()

isinstance()

pow()

sum()

basestring()

execfile()

issubclass()

print()

super()

bin()

file()

iter()

property()

tuple()

bool()

filter()

len()

range()

type()

bytearray()

float()

list()

raw_input()

unichr()

callable()

format()

locals()

reduce()

unicode()

chr()

frozenset()

long()

reload()

vars()

classmethod()

getattr()

map()

repr()

xrange()

cmp()

globals()

max()

reversed()

zip()

compile()

hasattr()

memoryview()

round()

__import__()

complex()

hash()

min()

set()

delattr()

help()

next()

setattr()

dict()

hex()

object()

slice()

dir()

id()

oct()

sorted()

Inaddition,thereareotherfourbuiltinfunctionsthatarenolongerconsideredessential: apply() ,
buffer() , coerce() , and intern() . They are documented in the Nonessential Builtin Functions
section.
abs (x)
Return the absolute value of a number. The argument may be a plain or long integer or a
floatingpointnumber.Iftheargumentisacomplexnumber,itsmagnitudeisreturned.
all (iterable)
Return True ifallelementsoftheiterablearetrue(oriftheiterableisempty).Equivalentto:
defall(iterable):
forelementiniterable:
ifnotelement:
returnFalse
returnTrue

Newinversion2.5.
any (iterable)
Return True if any element of the iterable is true. If the iterable is empty, return
Equivalentto:

False .

defany(iterable):
forelementiniterable:
ifelement:
https://docs.python.org/2/library/functions.html

1/27

8/31/2016

2.BuiltinFunctionsPython2.7.12documentation

returnTrue
returnFalse

Newinversion2.5.
basestring ()
Thisabstracttypeisthesuperclassfor str and unicode .Itcannotbecalledorinstantiated,but
it can be used to test whether an object is an instance of str or unicode . isinstance(obj,
basestring) isequivalentto isinstance(obj,(str,unicode)) .

Newinversion2.3.
bin (x)
Convertanintegernumbertoabinarystring.TheresultisavalidPythonexpression.Ifxisnot
aPython int object,ithastodefinean __index__() methodthatreturnsaninteger.

Newinversion2.6.
class bool ([x])
Return a Boolean value, i.e. one of True or False . x is converted using the standard truth
testingprocedure.Ifxisfalseoromitted,thisreturns False otherwiseitreturns True . bool is
also a class, which is a subclass of int . Class bool cannot be subclassed further. Its only
instancesare False and True .
Newinversion2.2.1.
Changedinversion2.3:Ifnoargumentisgiven,thisfunctionreturns False .
class bytearray ([source[,encoding[,errors]]])
Return a new array of bytes. The bytearray class is a mutable sequence of integers in the
range 0 <= x < 256. It has most of the usual methods of mutable sequences, described in
MutableSequenceTypes,aswellasmostmethodsthatthe str typehas,seeStringMethods.
Theoptionalsourceparametercanbeusedtoinitializethearrayinafewdifferentways:
If it is unicode, you must also give the encoding (and optionally, errors) parameters
bytearray() thenconvertstheunicodetobytesusing unicode.encode() .
Ifitisaninteger,thearraywillhavethatsizeandwillbeinitializedwithnullbytes.
Ifitisanobjectconformingtothebufferinterface,areadonlybufferoftheobjectwillbe
usedtoinitializethebytesarray.
Ifitisaniterable,itmustbeaniterableofintegersintherange 0<=x<256 ,whichare
usedastheinitialcontentsofthearray.
Withoutanargument,anarrayofsize0iscreated.
Newinversion2.6.
callable (object)
Return True if the object argument appears callable, False if not. If this returns true, it is still
possiblethatacallfails,butifitisfalse,callingobjectwillneversucceed.Note that classes
https://docs.python.org/2/library/functions.html

2/27

8/31/2016

2.BuiltinFunctionsPython2.7.12documentation

arecallable(callingaclassreturnsanewinstance)classinstancesarecallableiftheyhavea
__call__() method.
chr (i)
Return a string of one character whose ASCII code is the integer i. For example, chr(97)
returnsthestring 'a' .Thisistheinverseof ord() .Theargumentmustbeintherange[0..255],
inclusive ValueError willberaisedifiisoutsidethatrange.Seealso unichr() .
classmethod (function)
Returnaclassmethodforfunction.

A class method receives the class as implicit first argument, just like an instance method
receivestheinstance.Todeclareaclassmethod,usethisidiom:
classC(object):
@classmethod
deff(cls,arg1,arg2,...):
...

The @classmethod form is a function decorator see the description of function definitions in
Functiondefinitionsfordetails.
Itcanbecalledeitherontheclass(suchas C.f() )oronaninstance(suchas C().f() ). The
instance is ignored except for its class. If a class method is called for a derived class, the
derivedclassobjectispassedastheimpliedfirstargument.
Class methods are different than C++ or Java static methods. If you want those, see
staticmethod() inthissection.
For more information on class methods, consult the documentation on the standard type
hierarchyinThestandardtypehierarchy.
Newinversion2.2.
Changedinversion2.4:Functiondecoratorsyntaxadded.
cmp (x,y)
Comparethetwoobjectsxandyandreturnanintegeraccordingtotheoutcome.Thereturn
valueisnegativeif x<y ,zeroif x==y andstrictlypositiveif x>y .
compile (source,filename,mode[,flags[,dont_inherit]])
Compile the source into a code or AST object. Code objects can be executed by an exec
statement or evaluated by a call to eval() . source can either be a Unicode string, a Latin1
encoded string or anAST object. Refer to the ast module documentation for information on
howtoworkwithASTobjects.

The filename argument should give the file from which the code was read pass some
recognizablevalueifitwasntreadfromafile( '<string>' iscommonlyused).
Themodeargumentspecifieswhatkindofcodemustbecompileditcanbe 'exec' ifsource
consistsofasequenceofstatements, 'eval' ifitconsistsofasingleexpression,or 'single' if
https://docs.python.org/2/library/functions.html

3/27

8/31/2016

2.BuiltinFunctionsPython2.7.12documentation

it consists of a single interactive statement (in the latter case, expression statements that
evaluatetosomethingotherthan None willbeprinted).
Theoptionalargumentsflagsanddont_inheritcontrolwhichfuturestatements(seePEP236)
affectthecompilationofsource.Ifneitherispresent(orbotharezero)thecodeiscompiled
withthosefuturestatementsthatareineffectinthecodethatiscalling compile() .Iftheflags
argumentisgivenanddont_inheritisnot(oriszero)thenthefuturestatementsspecifiedby
theflagsargumentareusedinadditiontothosethatwouldbeusedanyway.Ifdont_inheritis
anonzerointegerthentheflagsargumentisitthefuturestatementsineffectaroundthecall
tocompileareignored.
FuturestatementsarespecifiedbybitswhichcanbebitwiseORedtogethertospecifymultiple
statements.Thebitfieldrequiredtospecifyagivenfeaturecanbefoundasthe compiler_flag
attributeonthe _Feature instanceinthe __future__ module.
This function raises SyntaxError if the compiled source is invalid, and TypeError if the source
containsnullbytes.
IfyouwanttoparsePythoncodeintoitsASTrepresentation,see ast.parse() .
Note: Whencompilingastringwithmultilinecodein 'single' or 'eval' mode,inputmust
beterminatedbyatleastonenewlinecharacter.Thisistofacilitatedetectionofincomplete
andcompletestatementsinthe code module.
Changedinversion2.3:Theflagsanddont_inheritargumentswereadded.
Changedinversion2.6:SupportforcompilingASTobjects.
Changedinversion2.7:AlloweduseofWindowsandMacnewlines.Alsoinputin 'exec' mode
doesnothavetoendinanewlineanymore.
class complex ([real[,imag]])
Return a complex number with the value real + imag*1j or convert a string or number to a
complexnumber.Ifthefirstparameterisastring,itwillbeinterpretedasacomplexnumber
andthefunctionmustbecalledwithoutasecondparameter.Thesecondparametercannever
beastring.Eachargumentmaybeanynumerictype(includingcomplex).Ifimagisomitted,it
defaults to zero and the function serves as a numeric conversion function like int() , long()
and float() .Ifbothargumentsareomitted,returns 0j .
Note: When converting from a string, the string must not contain whitespace around the
central + or operator. For example, complex('1+2j') is fine, but complex('1 + 2j') raises
ValueError .
ThecomplextypeisdescribedinNumericTypesint,float,long,complex.
delattr (object,name)
Thisisarelativeof setattr() .Theargumentsareanobjectandastring.The string must be
thenameofoneoftheobjectsattributes.Thefunctiondeletesthenamedattribute,provided
theobjectallowsit.Forexample, delattr(x,'foobar') isequivalentto delx.foobar .
https://docs.python.org/2/library/functions.html

4/27

8/31/2016

2.BuiltinFunctionsPython2.7.12documentation

class dict (**kwarg)


class dict (mapping,**kwarg)
class dict (iterable,**kwarg)
Createanewdictionary.The dict objectisthedictionaryclass.See dict andMappingTypes
dictfordocumentationaboutthisclass.
For other containers see the builtin list , set , and tuple classes, as well as the collections
module.
dir ([object])
Without arguments, return the list of names in the current local scope. With an argument,
attempttoreturnalistofvalidattributesforthatobject.

Iftheobjecthasamethodnamed __dir__() ,thismethodwillbecalledandmustreturnthelist


of attributes. This allows objects that implement a custom __getattr__() or __getattribute__()
functiontocustomizetheway dir() reportstheirattributes.
Iftheobjectdoesnotprovide __dir__() ,thefunctiontriesitsbesttogatherinformationfromthe
objects __dict__ attribute, if defined, and from its type object. The resulting list is not
necessarilycomplete,andmaybeinaccuratewhentheobjecthasacustom __getattr__() .
Thedefault dir() mechanismbehavesdifferentlywithdifferenttypesofobjects,asitattempts
toproducethemostrelevant,ratherthancomplete,information:
Iftheobjectisamoduleobject,thelistcontainsthenamesofthemodulesattributes.
If the object is a type or class object, the list contains the names of its attributes, and
recursivelyoftheattributesofitsbases.
Otherwise, the list contains the objects attributes names, the names of its classs
attributes,andrecursivelyoftheattributesofitsclasssbaseclasses.
Theresultinglistissortedalphabetically.Forexample:
>>>importstruct
>>>dir()#showthenamesinthemodulenamespace
['__builtins__','__doc__','__name__','struct']
>>>dir(struct)#showthenamesinthestructmodule
['Struct','__builtins__','__doc__','__file__','__name__',
'__package__','_clearcache','calcsize','error','pack','pack_into',
'unpack','unpack_from']
>>>classShape(object):
def__dir__(self):
return['area','perimeter','location']
>>>s=Shape()
>>>dir(s)
['area','perimeter','location']

>>>

Note: Because dir() is supplied primarily as a convenience for use at an interactive


prompt,ittriestosupplyaninterestingsetofnamesmorethanittriestosupplyarigorously
orconsistentlydefinedsetofnames,anditsdetailedbehaviormaychangeacrossreleases.
Forexample,metaclassattributesarenotintheresultlistwhentheargumentisaclass.
divmod (a,b)
https://docs.python.org/2/library/functions.html

5/27

8/31/2016

2.BuiltinFunctionsPython2.7.12documentation

Take two (non complex) numbers as arguments and return a pair of numbers consisting of
theirquotientandremainderwhenusinglongdivision.Withmixedoperandtypes,therulesfor
binaryarithmeticoperatorsapply.Forplainandlongintegers,theresultisthesameas (a //
b,a%b) .Forfloatingpointnumberstheresultis (q,a%b) ,whereqisusually math.floor(a/
b) butmaybe1lessthanthat.Inanycase q*b+a%b isveryclosetoa,if a%b isnonzero
ithasthesamesignasb,and 0<=abs(a%b)<abs(b) .
Changedinversion2.3:Using divmod() withcomplexnumbersisdeprecated.
enumerate (sequence,start=0)
Returnanenumerateobject.sequencemustbeasequence,aniterator,orsomeotherobject
which supports iteration. The next() method of the iterator returned by enumerate() returns a
tuplecontainingacount(fromstartwhichdefaultsto0)andthevaluesobtainedfromiterating
oversequence:
>>>seasons=['Spring','Summer','Fall','Winter']
>>>list(enumerate(seasons))
[(0,'Spring'),(1,'Summer'),(2,'Fall'),(3,'Winter')]
>>>list(enumerate(seasons,start=1))
[(1,'Spring'),(2,'Summer'),(3,'Fall'),(4,'Winter')]

>>>

Equivalentto:
defenumerate(sequence,start=0):
n=start
foreleminsequence:
yieldn,elem
n+=1

Newinversion2.3.
Changedinversion2.6:Thestartparameterwasadded.
eval (expression[,globals[,locals]])
The arguments are a Unicode or Latin1 encoded string and optional globals and locals. If
provided,globalsmustbeadictionary.Ifprovided,localscanbeanymappingobject.

Changedinversion2.4:formerlylocalswasrequiredtobeadictionary.
The expression argument is parsed and evaluated as a Python expression (technically
speaking, a condition list) using the globals and locals dictionaries as global and local
namespace.Iftheglobalsdictionaryispresentandlacks__builtins__,thecurrentglobalsare
copiedintoglobalsbeforeexpressionisparsed.Thismeansthatexpressionnormallyhasfull
accesstothestandard __builtin__ moduleandrestrictedenvironmentsarepropagated.Ifthe
localsdictionaryisomitteditdefaultstotheglobalsdictionary.Ifbothdictionariesareomitted,
theexpressionisexecutedintheenvironmentwhere eval() iscalled.Thereturnvalueisthe
resultoftheevaluatedexpression.Syntaxerrorsarereportedasexceptions.Example:
>>>x=1
>>>printeval('x+1')
2
https://docs.python.org/2/library/functions.html

>>>

6/27

8/31/2016

2.BuiltinFunctionsPython2.7.12documentation

This function can also be used to execute arbitrary code objects (such as those created by
compile() ). In this case pass a code object instead of a string. If the code object has been
compiledwith 'exec' asthemodeargument, eval() sreturnvaluewillbe None .
Hints: dynamic execution of statements is supported by the exec statement. Execution of
statements from a file is supported by the execfile() function. The globals() and locals()
functionsreturnsthecurrentglobalandlocaldictionary,respectively,whichmaybeusefulto
passaroundforuseby eval() or execfile() .
See ast.literal_eval() for a function that can safely evaluate strings with expressions
containingonlyliterals.
execfile (filename[,globals[,locals]])
Thisfunctionissimilartothe exec statement,butparsesafileinsteadofastring.Itisdifferent
fromthe import statementinthatitdoesnotusethemoduleadministrationitreadsthefile
unconditionallyanddoesnotcreateanewmodule.[1]

Theargumentsareafilenameandtwooptionaldictionaries.Thefileisparsedandevaluated
as a sequence of Python statements (similarly to a module) using the globals and locals
dictionaries as global and local namespace. If provided, locals can be any mapping object.
Remember that at module level, globals and locals are the same dictionary. If two separate
objectsarepassedasglobalsandlocals,thecodewillbeexecutedasifitwereembeddedin
aclassdefinition.
Changedinversion2.4:formerlylocalswasrequiredtobeadictionary.
If the locals dictionary is omitted it defaults to the globals dictionary. If both dictionaries are
omitted,theexpressionisexecutedintheenvironmentwhere execfile() iscalled.Thereturn
valueis None .
Note: Thedefaultlocalsactasdescribedforfunction locals() below:modificationstothe
default locals dictionary should not be attempted. Pass an explicit locals dictionary if you
needtoseeeffectsofthecodeonlocalsafterfunction execfile() returns. execfile() cannot
beusedreliablytomodifyafunctionslocals.
file (name[,mode[,buffering]])
Constructor function for the file type, described further in section File Objects. The
constructorsargumentsarethesameasthoseofthe open() builtinfunctiondescribedbelow.

Whenopeningafile,itspreferabletouse open() insteadofinvokingthisconstructordirectly.


file ismoresuitedtotypetesting(forexample,writing isinstance(f,file) ).
Newinversion2.2.
filter (function,iterable)
Constructalistfromthoseelementsofiterableforwhichfunctionreturnstrue.iterablemaybe
eitherasequence,acontainerwhichsupportsiteration,oraniterator.Ifiterableisastringora

https://docs.python.org/2/library/functions.html

7/27

8/31/2016

2.BuiltinFunctionsPython2.7.12documentation

tuple,theresultalsohasthattypeotherwiseitisalwaysalist.Iffunctionis None ,theidentity


functionisassumed,thatis,allelementsofiterablethatarefalseareremoved.
Note that

filter(function, iterable)

is equivalent to [item for item in iterable if


function(item)] iffunctionisnot None and [itemforiteminiterableifitem] iffunctionis None .
See itertools.ifilter() and itertools.ifilterfalse() for iterator versions of this function,
includingavariationthatfiltersforelementswherethefunctionreturnsfalse.
class float ([x])
Returnafloatingpointnumberconstructedfromanumberorstringx.
Iftheargumentisastring,itmustcontainapossiblysigneddecimalorfloatingpointnumber,
possiblyembeddedinwhitespace.Theargumentmayalsobe[+|]nanor[+|]inf.Otherwise,
the argument may be a plain or long integer or a floating point number, and a floating point
number with the same value (within Pythons floating point precision) is returned. If no
argumentisgiven,returns 0.0 .
Note: Whenpassinginastring,valuesforNaNandInfinitymaybereturned,depending
ontheunderlyingClibrary.Floatacceptsthestringsnan,infandinfforNaNandpositiveor
negativeinfinity.Thecaseandaleading+areignoredaswellasaleadingisignoredfor
NaN.FloatalwaysrepresentsNaNandinfinityasnan,inforinf.
ThefloattypeisdescribedinNumericTypesint,float,long,complex.
format (value[,format_spec])
Convert a value to a formatted representation, as controlled by format_spec. The
interpretationofformat_specwilldependonthetypeofthevalueargument,howeverthereis
a standard formatting syntax that is used by most builtin types: Format Specification Mini
Language.

Note: format(value,format_spec) merelycalls value.__format__(format_spec) .


Newinversion2.6.
class frozenset ([iterable])
Returnanew frozenset object,optionallywithelementstakenfromiterable. frozenset isabuilt
inclass.See frozenset andSetTypesset,frozensetfordocumentationaboutthisclass.
For other containers see the builtin
collections module.

set , list , tuple ,

and

dict

classes, as well as the

Newinversion2.4.
getattr (object,name[,default])
Returnthevalueofthenamedattributeofobject.name must be a string. If the string is the
name of one of the objects attributes, the result is the value of that attribute. For example,

https://docs.python.org/2/library/functions.html

8/27

8/31/2016

2.BuiltinFunctionsPython2.7.12documentation

getattr(x,'foobar') isequivalentto x.foobar .If the named attribute does not exist, default is

returnedifprovided,otherwise AttributeError israised.


globals ()
Returnadictionaryrepresentingthecurrentglobalsymboltable.Thisisalwaysthedictionary
ofthecurrentmodule(insideafunctionormethod,thisisthemodulewhereitisdefined,not
themodulefromwhichitiscalled).
hasattr (object,name)
Theargumentsareanobjectandastring.Theresultis True ifthestringisthenameofoneof
the objects attributes, False if not. (This is implemented by calling getattr(object, name) and
seeingwhetheritraisesanexceptionornot.)
hash (object)
Returnthehashvalueoftheobject(ifithasone).Hashvaluesareintegers.Theyareusedto
quickly compare dictionary keys during a dictionary lookup. Numeric values that compare
equalhavethesamehashvalue(eveniftheyareofdifferenttypes,asisthecasefor1and
1.0).
help ([object])
Invokethebuiltinhelpsystem.(Thisfunctionisintendedforinteractiveuse.)Ifnoargumentis
given,theinteractivehelpsystemstartsontheinterpreterconsole.Iftheargumentisastring,
then the string is looked up as the name of a module, function, class, method, keyword, or
documentationtopic,andahelppageisprintedontheconsole.Iftheargumentisanyother
kindofobject,ahelppageontheobjectisgenerated.

Thisfunctionisaddedtothebuiltinnamespacebythe site module.


Newinversion2.2.
hex (x)
Convertanintegernumber(ofanysize)toalowercasehexadecimalstringprefixedwith0x,
forexample:
>>>

>>>hex(255)
'0xff'
>>>hex(42)
'0x2a'
>>>hex(1L)
'0x1L'

IfxisnotaPython int or long object,ithastodefinean__index__()methodthatreturnsan


integer.
Seealso int() forconvertingahexadecimalstringtoanintegerusingabaseof16.
Note: To obtain a hexadecimal string representation for a float, use the
method.

float.hex()

Changedinversion2.4:Formerlyonlyreturnedanunsignedliteral.
https://docs.python.org/2/library/functions.html

9/27

8/31/2016

2.BuiltinFunctionsPython2.7.12documentation

id (object)
Returntheidentityofanobject.Thisisaninteger(orlonginteger)whichisguaranteedtobe
unique and constant for this object during its lifetime. Two objects with nonoverlapping
lifetimesmayhavethesame id() value.

CPythonimplementationdetail:Thisistheaddressoftheobjectinmemory.

input ([prompt])
Equivalentto eval(raw_input(prompt)) .

Thisfunctiondoesnotcatchusererrors.Iftheinputisnotsyntacticallyvalid,a SyntaxError will


beraised.Otherexceptionsmayberaisedifthereisanerrorduringevaluation.
Ifthe readline modulewasloaded,then input() willuseittoprovideelaboratelineeditingand
historyfeatures.
Considerusingthe raw_input() functionforgeneralinputfromusers.
class int (x=0)
class int (x,base=10)
Returnanintegerobjectconstructedfromanumberorstringx,orreturn 0 ifnoargumentsare
given.Ifxisanumber,itcanbeaplaininteger,alonginteger,orafloatingpointnumber.Ifx
isfloatingpoint,theconversiontruncatestowardszero.Iftheargumentisoutsidetheinteger
range,thefunctionreturnsalongobjectinstead.
Ifxisnotanumberorifbaseisgiven,thenxmustbeastringorUnicodeobjectrepresenting
anintegerliteralinradixbase.Optionally,theliteralcanbeprecededby + or (withnospace
inbetween)andsurroundedbywhitespace.Abasenliteralconsistsofthedigits0ton1,with
a to z (or A to Z )havingvalues10to35.Thedefaultbaseis10.Theallowedvaluesare0and
236.Base2,8,and16literalscanbeoptionallyprefixedwith 0b / 0B , 0o / 0O / 0 ,or 0x / 0X ,aswith
integerliteralsincode.Base0meanstointerpretthestringexactlyasanintegerliteral,sothat
theactualbaseis2,8,10,or16.
TheintegertypeisdescribedinNumericTypesint,float,long,complex.
isinstance (object,classinfo)
Return true if the object argument is an instance of the classinfo argument, or of a (direct,
indirect or virtual) subclass thereof. Also return true if classinfo is a type object (newstyle
class)andobjectisanobjectofthattypeorofa(direct,indirectorvirtual)subclassthereof.If
objectisnotaclassinstanceoranobjectofthegiventype,thefunctionalwaysreturnsfalse.If
classinfo is a tuple of class or type objects (or recursively, other such tuples), return true if
objectisaninstanceofanyoftheclassesortypes.Ifclassinfoisnotaclass,type,ortupleof
classes,types,andsuchtuples,a TypeError exceptionisraised.

Changedinversion2.2:Supportforatupleoftypeinformationwasadded.
issubclass (class,classinfo)

https://docs.python.org/2/library/functions.html

10/27

8/31/2016

2.BuiltinFunctionsPython2.7.12documentation

Returntrueifclassisasubclass(direct,indirectorvirtual)ofclassinfo.Aclassisconsidereda
subclass of itself. classinfo may be a tuple of class objects, in which case every entry in
classinfowillbechecked.Inanyothercase,a TypeError exceptionisraised.
Changedinversion2.3:Supportforatupleoftypeinformationwasadded.
iter (o[,sentinel])
Returnaniterator object. The first argument is interpreted very differently depending on the
presenceofthesecondargument.Withoutasecondargument,omustbeacollectionobject
whichsupportstheiterationprotocol(the __iter__() method),oritmustsupportthesequence
protocol(the __getitem__() methodwithintegerargumentsstartingat 0 ).Ifitdoesnotsupport
eitherofthoseprotocols, TypeError israised.Ifthesecondargument,sentinel,isgiven,theno
must be a callable object. The iterator created in this case will call o with no arguments for
eachcalltoits next() method if the value returned is equal to sentinel, StopIteration will be
raised,otherwisethevaluewillbereturned.

Oneusefulapplicationofthesecondformof iter() istoreadlinesofafileuntilacertainlineis


reached. The following example reads a file until the readline() method returns an empty
string:
withopen('mydata.txt')asfp:
forlineiniter(fp.readline,''):
process_line(line)

Newinversion2.2.
len (s)
Returnthelength(thenumberofitems)ofanobject.Theargumentmaybeasequence(such
asastring,bytes,tuple,list,orrange)oracollection(suchasadictionary,set,orfrozenset).

class list ([iterable])


Returnalistwhoseitemsarethesameandinthesameorderasiterablesitems.iterablemay
be either a sequence, a container that supports iteration, or an iterator object. If iterable is
already a list, a copy is made and returned, similar to iterable[:] . For instance, list('abc')
returns ['a','b','c'] and list((1,2,3)) returns [1,2,3] .Ifnoargumentisgiven,returns
anewemptylist, [] .
list is a mutable sequence type, as documented in Sequence Types str, unicode, list,

tuple, bytearray, buffer, xrange. For other containers see the built in dict , set , and
classes,andthe collections module.

tuple

locals ()
Updateandreturnadictionaryrepresentingthecurrentlocalsymboltable.Freevariablesare
returnedby locals() whenitiscalledinfunctionblocks,butnotinclassblocks.

Note: Thecontentsofthisdictionaryshouldnotbemodifiedchangesmaynotaffectthe
valuesoflocalandfreevariablesusedbytheinterpreter.
class long (x=0)
https://docs.python.org/2/library/functions.html

11/27

8/31/2016

2.BuiltinFunctionsPython2.7.12documentation

class long (x,base=10)


Returnalongintegerobjectconstructedfromastringornumberx.Iftheargumentisastring,
itmustcontainapossiblysignednumberofarbitrarysize,possiblyembeddedinwhitespace.
Thebaseargumentisinterpretedinthesamewayasfor int() ,andmayonlybegivenwhenx
isastring.Otherwise,theargumentmaybeaplainorlongintegerorafloatingpointnumber,
and a long integer with the same value is returned. Conversion of floating point numbers to
integerstruncates(towardszero).Ifnoargumentsaregiven,returns 0L .
ThelongtypeisdescribedinNumericTypesint,float,long,complex.
map (function,iterable,...)
Apply function to every item of iterable and return a list of the results. If additional iterable
arguments are passed, function must take that many arguments and is applied to the items
fromalliterablesinparallel.Ifoneiterableisshorterthananotheritisassumedtobeextended
with None items. If function is None , the identity function is assumed if there are multiple
arguments, map() returnsalistconsistingoftuplescontainingthecorrespondingitemsfromall
iterables(akindoftransposeoperation).Theiterableargumentsmaybeasequenceor any
iterableobjecttheresultisalwaysalist.
max (iterable[,key])
max (arg1,arg2,*args[,key])
Returnthelargestiteminaniterableorthelargestoftwoormorearguments.

Ifonepositionalargumentisprovided,iterablemustbeanonemptyiterable(suchasanon
emptystring,tupleorlist).Thelargestitemintheiterableisreturned.Iftwoormorepositional
argumentsareprovided,thelargestofthepositionalargumentsisreturned.
The optional key argument specifies a oneargument ordering function like that used for
list.sort() . The key argument, if supplied, must be in keyword form (for example,
max(a,b,c,key=func) ).
Changedinversion2.5:Addedsupportfortheoptionalkeyargument.
memoryview (obj)
Return a memory view object created from the given argument. See memoryview type for
moreinformation.
min (iterable[,key])
min (arg1,arg2,*args[,key])
Returnthesmallestiteminaniterableorthesmallestoftwoormorearguments.

Ifonepositionalargumentisprovided,iterablemustbeanonemptyiterable(suchasanon
empty string, tuple or list). The smallest item in the iterable is returned. If two or more
positionalargumentsareprovided,thesmallestofthepositionalargumentsisreturned.
The optional key argument specifies a oneargument ordering function like that used for
list.sort() . The key argument, if supplied, must be in keyword form (for example,
min(a,b,c,key=func) ).
https://docs.python.org/2/library/functions.html

12/27

8/31/2016

2.BuiltinFunctionsPython2.7.12documentation

Changedinversion2.5:Addedsupportfortheoptionalkeyargument.
next (iterator[,default])
Retrieve the next item from the iterator by calling its next() method. If default is given, it is
returnediftheiteratorisexhausted,otherwise StopIteration israised.

Newinversion2.6.
class object
Returnanewfeaturelessobject. object isabaseforallnewstyleclasses.Ithasthemethods
thatarecommontoallinstancesofnewstyleclasses.
Newinversion2.2.
Changedinversion2.3:Thisfunctiondoesnotacceptanyarguments.Formerly,itaccepted
argumentsbutignoredthem.
oct (x)
Convert an integer number (of any size) to an octal string. The result is a valid Python
expression.

Changedinversion2.4:Formerlyonlyreturnedanunsignedliteral.
open (name[,mode[,buffering]])
Open a file, returning an object of the file type described in section File Objects. If the file
cannotbeopened, IOError israised.Whenopeningafile,itspreferabletouse open() instead
ofinvokingthe file constructordirectly.

The first two arguments are the same as for stdio s fopen() : name is the file name to be
opened,andmodeisastringindicatinghowthefileistobeopened.
Themostcommonlyused values ofmodeare 'r' for reading, 'w' for writing (truncating the
file if it already exists), and 'a' for appending (which on some Unix systems means that all
writesappendtotheendofthefileregardlessofthecurrentseekposition).Ifmodeisomitted,
it defaults to 'r' . The default is to use text mode, which may convert '\n' characters to a
platformspecificrepresentationonwritingandbackonreading.Thus,whenopeningabinary
file, you should append 'b' to the mode value to open the file in binary mode, which will
improveportability.(Appending 'b' isusefulevenonsystemsthatdonttreatbinaryandtext
files differently, where it serves as documentation.) See below for more possible values of
mode.
Theoptionalbufferingargumentspecifiesthefilesdesiredbuffersize:0meansunbuffered,1
meanslinebuffered,anyotherpositivevaluemeansuseabufferof(approximately)thatsize
(inbytes).Anegativebufferingmeanstousethesystemdefault,whichisusuallylinebuffered
forttydevicesandfullybufferedforotherfiles.Ifomitted,thesystemdefaultisused.[2]
Modes 'r+' , 'w+' and 'a+' open the file for updating (reading and writing) note that 'w+'
truncates the file. Append 'b' to the mode to open the file in binary mode, on systems that

https://docs.python.org/2/library/functions.html

13/27

8/31/2016

2.BuiltinFunctionsPython2.7.12documentation

differentiatebetweenbinaryandtextfilesonsystemsthatdonthavethisdistinction,adding
the 'b' hasnoeffect.
Inadditiontothestandard fopen() valuesmodemaybe 'U' or 'rU' .Pythonisusuallybuiltwith
universal newlines support supplying 'U' opens the file as a text file, but lines may be
terminated by any of the following: the Unix endofline convention '\n' , the Macintosh
convention '\r' ,ortheWindowsconvention '\r\n' . All of these external representations are
seenas '\n' by the Python program. If Python is built without universal newlines support a
modewith 'U' isthesameasnormaltextmode.Notethatfileobjectssoopenedalsohavean
attributecalled newlines whichhasavalueof None (ifnonewlineshaveyetbeenseen), '\n' ,
'\r' , '\r\n' ,oratuplecontainingallthenewlinetypesseen.
Pythonenforcesthatthemode,afterstripping 'U' ,beginswith 'r' , 'w' or 'a' .
Python provides many file handling modules including fileinput , os , os.path ,
shutil .

tempfile ,

and

Changedinversion2.5:Restrictiononfirstletterofmodestringintroduced.
ord (c)
Given a string of length one, return an integer representing the Unicode code point of the
characterwhentheargumentisaunicodeobject,orthevalueofthebytewhentheargument
isan8bitstring.Forexample, ord('a') returnstheinteger 97 , ord(u'\u2020') returns 8224 .This
is the inverse of chr() for 8bit strings and of unichr() for unicode objects. If a unicode
argumentisgivenandPythonwasbuiltwithUCS2Unicode,thenthecharacterscodepoint
mustbeinthe range [0..65535] inclusive otherwise the string length istwo,anda TypeError
willberaised.
pow (x,y[,z])
Returnx to the power y if z is present, return x to the power y, modulo z (computed more
efficiently than pow(x, y) % z ). The twoargument form pow(x, y) is equivalent to using the
poweroperator: x**y .

The arguments must have numeric types. With mixed operand types, the coercion rules for
binaryarithmeticoperatorsapply.Forintandlongintoperands,theresulthasthesametype
as the operands (after coercion) unless the second argument is negative in that case, all
argumentsareconvertedtofloatandafloatresultisdelivered.Forexample, 10**2 returns 100 ,
but 10**2 returns 0.01 .(ThislastfeaturewasaddedinPython2.2.InPython2.1andbefore,if
both arguments were of integer types and the second argument was negative, an exception
was raised.) If the second argument is negative, the third argument must be omitted. If z is
present,xandymustbeofintegertypes,andymustbenonnegative.(Thisrestrictionwas
added in Python 2.2. In Python 2.1 and before, floating 3argument pow() returnedplatform
dependentresultsdependingonfloatingpointroundingaccidents.)
print (*objects,sep='',end='\n',file=sys.stdout)
Print objects to the stream file, separated by sep and followed by end. sep, end and file, if
present,mustbegivenaskeywordarguments.

https://docs.python.org/2/library/functions.html

14/27

8/31/2016

2.BuiltinFunctionsPython2.7.12documentation

Allnonkeywordargumentsareconvertedtostringslike str() doesandwrittentothestream,


separatedbysepandfollowedbyend.Bothsepandend must be strings they can also be
None ,whichmeanstousethedefaultvalues.Ifnoobjectsaregiven, print() willjustwriteend.
Thefile argument must be an object with a write(string) method if it is not present or None ,
sys.stdout willbeused.Outputbufferingisdeterminedbyfile.Use file.flush() to ensure, for
instance,immediateappearanceonascreen.
Note: This function is not normally available as a builtin since the name print is
recognized as the print statement.To disable the statement and use the print() function,
usethisfuturestatementatthetopofyourmodule:
from__future__importprint_function

Newinversion2.6.
class property ([fget[,fset[,fdel[,doc]]]])
Returnapropertyattributefornewstyleclasses(classesthatderivefrom object ).
fgetisafunctionforgettinganattributevalue.fsetisafunctionforsettinganattributevalue.
fdelisafunctionfordeletinganattributevalue.Anddoccreatesadocstringfortheattribute.
Atypicaluseistodefineamanagedattribute x :
classC(object):
def__init__(self):
self._x=None
defgetx(self):
returnself._x
defsetx(self,value):
self._x=value
defdelx(self):
delself._x
x=property(getx,setx,delx,"I'mthe'x'property.")

IfcisaninstanceofC, c.x willinvokethegetter, c.x=value willinvokethesetterand delc.x


thedeleter.
Ifgiven,doc will be the docstring of the property attribute. Otherwise, the property will copy
fgetsdocstring(ifitexists).Thismakesitpossibletocreatereadonlypropertieseasilyusing
property() asadecorator:
classParrot(object):
def__init__(self):
self._voltage=100000
@property
defvoltage(self):
"""Getthecurrentvoltage."""
returnself._voltage
https://docs.python.org/2/library/functions.html

15/27

8/31/2016

2.BuiltinFunctionsPython2.7.12documentation

The @property decoratorturnsthe voltage() methodintoagetterforareadonlyattributewith


thesamename,anditsetsthedocstringforvoltagetoGetthecurrentvoltage.
Apropertyobjecthas getter , setter ,and deleter methodsusableasdecoratorsthatcreatea
copy of the property with the corresponding accessor function set to the decorated function.
Thisisbestexplainedwithanexample:
classC(object):
def__init__(self):
self._x=None
@property
defx(self):
"""I'mthe'x'property."""
returnself._x
@x.setter
defx(self,value):
self._x=value
@x.deleter
defx(self):
delself._x

Thiscodeisexactlyequivalenttothefirstexample.Besuretogivetheadditionalfunctionsthe
samenameastheoriginalproperty( x inthiscase.)
Thereturnedpropertyobjectalsohastheattributes fget , fset ,and fdel correspondingtothe
constructorarguments.
Newinversion2.2.
Changedinversion2.5:Usefgetsdocstringifnodocgiven.
Changedinversion2.6:The getter , setter ,and deleter attributeswereadded.
range (stop)
range (start,stop[,step])
This is a versatile function to create lists containing arithmetic progressions. It is most often
usedin for loops.The arguments must be plain integers. If the step argument is omitted, it
defaultsto 1 .Ifthestartargumentisomitted,itdefaultsto 0 .Thefullformreturnsalistofplain
integers [start,start+step,start+2*step,...] .Ifstepispositive,thelastelementisthe
largest start+i*step lessthanstopifstepisnegative,thelastelementisthesmallest start
+i*step greaterthanstop.stepmustnotbezero(orelse ValueError israised).Example:
>>>range(10)
[0,1,2,3,4,5,6,7,8,9]
>>>range(1,11)
[1,2,3,4,5,6,7,8,9,10]
>>>range(0,30,5)
[0,5,10,15,20,25]
>>>range(0,10,3)
[0,3,6,9]
>>>range(0,10,1)
https://docs.python.org/2/library/functions.html

>>>

16/27

8/31/2016

2.BuiltinFunctionsPython2.7.12documentation

[0,1,2,3,4,5,6,7,8,9]
>>>range(0)
[]
>>>range(1,0)
[]

raw_input ([prompt])
Ifthepromptargumentispresent,itiswrittentostandardoutputwithoutatrailingnewline.The
functionthenreadsalinefrominput,convertsittoastring(strippingatrailingnewline),and
returnsthat.WhenEOFisread, EOFError israised.Example:
>>>s=raw_input('>')
>MontyPython'sFlyingCircus
>>>s
"MontyPython'sFlyingCircus"

>>>

Ifthe readline modulewasloaded,then raw_input() willuseittoprovideelaboratelineediting


andhistoryfeatures.
reduce (function,iterable[,initializer])
Applyfunctionoftwoargumentscumulativelytotheitemsofiterable,fromlefttoright,soasto
reduce the iterable to a single value. Forexample, reduce(lambdax,y: x+y, [1, 2, 3, 4, 5])
calculates ((((1+2)+3)+4)+5) . The left argument, x, is the accumulated value and the right
argument, y, is the update value from the iterable. If the optional initializer is present, it is
placed before the items of the iterable in the calculation, and serves as a default when the
iterableisempty.Ifinitializerisnotgivenanditerablecontainsonlyoneitem,thefirstitemis
returned.Roughlyequivalentto:
defreduce(function,iterable,initializer=None):
it=iter(iterable)
ifinitializerisNone:
try:
initializer=next(it)
exceptStopIteration:
raiseTypeError('reduce()ofemptysequencewithnoinitialvalue')
accum_value=initializer
forxinit:
accum_value=function(accum_value,x)
returnaccum_value

reload (module)
Reloadapreviouslyimportedmodule.Theargumentmustbeamoduleobject,soitmusthave
been successfully imported before. This is useful if you have edited the module source file
using an external editor and want to try out the new version without leaving the Python
interpreter.Thereturnvalueisthemoduleobject(thesameasthemoduleargument).

When reload(module) isexecuted:


Python modules code is recompiled and the modulelevel code reexecuted, defining a
new set of objects which are bound to names in the modules dictionary. The init
functionofextensionmodulesisnotcalledasecondtime.
AswithallotherobjectsinPythontheoldobjectsareonlyreclaimedaftertheirreference
countsdroptozero.
https://docs.python.org/2/library/functions.html

17/27

8/31/2016

2.BuiltinFunctionsPython2.7.12documentation

The names in the module namespace are updated to point to any new or changed
objects.
Other references to the old objects (such as names external to the module) are not
reboundtorefertothenewobjectsandmustbeupdatedineachnamespacewherethey
occurifthatisdesired.
Thereareanumberofothercaveats:
When a module is reloaded, its dictionary (containing the modules global variables) is
retained. Redefinitions of names will override the old definitions, so this is generally not a
problem.Ifthenewversionofamoduledoesnotdefineanamethatwasdefinedbytheold
version, the old definition remains. This feature can be used to the modules advantage if it
maintainsaglobaltableorcacheofobjectswitha try statementitcantestforthetables
presenceandskipitsinitializationifdesired:
try:
cache
exceptNameError:
cache={}

Itisgenerallynotveryusefultoreloadbuiltinordynamicallyloadedmodules.Reloading sys ,
__main__ , builtins and other key modules is not recommended. In many cases extension
modulesarenotdesignedtobeinitializedmorethanonce,andmayfailinarbitrarywayswhen
reloaded.
Ifamoduleimportsobjectsfromanothermoduleusing from ... import ...,calling reload() forthe
othermoduledoesnotredefinetheobjectsimportedfromitonewayaroundthisistore
execute the from statement, another is to use import and qualified names (module.*name*)
instead.
Ifamoduleinstantiatesinstancesofaclass,reloadingthemodulethatdefinestheclassdoes
not affect the method definitions of the instances they continue to use the old class
definition.Thesameistrueforderivedclasses.
repr (object)
Return a string containing a printable representation of an object. This is the same value
yielded by conversions (reverse quotes). It is sometimes useful to be able to access this
operationasanordinaryfunction.Formanytypes,thisfunctionmakesanattempttoreturna
string that would yield an object with the same value when passed to eval() , otherwise the
representationisastringenclosedinanglebracketsthatcontainsthenameofthetypeofthe
objecttogetherwithadditionalinformationoftenincludingthenameandaddressoftheobject.
Aclasscancontrolwhatthisfunctionreturnsforitsinstancesbydefininga __repr__() method.
reversed (seq)
Return a reverse iterator. seq must be an object which has a __reversed__() method or
supports the sequence protocol (the __len__() method and the __getitem__() method with
integerargumentsstartingat 0 ).

Newinversion2.4.
Changedinversion2.6:Addedthepossibilitytowriteacustom __reversed__() method.
https://docs.python.org/2/library/functions.html

18/27

8/31/2016

2.BuiltinFunctionsPython2.7.12documentation

round (number[,ndigits])
Return the floating point value number rounded to ndigits digits after the decimal point. If
ndigitsisomitted,itdefaultstozero.Theresultisafloatingpointnumber.Valuesarerounded
to the closest multiple of 10 to the power minus ndigits if two multiples are equally close,
roundingisdoneawayfrom0(so,forexample, round(0.5) is 1.0 and round(0.5) is 1.0 ).

Note: The behavior of round() for floats can be surprising: for example, round(2.675, 2)
gives 2.67 insteadoftheexpected 2.68 .Thisisnotabug:itsaresultofthefactthatmost
decimal fractions cant be represented exactly as a float. See Floating Point Arithmetic:
IssuesandLimitationsformoreinformation.
class set ([iterable])
Return a new set object, optionally with elements taken from iterable. set is a builtin class.
See set andSetTypesset,frozensetfordocumentationaboutthisclass.
For other containers see the builtin frozenset , list , tuple , and dict classes, as well as the
collections module.
Newinversion2.4.
setattr (object,name,value)
This is the counterpart of getattr() . The arguments are an object, a string and an arbitrary
value.Thestringmaynameanexistingattributeoranewattribute.Thefunctionassignsthe
value to the attribute, provided the object allows it. Forexample, setattr(x, 'foobar', 123) is
equivalentto x.foobar=123 .

class slice (stop)


class slice (start,stop[,step])
Returnasliceobjectrepresentingthesetofindicesspecifiedby range(start,stop,step) .The
start and step arguments default to None . Slice objects have readonly data attributes start ,
stop and step whichmerelyreturntheargumentvalues(ortheirdefault).Theyhavenoother
explicit functionality however they are used by Numerical Python and other third party
extensions. Slice objects are also generated when extended indexing syntax is used. For
example: a[start:stop:step] or a[start:stop,i] .See itertools.islice() foranalternateversion
thatreturnsaniterator.
sorted (iterable[,cmp[,key[,reverse]]])
Returnanewsortedlistfromtheitemsiniterable.

The optional arguments cmp, key, and reverse have the same meaning as those for the
list.sort() method(describedinsectionMutableSequenceTypes).
cmp specifies a custom comparison function of two arguments (iterable elements) which
shouldreturnanegative,zeroorpositivenumberdependingonwhetherthefirstargumentis
considered smaller than, equal to, or larger than the second argument: cmp=lambda x,y:
cmp(x.lower(),y.lower()) .Thedefaultvalueis None .

https://docs.python.org/2/library/functions.html

19/27

8/31/2016

2.BuiltinFunctionsPython2.7.12documentation

keyspecifiesafunctionofoneargumentthatisusedtoextractacomparisonkeyfromeach
listelement: key=str.lower .Thedefaultvalueis None (comparetheelementsdirectly).
reverse is a boolean value. If set to
comparisonwerereversed.

True ,

then the list elements are sorted as if each

In general, the key and reverse conversion processes are much faster than specifying an
equivalent cmp function. This is because cmp is called multiple times for each list element
whilekeyandreversetoucheachelementonlyonce.Use functools.cmp_to_key() toconvertan
oldstylecmpfunctiontoakeyfunction.
Thebuiltin sorted() functionisguaranteedtobestable.Asortisstableifitguaranteesnotto
change the relative order of elements that compare equal this is helpful for sorting in
multiplepasses(forexample,sortbydepartment,thenbysalarygrade).
Forsortingexamplesandabriefsortingtutorial,seeSortingHOWTO.
Newinversion2.4.
staticmethod (function)
Returnastaticmethodforfunction.

A static method does not receive an implicit first argument. To declare a static method, use
thisidiom:
classC(object):
@staticmethod
deff(arg1,arg2,...):
...

The @staticmethod form is a function decorator see the description of function definitions in
Functiondefinitionsfordetails.
Itcanbecalledeitherontheclass(suchas C.f() )oronaninstance(suchas C().f() ). The
instanceisignoredexceptforitsclass.
StaticmethodsinPythonaresimilartothosefoundinJavaorC++.Alsosee classmethod() for
avariantthatisusefulforcreatingalternateclassconstructors.
For more information on static methods, consult the documentation on the standard type
hierarchyinThestandardtypehierarchy.
Newinversion2.2.
Changedinversion2.4:Functiondecoratorsyntaxadded.
class str (object='')
Return a string containing a nicely printable representation of an object. For strings, this
returns the string itself. The difference with repr(object) is that str(object) does not always
attempttoreturnastringthatisacceptableto eval() itsgoalistoreturnaprintablestring.If
noargumentisgiven,returnstheemptystring, '' .
https://docs.python.org/2/library/functions.html

20/27

8/31/2016

2.BuiltinFunctionsPython2.7.12documentation

For more information on strings see Sequence Types str, unicode, list, tuple, bytearray,
buffer, xrange which describes sequence functionality (strings are sequences), and also the
stringspecific methods described in the String Methods section. To output formatted strings
usetemplatestringsorthe % operatordescribedintheStringFormattingOperations section.
InadditionseetheStringServicessection.Seealso unicode() .
sum (iterable[,start])
Sumsstartandtheitemsofaniterablefromlefttorightandreturnsthetotal.startdefaultsto
0 .Theiterablesitemsarenormallynumbers,andthestartvalueisnotallowedtobeastring.

For some use cases, there are good alternatives to sum() . The preferred, fast way to
concatenateasequenceofstringsisbycalling ''.join(sequence) .Toaddfloatingpointvalues
withextendedprecision,see math.fsum() .Toconcatenateaseriesofiterables,considerusing
itertools.chain() .
Newinversion2.3.
super (type[,objectortype])
Returnaproxyobjectthatdelegatesmethodcallstoaparentorsiblingclassoftype.Thisis
usefulforaccessinginheritedmethodsthathavebeenoverriddeninaclass.Thesearchorder
issameasthatusedby getattr() exceptthatthetypeitselfisskipped.

The

__mro__

attribute of the type lists the method resolution search order used by both

getattr() and super() . The attribute is dynamic and can change whenever the inheritance

hierarchyisupdated.
If the second argument is omitted, the super object returned is unbound. If the second
argument is an object, isinstance(obj,type) must be true. If the second argument is a type,
issubclass(type2,type) mustbetrue(thisisusefulforclassmethods).
Note: super() onlyworksfornewstyleclasses.
Therearetwotypicalusecasesforsuper.Inaclasshierarchywithsingleinheritance,super
canbeusedto refer to parent classes without naming them explicitly, thusmakingthecode
more maintainable. This use closely parallels the use of super in other programming
languages.
The second use case is to support cooperative multiple inheritance in a dynamic execution
environment. This use case is unique to Python and is not found in statically compiled
languages or languages that only support single inheritance. This makes it possible to
implement diamond diagrams where multiple base classes implement the same method.
Gooddesigndictatesthatthismethodhavethesamecallingsignatureineverycase(because
theorderofcallsisdeterminedatruntime,becausethatorderadaptstochangesintheclass
hierarchy, and because that order can include sibling classes that are unknown prior to
runtime).
Forbothusecases,atypicalsuperclasscalllookslikethis:

https://docs.python.org/2/library/functions.html

21/27

8/31/2016

2.BuiltinFunctionsPython2.7.12documentation

classC(B):
defmethod(self,arg):
super(C,self).method(arg)

Note that super() is implemented as part of the binding process for explicit dotted attribute
lookups such as super().__getitem__(name) . It does so by implementing its own
__getattribute__() method for searching classes in a predictable order that supports
cooperative multiple inheritance. Accordingly, super() is undefined for implicit lookups using
statementsoroperatorssuchas super()[name] .
Alsonotethat super() isnotlimitedtouseinsidemethods.Thetwoargumentformspecifies
theargumentsexactlyandmakestheappropriatereferences.
For practical suggestions on how to design cooperative classes using super() , see guide to
usingsuper().
Newinversion2.2.
tuple ([iterable])
Returnatuplewhoseitemsarethesameandinthesameorderasiterablesitems.iterable
may be a sequence, a container that supports iteration, or an iterator object. If iterable is
alreadyatuple,itisreturnedunchanged.Forinstance, tuple('abc') returns ('a','b','c') and
tuple([1,2,3]) returns (1,2,3) .Ifnoargumentisgiven,returnsanewemptytuple, () .
tuple isanimmutablesequencetype,asdocumentedinSequenceTypesstr,unicode,list,

tuple, bytearray, buffer, xrange. For other containers see the built in
classes,andthe collections module.

dict , list ,

and

set

class type (object)


class type (name,bases,dict)
With one argument, return the type of an object. The return value is a type object. The
isinstance() builtinfunctionisrecommendedfortestingthetypeofanobject.
Withthreearguments,returnanewtypeobject.Thisisessentiallyadynamicformofthe class
statement.Thenamestringistheclassnameandbecomesthe __name__ attributethebases
tupleitemizesthebaseclassesandbecomesthe __bases__ attributeandthedictdictionaryis
thenamespacecontaining definitions for class body and becomesthe __dict__ attribute. For
example,thefollowingtwostatementscreateidentical type objects:
>>>classX(object):
...a=1
...
>>>X=type('X',(object,),dict(a=1))

>>>

Newinversion2.2.
unichr (i)
ReturntheUnicodestringofonecharacterwhoseUnicodecodeistheintegeri.Forexample,
unichr(97) returns the string u'a' . This is the inverse of ord() for Unicode strings. The valid
range for the argument depends how Python was configured it may be either UCS2
https://docs.python.org/2/library/functions.html

22/27

8/31/2016

2.BuiltinFunctionsPython2.7.12documentation

[0..0xFFFF]orUCS4[0..0x10FFFF]. ValueError israisedotherwise.ForASCIIand8bitstrings


see chr() .
Newinversion2.0.
unicode (object='')
unicode (object[,encoding[,errors]])
ReturntheUnicodestringversionofobjectusingoneofthefollowingmodes:

Ifencodingand/orerrorsaregiven, unicode() willdecodetheobjectwhichcaneitherbean8


bit string or a character buffer using the codec for encoding. The encoding parameter is a
stringgivingthenameofanencodingiftheencodingisnotknown, LookupError israised.Error
handling is done according to errors this specifies the treatment of characters which are
invalidintheinputencoding.Iferrorsis 'strict' (thedefault),a ValueError israisedonerrors,
whileavalueof 'ignore' causeserrorstobesilentlyignored,andavalueof 'replace' causes
the official Unicode replacement character, U+FFFD , to be used to replace input characters
whichcannotbedecoded.Seealsothe codecs module.
Ifnooptionalparametersaregiven, unicode() willmimicthebehaviourof str() except that it
returnsUnicodestringsinsteadof8bitstrings.Moreprecisely,ifobjectisaUnicodestringor
subclassitwillreturnthatUnicodestringwithoutanyadditionaldecodingapplied.
Forobjectswhichprovidea __unicode__() method,itwillcallthismethodwithoutargumentsto
create a Unicode string. For all other objects, the 8bit string version or representation is
requestedandthenconvertedtoaUnicodestringusingthecodecforthedefaultencodingin
'strict' mode.
For more information on Unicode strings see Sequence Types str, unicode, list, tuple,
bytearray, buffer, xrange which describes sequence functionality (Unicode strings are
sequences),andalsothestringspecificmethodsdescribedintheStringMethodssection.To
output formatted strings use template strings or the % operator described in the String
FormattingOperationssection.InadditionseetheStringServicessection.Seealso str() .
Newinversion2.0.
Changedinversion2.2:Supportfor __unicode__() added.
vars ([object])
Returnthe __dict__ attributeforamodule,class,instance,oranyotherobjectwitha __dict__
attribute.

Objectssuchasmodulesandinstanceshaveanupdateable __dict__ attributehowever,other


objectsmayhavewriterestrictionsontheir __dict__ attributes(forexample,newstyleclasses
useadictproxytopreventdirectdictionaryupdates).
Without an argument, vars() acts like locals() . Note, the locals dictionary is only useful for
readssinceupdatestothelocalsdictionaryareignored.
xrange (stop)
https://docs.python.org/2/library/functions.html

23/27

8/31/2016

2.BuiltinFunctionsPython2.7.12documentation

xrange (start,stop[,step])
Thisfunctionisverysimilarto range() ,butreturnsanxrangeobjectinsteadofalist.Thisisan
opaque sequence type which yields the same values as the corresponding list, without
actually storing them all simultaneously. The advantage of xrange() over range() is minimal
(since xrange() stillhastocreatethevalueswhenaskedforthem)exceptwhenaverylarge
range is used on a memorystarved machine or when all of the ranges elements are never
used(suchaswhentheloopisusuallyterminatedwith break ).Formoreinformationonxrange
objects,seeXRangeTypeandSequence Types str, unicode, list, tuple, bytearray, buffer,
xrange.

CPython implementation detail: xrange() is intended to be simple and fast.


Implementations may impose restrictions to achieve this. TheCimplementationofPython
restrictsallargumentstonativeClongs(shortPythonintegers),andalsorequiresthatthe
numberofelementsfitinanativeClong.Ifalargerrangeisneeded,analternateversion
can be crafted using the itertools module: islice(count(start, step), (stopstart+step1+2*
(step<0))//step) .

zip ([iterable,...])
Thisfunctionreturnsalistoftuples,wheretheithtuplecontainstheithelementfromeachof
theargumentsequencesoriterables.Thereturnedlististruncatedinlengthtothelengthof
the shortest argument sequence. When there are multiple arguments which are all of the
samelength, zip() issimilarto map() withaninitialargumentof None .Withasinglesequence
argument,itreturnsalistof1tuples.Withnoarguments,itreturnsanemptylist.

Thelefttorightevaluationorderoftheiterablesisguaranteed.Thismakespossibleanidiom
forclusteringadataseriesintonlengthgroupsusing zip(*[iter(s)]*n) .
zip() inconjunctionwiththe * operatorcanbeusedtounzipalist:

>>>x=[1,2,3]
>>>y=[4,5,6]
>>>zipped=zip(x,y)
>>>zipped
[(1,4),(2,5),(3,6)]
>>>x2,y2=zip(*zipped)
>>>x==list(x2)andy==list(y2)
True

>>>

Newinversion2.0.
Changed in version 2.4: Formerly, zip() required at least one argument and zip() raised a
TypeError insteadofreturninganemptylist.
__import__ (name[,globals[,locals[,fromlist[,level]]]])

Note: ThisisanadvancedfunctionthatisnotneededineverydayPythonprogramming,
unlike importlib.import_module() .

https://docs.python.org/2/library/functions.html

24/27

8/31/2016

2.BuiltinFunctionsPython2.7.12documentation

This function is invoked by the import statement. It can be replaced (by importing the
__builtin__ module and assigning to __builtin__.__import__ ) in order to change semantics of
the import statement,butnowadaysitisusuallysimplertouseimporthooks(seePEP302).
Directuseof __import__() israre,exceptincaseswhereyouwanttoimportamodulewhose
nameisonlyknownatruntime.
The function imports the module name, potentially using the given globals and locals to
determine how to interpret the name in a package context. The fromlist gives the names of
objectsorsubmodulesthatshouldbeimportedfromthemodulegivenbyname.Thestandard
implementationdoesnotuseitslocalsargumentatall,andusesitsglobalsonlytodetermine
thepackagecontextofthe import statement.
level specifies whether to use absolute or relative imports. The default is 1 which indicates
bothabsoluteandrelativeimportswillbeattempted. 0 meansonlyperformabsoluteimports.
Positive values for level indicate the number of parent directories to search relative to the
directoryofthemodulecalling __import__() .
When the name variable is of the form package.module , normally, the toplevel package (the
nameuptillthefirstdot)isreturned,notthemodulenamedbyname.However,whenanon
emptyfromlistargumentisgiven,themodulenamedbynameisreturned.
Forexample,thestatement importspam resultsinbytecoderesemblingthefollowingcode:
spam=__import__('spam',globals(),locals(),[],1)

Thestatement importspam.ham resultsinthiscall:


spam=__import__('spam.ham',globals(),locals(),[],1)

Note how __import__() returns the toplevel module here because this is the object that is
boundtoanamebythe import statement.
Ontheotherhand,thestatement fromspam.hamimporteggs,sausageassaus resultsin
_temp=__import__('spam.ham',globals(),locals(),['eggs','sausage'],1)
eggs=_temp.eggs
saus=_temp.sausage

Here,the spam.ham moduleisreturnedfrom __import__() .Fromthisobject,thenamestoimport


areretrievedandassignedtotheirrespectivenames.
If you simply want to import a module (potentially within a package) by name, use
importlib.import_module() .
Changedinversion2.5:Thelevelparameterwasadded.
Changedinversion2.5:Keywordsupportforparameterswasadded.

3. Nonessential Builtin Functions


https://docs.python.org/2/library/functions.html

25/27

8/31/2016

2.BuiltinFunctionsPython2.7.12documentation

There are several builtin functions that are no longer essential to learn, know or use in modern
Python programming. They have been kept here to maintain backwards compatibility with
programswrittenforolderversionsofPython.
Python programmers, trainers, students and book writers should feel free to bypass these
functionswithoutconcernsaboutmissingsomethingimportant.
apply (function,args[,keywords])
Thefunctionargumentmustbeacallableobject(auserdefinedorbuiltinfunctionormethod,
oraclassobject)andtheargsargumentmustbeasequence.Thefunctioniscalledwithargs
as the argument list the number of arguments is the length of the tuple. If the optional
keywords argument is present, it must be a dictionary whose keys are strings. It specifies
keyword arguments to be added to the end of the argument list. Calling apply() is different
fromjustcalling function(args) ,sinceinthatcasethereisalwaysexactlyoneargument.The
useof apply() isequivalentto function(*args,**keywords) .

Deprecated since version 2.3: Use function(*args, **keywords) instead of


args,keywords) (seeUnpackingArgumentLists).

apply(function,

buffer (object[,offset[,size]])
Theobjectargumentmustbeanobjectthatsupportsthebuffercallinterface(suchasstrings,
arrays,andbuffers).Anewbufferobjectwillbecreatedwhichreferencestheobjectargument.
Thebufferobjectwillbeaslicefromthebeginningofobject(orfromthespecifiedoffset).The
slicewillextendtotheendofobject(orwillhavealengthgivenbythesizeargument).
coerce (x,y)
Return a tuple consisting of the two numeric arguments converted to a common type, using
thesamerulesasusedbyarithmeticoperations.Ifcoercionisnotpossible,raise TypeError .
intern (string)
Enter string in the table of interned strings and return the interned string which is string
itselforacopy.Interningstringsisusefultogainalittleperformanceondictionarylookupif
the keys in a dictionary are interned, and the lookup key is interned, the key comparisons
(afterhashing)canbedonebyapointercompareinsteadofastringcompare.Normally, the
namesusedinPythonprogramsareautomaticallyinterned,andthedictionariesusedtohold
module,classorinstanceattributeshaveinternedkeys.

Changedinversion2.3:Internedstringsarenotimmortal(liketheyusedtobeinPython2.2
andbefore)youmustkeepareferencetothereturnvalueof intern() aroundtobenefitfrom
it.
Footnotes
[1] Itisusedrelativelyrarelysodoesnotwarrantbeingmadeintoastatement.
[2] Specifyingabuffersizecurrentlyhasnoeffectonsystemsthatdonthave setvbuf() .The
interfacetospecifythebuffersizeisnotdoneusingamethodthatcalls setvbuf() ,because
thatmaydumpcorewhencalledafteranyI/Ohasbeenperformed,andtheresnoreliable
waytodeterminewhetherthisisthecase.
https://docs.python.org/2/library/functions.html

26/27

8/31/2016

2.BuiltinFunctionsPython2.7.12documentation

[3] Inthecurrentimplementation,localvariablebindingscannotnormallybeaffectedthisway,
butvariablesretrievedfromotherscopes(suchasmodules)canbe.Thismaychange.

https://docs.python.org/2/library/functions.html

27/27

You might also like