Author name: Prasanna

Python Programming – Customizing Attribute Access

In this Page, We are Providing Python Programming – Customizing Attribute Access. Students can visit for more Detail and Explanation of Python Handwritten Notes Pdf.

Python Programming – Customizing Attribute Access

Customizing attribute access

The following are some methods that can be defined to customize the meaning of attribute access for class instance.

object.___getattr____ ( self , name )
Called when an attribute lookup does not find the attribute name. This method should return the (computed) attribute value or raise an AttributeError exception. Note that, if the attribute is found through the normal mechanism, ___getattr___ ( ) is not called.

>>> class HiddenMembers:
. . .        def ___getattr___ ( self , name ) :
. . .               return "You don't get to see "+name
. . . 
>>> h=HiddenMembers ( )
>>> h . anything
" You don't get to see anything "

object . setattr ( self , name , value )
Called when an attribute assignment is attempted. The name is the attribute name and value is the value to be assigned to if. Each class, of course, comes with a default ___setattr___ , which simply set the value of the variable, but that can be overridden.

>>> class Unchangable: 
. . .         def ___setattr____ ( self , name , value ) :
. . .                print " Nice try "
. . . 
>>> u=Unchangable ( )
>>> u . x=9 
Nice try 
>>> u . x
Traceback ( most recent call last ) :
    File "<stdin>", line 1, in ?
AttributeError: Unchangable instance has no attribute 'x' ;

object.___delattr___ ( self , name )
Like ____setattr___ ( ), but for attribute deletion instead of assignment. This should only be implemented if del ob j . name is meaningful for the object.

>>> Class Permanent :
. . . def ___delattr____ ( self , name ) :
. . . print name , " cannot be deleted "
. . .
>>> p=Permanent ( )
>>> p . x=9 
>>> del p . x 
x cannot be deleted 
>>> p . x
9

Python Programming – Customizing Attribute Access Read More »

Python Programming – Pre-Defined Attributes

In this Page, We are Providing Python Programming – Pre-Defined Attributes. Students can visit for more Detail and Explanation of Python Handwritten Notes Pdf.

Python Programming – Pre-Defined Attributes

Pre-defined attributes

Class and class instance objects has some pre-defined attributes:

Class object

Some pre-defined attributes of class object are:

__name__
This attribute give the class name.

>>> MYClass . __name__
' MYClass '

__module__
This attribute give the module name.in which the class was defined.

>>> MYClass . ___module___
' ___main___ '

___dict___
A class has a namespace implemented by a dictionary object. Class attribute references are translated to lookups in this dictionary, e.g., MyClass . i is translated to MyClass .___dict___ [ ” i ” ].

>>> MyClass.___dict___
{ ' i ' : 12345 , '___module___' : '___main___ ' , '___doc___ ': ' A simple example class ' , ' f ' : <function f at 0x0640A070>}

___bases___
This attribute give the tuple (possibly empty or a singleton) containing the base classes.

>>> MyClass.___bases___.
( )

___doc___
This attribute give the class documentation string, or None, if not defined.

>>> MyClass.___doc___ 
' A simple example class '

Class instance object
Some pre-defined attributes of class instance object are:

___dict___
This give attribute dictionary of class instance.

>>> x. ___dict___ 
{ }

___class___
This give the instance’s class.

>>> x. ___class____ 
<class ___main___ .MyClass at 0x063DA880>

Python Programming – Pre-Defined Attributes Read More »

Python Programming – Instance Object

In this Page, We are Providing Python Programming – Instance Object. Students can visit for more Detail and Explanation of Python Handwritten Notes Pdf.

Python Programming – Instance Object

Instance object

The only operation that done using class instance object x is attribute references. There are two kinds of valid attribute names: “data attribute” and “method”.

Data attribute corresponds to a variable of a class instance. Data attributes need not be declared; like local variables, they, spring into existence when they are first assigned to. For example, if x is the instance of MyClass (created, before), the following piece of code will print the value 16, without leaving a trace:

