# Python Programming – Compound statement Built-in functions

In this Page, We are Providing Python Programming – Compound statement Built-in functions. Students can visit for more Detail and Explanation of Python Handwritten Notes Pdf.

## Python Programming – Compound statement Built-in functions

Built-in functions

Till now, the discussed functions need to be defined before using it in a program; such functions are called user-defined functions. Python has a number of functions that are always available. These are called built-in functions. They are listed here in alphabetical order.

                   abs ( )                                  all ( )                                          any ( )
basestring ( )                       bin ( )                                        bool ( )
bytearray ( )                        callable ( )                                 chr ( )
classmethod ( )                   cmp ( )                                       compile ( )
complex ( )                          delattr ( )                                    diet ( )
dir ( )                                   divmod ( )                                  enumerate ( )
eval ( )                                  execfile ( )                                   file ( )
filter ( )                                float ( )                                      format ( )
frozenset ( )                        getattr ( )                                   globals ( )
hasattr ( )                            hash ( )                                         help ( )
hex ( )                                 id ( )                                            input ( )
int ( )                                  isinstance ( )                             issubclass ( )
iter ( )                                  len ( )                                         list ( )
locals ( )                             long ( )                                         map ( )
max ( )                               memoryview ( )                            min ( )
next ( )                              object ( )                                        oct ( )
open ( )                              ord ( )                                           pow ( )
print ( )                            property ( )                                      range ( )
raw_input ( )                      reduce ( )                                     reload ( )
repr ( )                              reversed ( )                                   round ( )
set ( )                                setattr ( )                                        slice ( )
sorted ( )                           staticmethod ( )                              str ( )
sum ( )                               super ( )                                         tuple ( )
type ( )                               unichr ( )                                       Unicode ( )
vars ( )                              xrange ( )                                        zip ( )
import ( )                           apply ( )                                         buffer ( )
coerce ( )                          intern ( )

Some of the above built-in functions are discussed below:

abs ( x )
Return the absolute value of a number. The argument may be a plain or long integer or a floating-point number. If the argument is a complex number, its magnitude is returned.

>>> abs ( - 34 )
34
>>> abs ( 34 . 5 )
34 . 5
>>> abs ( -3 -4 j )
5 . 0

all ( iterable )
Return True, if all elements of the iterable are true (or if the iterable is empty).

>>> all ( [ True , 10 ] )
True
>>> all ( [ True , 10 , 0 ] )
False
>>> all ( ( ) )
True

any ( iterable )
Return True, if any element of the iterable is true. If the iterable is empty, return False.

>>> any ( [ 0 , 5 , -3 ] )
True
>>> any (  [0 , False  , -3 ] )
True
>>> any ( ( ) )
False

bin ( x )
Convert an integer number to a binary string.

>>> bin ( 8 )
' 0b1000 '
>>> bin ( 27 )
' 0b11011 '
>>> (27) . hit_length ( )
5
>>> bin ( -1327 )
' -0b100101111 '
>>> ( -1327 ) . bit_length ( )
11

bool ( [ x ] )
Convert a value to a boolean. If x is false or omitted, this returns False; otherwise, it returns True. If no argument is given, this function returns False.

>>> bool ( 5 )
True
>>> bool ( -5 )
True
>>> bool ( 0 )
False
>>> bool ( ' hi ' )
True
>>> bool ( )
False
>>> bool ( '' )
False
>>> bool ( None )
False
>>> bool ( ' \ n ' )
True
>>> bool ( [ 0 ] )
True
>>> bool ( ( None , ) )
True

chr ( i )
Return a string of one character whose ASCII-8 code is the integer i. This is the inverse of ord ( ). The argument must be in the range [0,255]; ValueError will be raised if i is outside that range.

>>> for i in range ( 33 , 95 ) : print i , ' =  ' , chr ( i )
. . .
33 = !
34 = "
35 = #
36 = \$
3 7 = %
38 = &
39 = '
40 = (
41 = )
42 = *
43 = +
44 = ,
45 = -
46 = .
47 = /
48 = 0
49 = 1
50 = 2
51 = 3
52 = 4
53 = 5
55 = 7
56 = 8
57 = 9
58 = :
59 = ;
60 = <
61 = =
62 = >
63 = ?
64 = 0
65 = A
66 = B
67 = C
68 = D
69 = E
70 = F
71 = G
72 = H
73 = I
74 = J
75 = K
76 = L
77 = M
78 = N
79 = O
80 = P
81 = Q
82 = R
83 = S
84 = T
85 = U
86 = V
87 = W
88 = X
89 = Y
90 = Z
91 = [
92 = \
93 = ]
94 = A

