Python 2.7 Built-In Functions
Python 2.7 Built-In Functions
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
>>>
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.
https://docs.python.org/2/library/functions.html
7/27
8/31/2016
2.BuiltinFunctionsPython2.7.12documentation
filter(function, iterable)
and
dict
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
>>>hex(255)
'0xff'
>>>hex(42)
'0x2a'
>>>hex(1L)
'0x1L'
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)) .
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.
Newinversion2.2.
len (s)
Returnthelength(thenumberofitems)ofanobject.Theargumentmaybeasequence(such
asastring,bytes,tuple,list,orrange)oracollection(suchasadictionary,set,orfrozenset).
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
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
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.")
15/27
8/31/2016
2.BuiltinFunctionsPython2.7.12documentation
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"
>>>
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).
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 .
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 ,
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
>>>
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
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.
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)
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
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) .
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