>>> x . counter=1
>>> while x . counter<10:
. . . x . counter=x. counter*2
. . .
>>> print x . counter 
16 
>>> del x . counter

The other kind of instance attribute reference is a method. Any function object that is a class attribute defines a method for instances of that class. So, x. f is a valid method reference, since MyClass. f is a function.

Python Programming – Instance Object Read More »

Python Programming – Class Object

In this Page, We are Providing Python Programming – Class Object. Students can visit for more Detail and Explanation of Python Handwritten Notes Pdf.

Python Programming – Class Object

Class object

When a class definition is created, a “class object” is also created. The class object is basically a wrapper around the contents of the namespace created by the class definition. Class object support two kinds of operations: “attribute reference” and “instantiation”.

Attribute reference

Attribute references use the standard syntax used for all attribute references in Python: obj .name. Valid attribute names are all the names that were in the class’s namespace, when the class object was created. So, if the class definition looked like this:

>>> class MyClass: 
. . .            " " "A simple example class " " " 
. . .           i=12345
. . .           def f ( self ) : 
. . .                 return ' hello world ' :
. . . 
>>> MyClass . i 
12345
>>> MyClass.___doc___
' A simple example class '

then MyClass . i and MyClass . f are valid attribute references, returning an integer and a method object, respectively. The value of MyClass.i can also be change by assignment. The attribute ___doc___is also a valid attribute, returning the docstring belonging to the class.

>>> type ( MyClass )
<type ' classobj ' >

From the above expression, it can be noticed that MyClass is a class object.

Instantiation

A class object can be called to yield a class instance. Class instantiation uses function notation. For example (assuming the above class MyClass):

x=MyCiass ( )

creates a new instance of the class MyClass, and assigns this object to the local variable x.

>>> type ( MyClass( ) )
<bype ' instance' > 
>>> type (x) 
<type 'instance'>

Many classes like to create objects with instances customized to a specific initial state. Therefore, a class may define a special method named ___init___( ), like this:

def __init__ ( self ) :
self.data=[ ]

When a class defines an __init__ ( ) method, class instantiation automatically invokes __init__( ) for the newly created class instance. So in this example, a new, initialized instance can be obtained by:

x=MyClass ( )

Of course, the ___init___ ( ) method may have arguments for greater flexibility. In that case, arguments given to the class instantiation operator are passed on to ___init___ ( ). For example,

>>> class Complex:
. . .          def __init___ ( self , realpart , imagpart ) :
. . .              self . r=realpart
. . .              self . i=imagpart
>>> x=Complex ( 3 . 0, -4 . 5 )
>>> x . r , x . i
( 3 . 0 , -4 . 5 )

Python Programming – Class Object Read More »

Python Programming – Method

In this Page, We are Providing Python Programming – Method. Students can visit for more Detail and Explanation of Python Handwritten Notes Pdf.

Python Programming – Method

Method

A method is a function that belongs to an object. In Python, the term “method” is not unique to class instance, other object types can have methods as well. For example, list objects have methods, namely, append, insert, remove, sort, and so on.

Usually in a class, the method is defined inside its body. If called as an attribute of an instance of that class, the method will get the instance object as its first argument (which is usually called self). Self is merely a conventional name for the first argument of a method. For example, a method defined as meth (self, a, b, c) should be called as x.meth (a, b, c) for an instance x of the class in which the definition occurs; the called method will think it is called as meth (x, a, b, c). The idea of self was borrowed from “Modula-3” programming language.

It is not necessary that the function definition is textually enclosed in the class definition; assigning a function object to a local variable in the class is also fine. For example:

>>> def f 1 ( self , x , y ) :
. . .            return min ( x , x+y )
. . . 
>>> class test_class :
. . .        aa=f1
. . .        def bb ( self ) : 
. . .              return ' hello world '
. . .       cc=bb
. . . 
>>>

Here aa, bb and cc are all attributes of class test_class that refer to function objects, and consequently, they are all methods of instances of class test_class; cc being exactly equivalent to bb. Note that this practice usually confuses the reader of the program.