cmp ( x , y )
Compare the two objects x and y, and return an integer according to the outcome. The returned value is negative, if xc’y, zero, if x==y, and strictly positive, if x>y.

>>> cmp ( 2 . 5 , 5 . 2 )
-1
>>> cmp ( 5 . 2 , 5 . 2 )
0
>>> cmp ( 5 . 2 , 2 . 5 )
1
>>> cmp ( ' hi ' , ' hello ’ )
1
>>> cmp ( 'hello ' , ' hi ' )
-1

complex ( [ real [ , imag ] ] )
Create a complex number with the value real+imag* j, or convert a string or number to a complex number. If the first parameter is a string, it will be interpreted as a complex number and the function must be called without a second parameter. The second parameter can never be a string. Each argument may be any numeric type (including complex).

If imag is omitted, it defaults to zero. If both arguments are omitted, the function returns 0 j. When converting from a string, the string must not contain whitespace around the central + or – operator. For example, complex ( ‘ 1 + 2 j ‘ ) is fine, but complex (‘1 + 2 j ‘ ) raises ValueError.

>>> complex ( )
Oj
>>> complex ( 2 . 51 )
( 2 . 51+0 j )
>>> complex ( 2 . 51 , 4 . 79 )
( 2 . 51+4 . 79 j )
>>> c1=4+5 j
>>> c2=6+7 j
>>> complex(c1,c2)                                    # Equals ( 4+5 j ) + ( 6+7 j ) j = 4+5 j+6 j - 7
( -3+11 j )
>>> c= ' 7 '
>>> complex (c)
( 7+0 j )
>>> c=' 7 + 4 j '
>>> complex (c)
( 7+4 j )
>>> x=2+3 j
>>> x . real
2 . 0
>>> x . imag
3 . 0

delattr ( object , name )
This is a relative of setattr ( ). The arguments are an object and a string. The string must be the name of one of the object’s attributes. The function deletes the named attribute, provided the object allows it.

>>> class new__cls:
. . .                   def ______init_______ ( self , x ) :
. . .                   self. x=x
. . .
>>> tt=new__cls ( 10 )
>>> tt . x
10
>>> setattr ( tt ,' x ' , 20 )
>>> tt . x
20
>>> setattr ( tt, ' y ' ' hello ' )
>>> tt.y
' hello '
>>> delattr ( tt , ' x ' )
>>> tt . x
Traceback ( most recent call last ) :
File "<stdin>", line 1 , in <module>
AttributeError: new__cls instance has no attribute ’ x ’

divmod ( a , b )
Take two (non-complex) numbers as arguments and return a pair of numbers consisting of their quotient and remainder.

>>> divmod ( 13 . 5 , 3 )
( 4 . 0 , 1 . 5 )
>>> divmod ( 13 , 3 )
( 4 , 1 )

enumerate ( sequence , start=0 )
Return an enumerate object. The sequence argument must be a sequence, an iterator, or some other object which supports iteration, while start is a count (default argument as 0).

>>> seasons=[ ' Spring ' , ' Summer ' , ' Fall ' , ' Winter ' ]
>>> list (enumerate ( seasons ) )
[ ( 0 ,' Spring ' ) , ( 1 , ' Summer ' ) , ( 2 , ' Fall ' ) , ( 3 , ' Winter ' ) ]
>>> list (enumerate ( seasons , start=2 ) )
[ ( 2 ,' Spring ' ) , ( 3 , ' Summer ' ) , ( 4 , ' Fall ' ) , ( 5 , ' Winter ' ) ]
>>> for num , seasn in enumerate ( seasons , start=1 ) :
. . . print "[{0}] {1 } " . format ( num , seasn )
. . .
[1] Spring
[2] Summer
[3] Fall
[4] Winter

filter ( function , iterable )
Create a list from those elements of iterable for which function returns True. The iterable may be either a sequence, a container that supports iteration, or an iterator. If iterable is a string or a tuple, the result also has that type, otherwise, it will be a list. If function is None, the identity function is assumed, that is, all elements of iterable that are false are removed.

>>> def isOdd ( x ) :
. . .               if ( x % 2 )==1: return True
. . .               else : return False
>>> filter ( isOdd, [88 , 43 , 65 ,-11 ,202 ] )
[ 43, 65, -11 ]
>>>
>>> def isLetter ( c ) : return c . isalpha ( )
. . .
>>> filter ( isLetter,"01234abcdeFGHIJ* ( &!∧")
' abcdeFGHIJ '
>>> list= [ 0, 1, ( ) , (2, ) , 0 . 0, 0 . 25 ]
>>> filter ( None , list )
[1 , (2 ,), 0 . 25 ]
>>> filter ( boo1 , list )
[ 1 , ( 2 , ) , 0 . 25 ]

getattr ( object , name [ , default ] )
Return the value of the named attribute of the object; the name must be a string. If the string is the name of one of the object’s attributes, the result is the value of that attribute. If the named attribute does not exist, default is returned if provided, otherwise, AttributeError is raised. For example, a complex number object has real and imag attributes.

>>> a=3 . 5 + 4 . 9 J
>>> type ( a )
<type ' complex '>
>>> getattr ( a , ' real ' )
3 . 5
>>> getattr (a , ' imag ' )
4 . 9
>>> getattr ( a ,' imagine ' , 2 . 2 )
2 . 2

globals ( )
Return a dictionary representing the current global symbol table. The following script “GlobalScope.py” gives some idea about the use of this function.

# Filemame: GlobalScope . py
var1=10
def func (  ):
var2=20
func ( )
if ' var1 ' in globals ( ) . keys ( ) :
print "'var1' is a global variable of this module"
if 'var2' in globals ( ) . keys ( ) :
print "'var2' is a global variable of this module"

The output is:

’ var1 ' is a global variable of this module

hasattr ( object , name )
The arguments are an object and a string. The result is True, if the string is the name of one of the object’s attributes, otherwise False.

>>> a=3.5+4.9 J
>>> hasattr( a , ' imag ' )
True
>>> hasattr ( a,' imagine ' )
False

hash ( )
In computing, a hash table (also “hash map”) is a data structure that can map keys to values. A hash table uses a hash function to compute an index (or hash value) into an array of buckets or slots, from which the correct value can be found. The built-in function hash ( ) return the hash value of the object (if it has one) which is basically an integer and it never changes during its lifetime.

Hashability makes an object usable as a dictionary key and a set member because these data structures use the hash value internally. All of Python’s immutable built-in objects are hashable, while no mutable containers (such as lists or dictionaries) are hashable.

>>> d= { ' Lisa ' : 88 . 5 , ' John ' : 69 . 73 , ' Mike ' : 88 . 5 }
>>> hash ( d [ ' Lisa 1 ' ] )
1485012992
>>> hash ( d [ ' John ' ] )
-1664573625
>>> hash ( d [ ' Mike ' ] )
1485012992

Consider the following example :

>>> map ( hash , ( " namea " , " nameb " , " namec " , " named " ) )
[-1658398457 , -1658398460 , -1658398459 , -1658398462 ]
>>> map ( hash , ( 0 , 1 , 2 , 3 ) )
[ 0 , 1 , 2 , 3 ]

It can be observed that the strings are quite close in their letters, and their hashes are close in terms of numerical distance which is desirable behavior. If the keys are close in nature, one wants their hashes to be close as well so that lookups remain fast. Integers have the same hash value as themselves.

help ( [ object ] )
This function invokes the built-in help system (this function is intended for interactive use). If no argument is given, the interactive help system starts on the interpreter console. If the argument is a string, then the string is looked up as the name of a module, function, class, method, keyword, or documentation topic, and a help page is printed on the console. If the argument is any other kind of object, a help page on the object is generated.

>>> help (cmp)
Help on built-in function cmp in module ____builtin____ :
cmp ( . . . )
cmp ( x , y ) -> integer

Return negative if x<y , zero if x==y , positive if x>y .

hex ( x )
Convert an integer number (of any size) to a hexadecimal string. To obtain a hexadecimal string representation for a float, use the float. hex ( ) method.

>>> hex ( 25 )
' 0x19 '

id ( object )
Return the identity of the object. This is an integer (or long integer) which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id ( ) value.

>>> a=5
>>> id ( a )
3885104
>>> b= ' hello '
>>> id ( b )
44148000

input ( [ prompt ] )
This function is used to take input from user and evaluates the expression. There is also raw_input ( ) function which takes input from user, convert it to a string, and returns that.

>>> aa=4
>>> bb=6
>>> resultl=input( ' ----> ' )
- - - >aa+bb
>>> result2=raw__input ( ' ---> ' )
----->aa+bb
>>>
>>> result1
10
>>> result2
' aa+bb '



isinstance ( object , classinfo )
Return True, if the object argument is an instance of the classinfo argument, or of a subclass thereof.

>>> class new__cls :
. . .        def _____init______ ( self , x ) :
. . .              self . x=x
. . .
>>> tt=new_cls ( 10 )
>>> isinstance ( tt , new_cls )
True

Also return True, if classinfo is a type object, and an object is an object of that type or of a subclass thereof. If the object is not a class instance or an object of the given type, the function always returns False.

>>> i=5
>>> type ( i )
<type ' int '>
>>> type ( int )
<type ' type ' >
>>> isinstance ( i , int )
True
>>> isinstance ( i , str )
False

If classinfo is neither a class object nor a type object, it may be a tuple of class or type objects (other sequence types are not accepted). If classinfo is not a class, type, or tuple of classes, types, a TypeError exception is raised.

>>> isinstance( i ,( str , int , float , complex ) )
True

issubcTass ( class , classinfo )
Return True, if class is a subclass of classinfo.

>>> class A:
. . .        pass
. . .
class B(A):
. . .        pass
. . .
>>> class C:
. . .         pass
. . .
>>> class D:
. . .        pass
. . .
>>> issubclass ( B, A )
True

A class is considered a subclass of itself.

>>> issubclass ( D , D )
True

The classinfo may be a tuple of class objects, in which case every entry in classinfo will be checked. In any other case, a TypeError exception is raised.

>>> issubclass ( B , ( A , C , D ) )
True

len ( s )
Return the length (the number of items) of an object s. The argument may be a sequence (string, tuple or list) or a mapping (dictionary).

>>> len ( ' abed ' )
4
>>> seq=[ ' a ' , ' b ' , ' c ' , ' d ' ]
>>> len ( seq )
4
>>> seq= ( ' a ' , 'b \ 'c \ 'd')
>>> len ( seq )
4
>>> dict= { ' a ' : 8 , ' b ' :  9 , ' c ' : 10 , ' d ' : 11 }
>>> len ( diet )
4 '
>>> len ( ' ' )
0

locals ( )
The function returns a dictionary representing the current local symbol table.

# ! / usr / bin / env python
# Filemame: LocalScope . py
var1=10
var2=20
def func ( ) :
var3=30
var4=40
print ' Local variables of func ( ) = ',locals ( )
func ( )
if 'var1' in locals ( ).keys ( ) and 'var2' in locals ( ) . keys( ) :
print "'var1': and ' var2 ' are local variables of this module"

Output is:

Local variables of func( )= { ' var4 ' : 40 , ' var3 ' : 30 }
' var1 ' and ' var2 ' are local variables of this module

map ( function,iterable, . . . )
Apply function to every item of iterable and return a list of the results. If additional iterable arguments are passed, the function must take that many arguments and is applied to the items from all iterables in parallel. If one iterable is shorter than another, it is assumed to be extended with None items.

If the function is None, the identity function is assumed; if there are multiple arguments, map ( ) returns a list consisting of tuples containing the corresponding items from all iterables. The iterable arguments may be a sequence or any iterable object; the result is always a list.

>>> def add100 ( x ) :
. . .        return x+100
. . .
>>> map ( add100 , ( 44 , 22 , 66 ) )
[ 144 , 122 , 166 ]
>>>
>>> def abc ( a , b , c ) :
. . .        return a*10000+b*100+c
. . .
>>> map ( abc , ( 1 , 2 , 3 ) , ( 4 , 5 , 6 ) , ( 7 , 8 , 9 ) )
[ 10407 , 20508 , 30609 ]
>>>
>>> map ( None , range ( 3 ) )
[ 0 , 1 , 2 ]
>>> map (None,range ( 3 ) , ' abc ' , [ 44 , 55 , 66 ] )
[ ( 0 , ' a ' , 44 ) , ( 1, -b ’ , 55 ) , ( 2 , *c ', 66 ) ]

max ( iterable [ , key ] )
Return the largest item in an iterable. The optional argument key specifies a function of one argument that is used to extract a comparison key from each list element. The default value is None (compare the elements directly),

>>> max ( ' hello ' )
' o '
>>> max ( [10, 80, 90, 20,-100] )
90
>>> def LessThanFifty ( x ) :
. . .         if x<=50 :
. . .          return x
>>> max ( [ 10 , 80 , 90 , 20 , -100 ] , key=LessThanFifty )
20

The function has another form max (arg1, arg2, *args [, key] ), which returns the largest of two or more arguments.

>>> max ( ' hi ' ,  ' hello ' ,  ' bye ' )
' hi '
>>> max ( ' Gumby ' , ' Lambert ' , ' Sartre ' , ' Cheddar ' )
' Cheddar '
>>> max ( ' Gumby ' , ' Lambert ' , ' Sartre ' , ' Cheddar ' , key=str.upper )
' Sartre '

min ( iterable [ , key ] )
Return the smallest item in an iterable. The key has same meaning as that in max ( ) function.

>>> min ( ' hello' )
' e '
>>> min ( ( 10 , 80 , 90 , 20 , -100 } )
-100

The function has another form min (arg1, arg2, *args [ , key] ), which returns the smallest of two or more arguments.

>>> min ( 10 , 80 , 90 , 20 , -100 )
-100
>>> def rev ( x ) : return -x
. . .
>>> min ( 10 , 80 , 90 , 20 , -100 , key=rev )
90

next ( iterator [ , defauIt ] )
Retrieve the next item from the iterator. If the default is given, it is returned if the iterator is exhausted, otherwise, Stoplteration is raised.

>>> it=iter ( xrange ( 0 , 3 ) )
>>> next ( it , ' Done ' )
0
>>> next ( it , ' Done ' )
1
>>> next ( it ,  'Done ' )
2
>>> next ( it , ' Done ' )
' Done '
>>> next ( it , ' Done ' )
' Done '
>>> it=iter ( xrange ( 0 , 3 ) )
>>> next ( it )
0
>>> next ( it )
1
>>> next ( it )
2
>>> next ( it )
Traceback ( most recent call last ) :
File "<stdin>", line 1, in <module>
Stoplteration

oct ( x )
Convert an integer number (of any size) to an octal string.

>>> oct ( 135 )
' 0207 '

pow ( x , y [ , z ] )
Return x to the power y; if z is present, return x to the power y, and modulo z (computed more efficiently than pow (x, y) %z). The two-argument form pow (x, y) is equivalent to using the power operator x* *y. The arguments must be of numeric types. If the second argument is negative, the third argument must be omitted. If z is present, x and y must be of integer types, and y must be non-negative.

>>> 2 * * 4
16
>>> pow ( 2 , 4 )
16
>>> ( 2 * * 4 ) % 3
1
>>> pow ( 2 , 4 ,3 )
1

print ( * objects , sep=’ ‘ , end=’ \ n ‘ , file=sys . stdout )
Print objects to the stream file, separated by sep and followed by end. If sep, end and file, are present, they must be given as keyword arguments. All non-keyword arguments are converted to strings and written to the stream, separated by sep and followed by end. Both sep and end must be strings, they can also be None, which means to use the default values. If no objects are given, print ( ) will just write end. The file argument must be an object with a write ( ) method, if it is not present or None, sys. stdout (file objects corresponding to the interpreter’s standard output stream) will be used.

This function is not normally available as a built-in function, since the name print is recognized as the print statement. To disable the statement and use the print ( ) function, use the following future statement before using the function.

>>> from _____future______ import print_function
>>> x , y=3 , 5
>>> print ( ' The sum of ' , x , ' plus ' , y , ' is ' , x+y )
The sum of 3 plus 5 is 8
>>> print ( ' The sum of ' , x , ' plus ' , y , ' is ' , x+y , sep =' ' )
The sum of 3 plus 5 is 8
>>> print ( ' The sum of ' , x , ' plus ' , y , ' is ' , x+y , sep='  ' , end=' \ n The \ n End \ n ' )
The sum of 3 plus 5 is 8
The
End

range( start,stop[,step] )
This function creates list whose elements are in arithmetic progression. The arguments must be plain integers. If the step argument is omitted, it defaults to 1. If the start argument is omitted, it defaults to 0. step must not be zero (or else ValueError is raised).

>>> 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 )
[ 0 , -1 , -2 , -3 , -4 , -5 , -6 , -7 , -8 , -9 , ]
>>> range ( 0 )
[ ]
>>> range ( 10 , 5 )
[ ]
>>> range ( 10 , 5 , -1 )
[ 10 , 9 , 8 , 7 , 6 ]

Reload a previously imported module. The argument must be a module object, so it must have been successfully imported before. This is useful if the programmer has edited the module’s source file using an external editor and wants to try out the new version without leaving the Python interpreter. The return value is the module object.

reversed ( seq )
The function returns an iterator object that can iterate over all the objects in the container in reverse order.

>>> Seq= [ 10, 20, 30 ]
>>> revSeq=reversed ( Seq )
>>> for item in revSeq: print item
. . .
30
20
10

round ( number [ , ndigits ] )
Return the floating-point value number rounded to digits after the decimal point. If digits are omitted, it defaults to zero.

>>> round ( 2 .769753 )
3 . 0
>>> round ( -2 . 769753 )
-3 . 0
>>> round ( 2 . 769753 , 4 )
2 . 7698
>>> round ( -2 . 769753 , 4 )
-2 . 7698

setattr ( object, name, value )
This is the counterpart of getattr ( ). The arguments are an object, a string, and an arbitrary value. The string may name an existing attribute or a new attribute. The function assigns the value to the attribute, provided the object allows it. The following example will become clearer after going through chapter 6.

>>> class new_cls:
. . .             def init ( self , x ) :
. . .           self . x=x
>>> tt=new_cls ( 10 )
>>> tt.x
10
>>> setattr ( tt , ' x ' , 20 )
>>> tt.x
20
>>> setattr ( tt , ' yhello ' )
>>> tt.y
' hello '

slice ( start , stop [ , step ] )
Return a slice object representing the set of indices specified by range (start, stop, step). The function can also be of form slice (stop), where the start and step arguments default to None. Slice objects have read-only data attributes start, stop, and step, which merely returns the argument values (or their default).

>>> slice ( 20 )
slice ( None , 20 , None )
>>> s1=slice ( 2 , 20 , 3 )
>>> type ( s1 )
<type ' slice ' >
>>> s1 . start
2
>>> s1 . stop
20
>>> s1 . step
3

The slice object can be passed to the ________getitem__________ ( ) method of the built-in sequences.

>>> range ( 50 ). getitem ( s1 )
[ 2 , 5 , 8 , 11 , 14 , 17 ]

Or use slice objects directly in subscripts:

>>> range ( 50 ) [ s1 ]
[ 2 , 5 , 8 , 11 , 14 , 17 ]

sorted ( iterable [ , cmp [ , key [ , reverse] ] ] )
Return a new sorted list from the items in iterable. The arguments cmp, key, and reverse are optional.

>>> a= [ 66 . 25 , 333 , ' abc ' , 333 , 1 , ’ ab ' , 1234 . 5 ]
>>> sorted ( a )
[ 1 , 66 . 25 , 333 , 333 , 1234 . 5 , ' ab ' , ' abc ' ]
>>> sorted ( { 10 : ' D ' , 5 : ' B ' , 8 : ' B ' , 6 : ' E ' , 2 : ' A ' } )
[ 2 , 5 , 6 , 8 , 10 ]

cmp specifies a custom comparison function of two arguments (iterable elements) which should return a negative, zero or positive number depending on whether the first argument is considered smaller than, equal to, or larger than the second argument. The default value is None.

key specifies a function of one argument that is used to extract a comparison key from each list element. The default value is None (compare the elements directly).

>>> strs= [ ' ccc ' , ' aaaa ' , ' d ' , ' bb ' ]
>>> sorted ( strs , key=len)                               # Sorted by string length
[ ' d ' , ' bb ' , ' ccc ' , 'aaaa ' ]
>>> student_tuples=[
. . . ( ' john ' , ' A ' , 15 ) ,
. . . ( ' jane ' , ' B ' , 12 ) ,
. . . ( ' dave ' , ' B ' , 10 ) , ]
>>> sorted ( student_tuples , key=lambda student : student [ 2 ] )                        # By age
[ ( ' dave ' , ' B ' , 10 ) , ( ' jane ' , ' B ' , 12 ) , ( ' john ' , ' A ' , 15 ) ]

the reverse is a boolean value. If set to True, then the list elements are sorted as if each comparison were reversed.

>>> a= [ 66 . 25 , 333 , ' abc ' , 333 , 1 , ' ab ' , 1234 . 5 ]
>>> sorted ( a , reverse = True )
[ ' abc ' , ' ab ' , 1234 . 5 , 333 , 333 , 66 . 25 , 1 ]

In general, the key and reverse conversion processes are much faster than specifying an equivalent cmp function. This is because cmp is called multiple times for each list element, while key and reverse touch each element only once.

>>> L= [ ' geas ' , ' clue ' , ' Zoe ' , ' Ann ' ]
>>> sorted ( L )
[ ' Ann ' , ' Zoe ' , ' clue ' , ' geas ' ]
>>> def ignoreCase(x,y) :
. . . return cmp ( x . upper ( ) , y . upper ( ) )
. . .
>>> sorted ( L , ignoreCase )
[ ' Ann ' , ' clue ' , ' geas ' , ' Zoe ' ]
>>> sorted ( L , None , str . upper )
[ ' Ann ' , ’ clue ' , ' geas ' , ’ Zoe ' ]
>>> L
[ ' geas ' , ' clue ' , ' Zoe ' , ' Ann ' ]



sum ( iterable [ , start ] )
The function returns the sum total of start ( defaults to 0 ) and the items of an iterable.

>>> seq= [ 5 , 7 . 4 , 2 , 11 ]
>>> sum ( seq )
25 . 4
>>> sum ( seq , 10 . 2 )
35 . 6
>>> aa=4
>>> bb=2 . 5
>>> cc=9 . 1
>>> seq= [ aa , bb , cc ]
>>> sum ( seq )
15 . 6

type ( object )
The function returns the type of an object.

>>> i=50 . 7
>>> type ( i )
<type ' float '>
>>> type ( i ) is float
True

xrange ( start , stop [ , step ] )
This function is very similar to range ( ), but returns an xrange object instead of a list. This yields the same values as the corresponding list, without actually storing them all simultaneously. The advantage of xrange ( ) over range ( ) is minimal, except when a very large range is used on a memory-starved machine or when all of the range ( ) elements are never used (such as when the loop is usually terminated with break). The function can also be used as xrange (stop).

The xrange type is an immutable sequence that is commonly used for looping. The advantage of the xrange type is that an xrange object will always take the same amount of memory, no matter the size of the range it represents. There are no consistent performance advantages. The xrange objects support indexing, iteration, and the len ( ) function.

>>> for i in xrange ( 2000000000 ) :
. . . print i
. . . if i > 5 :
. . . break
. . .
0
1
2
3
4
5
6
>>> for i in range ( 2000000000 ) :
. . . print i
. . . if i>5 :
. . . break
. . .
Traceback ( most recent call last ) :
File "<stdin>", line 1, in <module>
MemoryError

zip ( [ iterable , . . . ] )
This function returns a list of tuples, where the /th tuple contains the /th element from each of the argument sequences or iterables. The returned list is truncated in length to the length of the shortest argument sequence. When there are multiple arguments that are all of the same lengths, zip ( ) is similar to map ( ) with an initial argument of None. With no arguments, it returns an empty list, zip ( ) in conjunction with the * operator can be used to unzip a list:

>>> x= [ 1 , 2 , 3 ]
>>> y=[ 4 , 5 , 6 , 7 , 8 ]
>>> zipped=zip ( x , y )
>>> zipped
[ ( 1 , -4 ) , ( 2 , 5 ) , ( 3 , 6 ) ]
>>> zip ( x )
[ ( 1 , ) , ( 2 , ) , ( 3 , ) ]
>>> x2 , y2=zip ( *zipped )
>>> x2
( 1 , 2 , 3 )
>>> y2
( 4 , 5 , 6 )
>>> zip ( )
[ ]