Usually, Python use methods for some functionality (e.g. list. index ()), but functions for other (e.g. len (list)). The major reason is history; functions were used for those operations that were generic for a group of types and which were intended to work even for objects that did not have methods at all (e.g. tuples). In fact, implementing len ( ), max ( ), min ( ) etc.

as built-in functions has actually less code than implementing them as methods for each type. One can quibble about individual cases, but it is part of Python, and it is too late to make such fundamental changes now. The functions have to remain to avoid massive code breakage.

Python Programming – Method Read More »

Python Programming – Class

In this Page, We are Providing Python Programming – Class. Students can visit for more Detail and Explanation of Python Handwritten Notes Pdf.

Python Programming – Class

Class

A class is the particular object type created by executing a class statement. Class objects are used as templates to create instance objects, which embodies the attributes: the “data attributes” and “methods”, specific to a data type. A class definition is given below:

classdef        : := " class " classname [ inheritance ] " : " suite
inheritance   : := " ( " [ expression_list ] " ) " 
classname    : := identifier

The above class definition might seem alien, it will become more clear with the progress of this Chapter. The simplest form of class definition looks like:

class ClassName: 
        <statement-1>
         .
 
        .

       .
      <statement-N>

The following example gives a glimpse of how a class is defined.

>>> class Output :
. . .      def Display ( self ) :
. . .            print ' This is a class example . '
. . . 
>>> x=Output ( ) 
>>> x . Display ( )
This is a class example.

Like function definition (def statements), the class definition (Output in the above example) must be executed before they have any effect. In practice, the statements inside a class definition will usually be function (or more specifically “method”) definitions (Display ( ) in the above example), but other statements are allowed. The function definitions inside a class normally have a peculiar form of the argument list, dictated by the calling conventions for methods (discussed later).

The creation of a class definition also creates a new namespace, and used as the local scope, thus all assignments to local variables go into this new namespace.

Python Programming – Class Read More »

Python Programming – Constants

In this Page, We are Providing Python Programming – Constants. Students can visit for more Detail and Explanation of Python Handwritten Notes Pdf.

Python Programming – Constants

Constants

math.pi
The mathematical constant π.

math. e
The mathematical constant e.

>>> math.e
2.718281828459045

Number-theoretic and representation functions

math . ceil ( x )
Return the ceiling of x as a float, the smallest integer value greater than or equal to x.

>>> import math 
>>> math . ceil ( -3 . 2 )
-3 . 0
>>> math . ceil ( 3 . 2 )
4 . 0

math . copysign ( x , y )
Return x with the sign of y.

>>> math . copysign ( 5 . 1 , -2 . 8 )
-5 . 1
>>> math . copysign ( -5 . 1 , 2 . 8 )
5 . 1

math . tabs ( x )
Return the absolute value of x.

>>> math . fabs ( - 4 . 2 )
4 . 2

math . factorial ( x )
Return x factorial. Raises ValueError, if x is not integral or is negative.

>>> math . factorial ( 5 ) 
120 
>>> math . factorial ( -5 ) 
Traceback ( most recent call last ) :
File "<stdin>", line 1, in <module>
ValueError: factorial ( ) not defined for negative values

math . floor ( x )
Return the largest integer value less than or equal to x as a float.

>>> math . floor ( -3 . 2 )
-4 . 0
>>> math . floor ( 3 . 2 )
3 . 0

math . fmod ( x , y )
Return remainder of a division expression. Note that the Python expression x%y may not return the same result. The result of fmod (x, y) has same sign as x, while x%y returns a result with the sign of y instead.

>>> math . fmod ( 5 . 0 , -2 . 0 )
1 . 0
>>> 5 . 0% -2 . 0 
-1 . 0
>>> math . fmod ( -5 . 0 , 2 . 0 )
-1 . 0
>>> -5 . 0 % 2 . 0
1 . 0

Consider the following interesting scenario.

>>> math . fmod ( -1e-100 , 1e100)
-1e-100 
>>> -1e-100 % 1e100
1e +100

It can be observed that fmod (-1e-100 , 1e100) returns -1e-100, but the result of Python’s – 1e-100%1e100 is 1e100-1e-100, which cannot be represented exactly as a float, and rounds to the surprising 1e100. For this reason, function fmod ( ) is generally preferred when working with floats, while Python’s x % y is preferred when working with integers.

math . frexp ( x )
Return the mantissa and exponent of x as the pair (m, e). The m is a float and e is an integer such that x = m x 2e exactly. If x is zero, returns ( 0 . 0 , 0 ) , otherwise 0 . 5<=abs ( m ) <1.

>>> math . frexp ( 4 . 0 )
( 0 . 5 , 3 )
>>> 0 . 5*2**3
4 . 0
>>> math . frexp ( 0 . 1 )
( 0 . 8 , -3 )
>>> 0 . 8* 2**-3
0 . 1
>>> math . frexp ( -4 . 0 )
( -0 . 5 , 3 )
>>> -0 . 5*2**3
- 4 . 0

math.fsum(iterable)
Return an accurate floating point sum of values in the iterable.

>>> math . fsum ( [ . 1 , . 1 , . 1 , . 1 , . 1 , . 1 , . 1 , . 1 , . 1 , . 1 ] )
1 . 0

math . isinf ( x )
Check if the float x is positive or negative infinity.

>>> a=1e+300
>>> a
1e+300
>>> math . isinf ( 1e+300 )
False
>>> a=1e+310
>>> a
inf
>>> math . isinf ( 1e+310 )
True

Calculating an exponent with floating point values, in particular, raises Overf lowError instead of preserving the inf result.

>>> a=10 . 0**310

Traceback ( most recent call last ) :
File "<pyshell#l>", line 1, in <module>
    a=10 . 0**310
OverflowError: (34 , ' Result too large ' )

math . isnan ( x )
Check if the float x is a nan (not a number), nan does not compare as equal to any value, even itself, so nan should be checked using isnan () function.

>>> a=1e+310
>>> a
inf
>>> b=a/a
>>> b
nan
>>> math . isnan ( a )
False
>>> math . isnan ( b )
True

math . ldexp ( x , i )
Return x* (2**i). This function is reverse of function frexp ( ).

>>> math . 1dexp ( -0 . 5 , 3 )
-4 . 0
>>> -0 . 5*2**3
-4 . 0
>>> math . ldexp ( 0 . 8 , -3 )
0 . 1
>>> 0 . 8*2**-3
0 . 1

math . modf ( x )
Return the fractional and integer parts of x. Both results carry the sign of x and are floats.

>>> math . modf ( 1 . 5 )
( 0 . 5 , 1 . 0 )

>>> math . modf ( -1 . 5 )
( -0 . 5 , -1 . 0 )

math . trunc ( x )
Return the real value x truncated to an integer.

>>> math . trunc ( 93 . 2508 )
93
>>> math . trunc ( -93 . 2508 )
-93

Power and logarithmic functions

math . exp ( x )
Return ex.

>>> math . e**-3 . 2
0 . 04076220397836622
>>> math . pow ( math . e , -3 . 2 )
0 . 04076220397836622
>>> math . exp ( -3 . 2 )
0 . 04076220397836621

math . expm1 ( x )
Return ex-1. For small floats x, the subtraction in exp(x)-1 can result in a significant loss of precision; the expml ( ) function provides a way to compute this quantity to full precision:

>>> x=0 . 0000000000000000000000001
>>> math . exp ( x ) , -1
0 . 0
>>> math . expm1 ( x )
1e - 25

math . log ( x [ , base ] )
With one argument, return the natural logarithm of x (to base e). With two arguments, return the logarithm of x to the given base, calculated as log (x) / log (base).

>>> math . log ( 9 )
2 . 1972245773362196
>>> math . log ( 9 , 2 )
3 . 1699250014423126

math . loglp ( x )
Return the natural logarithm of 1+x (base e). The result is calculated in a way which is accurate for x near zero.

>>>x=0.0000000000000000000000001
>>> X
1e-25
>>> 1+x
1 . 0
>>> math . 1og ( 1 +x )
0 . 0
>>> math . 1og1p ( x )
1e-25

math . 1og10 ( x )
Return the base-10 logarithm of x. This is usually more accurate than log (x, 10).

>>> math . 1og10 ( 100 )
2 . 0
>>> math . 1og10 ( 10000 )
4 . 0

math . pow ( x , y )
Return x raised to the power y. In particular, pow ( 1 . 0 , x ) and pow ( x , 0 . 0 ) always return 1.0, even when x is a zero or a NaN. If both x and y are finite, x is negative, and y is not an integer then pow (x, y) is undefined, and raises ValueError.

>>> math.pow ( 9 . 0 , 0 . 5 )
3 . 0
>>> math . pow ( -9 . 0 , 0 . 5 )
Traceback ( most recent call last ) :
File "<stdin>" , line 1 , in <module>
ValueError: math domain error

Unlike the built-in * * operator, math. pow ( ) converts both its arguments to type float.

math . sqrt( x )
Return the square root of x. Computing the square roots of negative numbers requires complex numbers, which are not handled by math module. Any attempt to calculate a square root of a negative value results in ValueError.

>>> math . sqrt ( 9 . 0 )
3 . 0
>>> math . sqrt ( -9 , 0 )

Traceback (most recent call last):
File "<pyshell#62>", line 1, in <module>
math . sqrt ( -9 . 0 )
ValueError: math domain error

Trigonometric functions

math . acos ( x )
Return the arc cosine of x, in radians.

>>> math . acos ( 0 . 5 )
1 . 0471975511965979

math . asin ( x )
Return the arc sine of x, in radians.

>>> math . asin ( 0 . 5 )
0 . 5235987755982989

math . atan ( x )
Return the arc tangent of x, in radians.

>>> math . atan ( 0 . 5 )
0 . 4636476090008061

math . atan2 ( y , x )
Return atan(y/x), in radians. The resuit is between -TI and TI. The vector in the plane from the origin to point (x, y) makes this angle with the positive X axis. The point of atan2 () is that the signs of both inputs are known to it, so it can compute the correct quadrant for the angle. For example, atan (1) and atan2 (1,1) are both n /4, but atan2 (-1,-1) is -3#/4.

>>> math . atan ( 1 . 0 )
0 . 7853981633974483
>>> math . pi / 4
0 . 7853981633974483

math . cos ( x )
Return the cosine of x radians.

>>> math . cos ( 0 . 7853981633974483 )
0 . 7071067811865476

math . hypot ( x , y )
Return the Euclidean distance, \(\sqrt{x^{2}+y^{2}}\) . This is the length of the vector from the origin to point (x,y).

>>> math . hypot ( 3 . 0 , 4 . 0 )
5 . 0

math . sin ( x )
Return the sine of x radians.

>>> math . sin ( 0 . 7853981633974483 )
0 . 7071067811865475

math . tan ( x )
Return the tangent of x radians.

>>> math.tan ( 0 . 7853981633974483 )
0.9999999999999999

Angular conversion

math . degrees ( x )
Converts angle x from radians to degrees.

>>> math . degrees ( 1 . 5707963267948966 )
90 . 0
>>> 1 . 5707963267948966*180 / math . pi
90 . 0

math . radians ( x )
Converts angle x from degrees to radians.

>>> math . radians ( 90 )
1 . 5707963267948966
>>> ( 90*math . pi ) / 180
1 . 5707963267948966

Hyperbolic functions

math . acosh ( x )
Return the inverse hyperbolic cosine of x.

>>> math . cosh ( 1 . 0 )
1 . 5430806348152437

math . asinh ( x )
Return the inverse hyperbolic sine of x.

>>> math . asinh ( 1 . 0 )
0 . 8813735870195429

math . atanh ( x )
Return the inverse hyperbolic tangent of x.

>>> math . atanh ( 0 . 8 )
1 . 0986122886681098

math . cosh ( x )
Return the hyperbolic cosine of x.

>>> math . cosh ( 0 . 7853981633974483 )
1 . 3246090892520057

math . sinh ( x )
Return the hyperbolic sine of x.

>>> math . sinh ( 0 . 7853981633974483)
0 . 8686709614860095

math . tanh ( x )
Return the hyperbolic tangent of x.

>>> math . tanh ( 0 . 7853981633974483 )
0 . 6557942026326724

Special functions

math . erf ( x )
Return the error function at x.

>>> math . erf ( 0 . 25 )
0 . 2763263901682369

math . erfc ( x )
Return the complementary error function at x i.e. 1-erf (x).

>>> math . erf c ( 0 . 25 )
0 . 7236736098317631

math . gamma ( x )
Return the gamma function at x.

>>> math . gamma ( 5 . 5 )
52 . 34277778455352

math . lgamma ( x )
Return the natural logarithm of the absolute value of the gamma function at x.

>>> math . 1 gamma ( 5 . 5 )
3 . 9578139676187165

Python Programming – Constants Read More »

Python Programming – Looping Techniques

In this Page, We are Providing Python Programming – Looping Techniques. Students can visit for more Detail and Explanation of Python Handwritten Notes Pdf.

Python Programming – Looping Techniques

Looping techniques

The list can also be used in iteration operation, for example:

>>> for a in [ 4 , 6 , 9 , 2 ] : print a
4
6
9
2
>>> for a in [ 4 , 6 , 9 , 2 ] : print a ,
. . .
4 6 9 2

When looping through a sequence, the position index and corresponding value can be retrieved at the same time using the enumerate ( ) function.

>>> for i ,v in enumerate ( [ ' tic ' , ' tac ' , ' toe ' ] ) :
. . . print i, v
0 tic
1 tac
2 toe

To loop over two or more sequences at the same time, the entries can be paired with the zip () function.

>>> questions= [ ' namer , ' quest ' , ' favorite color ' ]
>>> answers= [ ' lancelot ' , ' the holy grailblue ' ] 
>>> for q,a in zip ( questions , answers ) :
. . .   print 'What is your { 0 } ? It is { 1 }.'. format ( q , a) 
What is your name ? It is lancelot.
What is your quest? It is the holy grail.
What is your favorite color? It is blue.

While iterating a mutable sequence, if there is a need to change the sequence (for example to duplicate certain items), it is recommended to make a copy of the sequence before starting iteration. Looping over a sequence does not implicitly make a copy. The slice notation makes this especially convenient.

>>> words= [ ' cat ' , ' window ' , ' defenestrate ' ]
>>> for w in words [ : ] :
. . . if len ( w )>6:
. . . words. insert ( 0 , w )
>>> words
[ ' defenestrate ' , ' cat ' , ' window ' , ' defenestrate ' ]

Nested list

It is possible to nest lists (create list containing other lists), for example:

>>> q= [ 2 , 3 ]
>>> p= [ 1 , q , 4 ]
>>> len ( p )
3
>>> p [ 1 ]
[ 2 , 3 ]
>>> p [ 1 ] [ 0 ]
2
>>> p [ 1 ] . append ( ' xtra ' )
>>> p
[ 1 , [ 2 , 3 , ' xtra ' ] , 4 ]
>>> q
[ 2 , 3 , ' xtra ' ]

Note that in the last example, p [ 1 ] and q refer to the same object, which can be cross-checked using the id ( ) built-in function.

>>> id ( q )
104386192
>>> id (p [1] )
104386192

Python Programming – Looping Techniques Read More »

Python Programming – Deleting List Elements

In this Page, We are Providing Python Programming – Deleting List Elements. Students can visit for more Detail and Explanation of Python Handwritten Notes Pdf.

Python Programming – Deleting List Elements

Deleting list elements

To remove a list element, one can use either the del statement (if you know the element index to delete) or remove () method (if you do not know the element index, but the element itself, discussed in section 4.1.9). The following example depicts the deletion of an element using the del statement.

>>> a= [ ' spam ' , ' eggs ' , 100 , 1234 ]
>>> del a [ 1 ]
>>> a
[ ' spam ' , 100 , 1234 ]

The del statement can also be used to explicitly remove the entire list.

>>> a= [ ' spam ' , ' eggs ' , 100 , 1234 ]
>>> del a 
>>> a
Traceback ( most recent call last ) :
File " <stdin> " , line 1 , in <module>
NameError: name ' a ' is not defined

The following is an interesting case of the del statement:

>>> a= [ ' spam ' , ' eggs ' , 100 , 1234 ]
>>> del a [ 1 ] , a [ 1 ]
>>> a
[ ' spam ' , 1234 ]

It should be noted that the same index is deleted twice. As soon as an element is deleted, the indices of succeeding elements are changed. So deleting an index element n times, would actually delete n elements.

It is also possible to delete multiple items from a list.

>>> a= [ ' spam ' , ' eggs ' , 100 , 1234 ]
>>> a [ 1 : 3 ] = [ ]
>>> a
[ ' spam ' , 1234 ]

Swapping lists

There might be a scenario in which multiple lists need to be swapped among themselves. This is can done easily using multiple assignments expression.

>>> a= [ 10 , 20 , 30 ] 
>>> b= [ 40 , 50 , 60 ] 
>>> c= [ 70 , 80 , 90 ]
>>> a , b , c=c , a , b 
>>> a
[ 70 , 80 , 90 ] 
>>> b
[ 10 , 20 , 30 ]
>>> c
[ 40 , 50 , 60 ]

Python Programming – Deleting List Elements Read More »

Python Programming – Updating List Elements

In this Page, We are Providing Python Programming – Updating List Elements. Students can visit for more Detail and Explanation of Python Handwritten Notes Pdf.

Python Programming – Updating List Elements

Updating list elements

It is possible to change individual or multiple elements of a list:

>>> a= [ ' spam ' , ' eggs ' , 100 , 1234 ]
>>> a [ 0 ]= ' filter '
>>> a
[ ' filter ' , ' eggs ' , 100 , 1234 ]
>>> a [ 2 : 4 ]= 455 , 56858 
>>> a
[ ' filter ' , ' eggs ' , 455 , 56858 ]

The items of list can be updated by the elements of another iterable (list, tuple).

>>> a= [ 66 . 25 , 333 , 333 , 1 , 1234 . 5 ]
>>> b=[ ' hi ' , ' bye ' ]
>>> a [ 2 : 4 ] =b 
>>> a
[ 66 . 25 , 333 , ' hi ' , ' bye ' , 1234 . 5 ]
>>> a= [ 66 . 25 , 333 , 333 , 1 , 1234 . 5 ]
>>> b= ( ' hi ' , ' bye ' )
>>> a [ 2 : 4 ]=b 
>>> a
[ 66 . 25 , 333 , ' hi ' , ' bye ' , 1234 . 5 ]
>>> a= [ 66 . 25 , 333 , 333 , 1 , 1234 . 5 ]
>>> b= [ ' hi ' , ' bye ' ] 
>>> a [ 1: 4 : 2 ] =b 
>>> a
[ 66 . 25 , ' hi ' , 333 , ' bye ' , 1234 . 5 ]

It is also possible to insert elements in a list.

>>> a=[ ' spam ' , ' eggs ' , 100 , 1234 ]
>>> a [ 1 : 1 ]=[ ' chair ' ]
>>> a
[ ' spam ' , ' chair ' , ' eggs ' , 100 , 1234 ]
>>> a [ 1 : 1 ] = [ ' hello ', ' bye ' ]
>>> a
[ ' spam ' , ' hello ' , ' bye ' , ' chair ' , ' eggs ' , 100 , 1234 ]

To insert a copy of the list at the beginning of itself:

>>> a= [ ' spam ' , ' eggs ' , 100 , 1234 ]
>>> a [ : 0 ]=a 
>>> a
[ ' spam ' , ' eggs ' , 100 , 1234 , ' spam ' , ' eggs ' , 100 , 1234 ]

There are various methods of list objects for updating the list, which is discussed in section 4.1.9.

Python Programming – Updating List Elements Read More »