Python Programming – Dictionary

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

Python Programming – Dictionary

Dictionary

Another useful mutable built-in type is “dictionary”. A dictionary is an unordered group of comma-separated “key: value” pairs enclosed within braces, with the requirement that the keys are unique within a dictionary. The main operation of a dictionary is storing a value corresponding to a given key and extracting the value for that given key. Unlike sequences, which are indexed by a range of numbers, the dictionary is indexed by key (key should be of an immutable type, strings and numbers can always be keys).

Tuples can be used as keys if they contain only strings, numbers, or tuples; if a tuple contains any mutable object either directly or indirectly, it cannot be used as a key. The list cannot be used as keys, since lists are of mutable type. Also, as mentioned previously, Python allows adding a trailing comma after the last item of the dictionary.

>>> a= { ' sape ' : 4139 , ' guido ' : 4127 , ' jack ' : 4098 }
>>> a
{ ' sape ' : 4139 , ' jack ' : 4098 , ' guido ' : 4127 }
>>> a [ ' jack ' ]
4098
>>> a= { ' sape ' : 4139, ' guido ' : 4127, ' jack ' : 4098 , }
>>> a
{ ' sape ' : 4139 , ' jack ' : 4098 , ' guido ' : 4127 }

Dictionary creation

Dictionary can be created in many ways.

Using curly braces

Placing a comma-separated record of key-value pairs within the braces adds initial key-value pairs to the dictionary; this is also the way dictionaries are written as output.

>>> a= { ' sape ' : 4139 , ' guido ' : 4127 , ' jack ' : 4098 }
>>> a 
{ ' sape ' , : 4139 , ' jack ' : 4098 , ' guido ' : 412 7 }

A pair of braces creates an empty dictionary.

>>> a= { }
>>> a 
{ }
>>> type ( a ) 
<type ' dict ' >

Dictionary comprehension

Dictionary comprehension provides a concise way to create a dictionary.

>>> { x : x**2 for x in ( 2 , 4 , 6 ) } 
{ 2 : 4 , 4 : 16 , 6 : 36 }

Using built-in function

Dictionary can also be created using a built-in function diet ( ). Consider the following example using diet (), which returns the same dictionary { ” one ” : 1 , ” two ” : 2 , ” three ” : 3 } :

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

Accessing dictionary elements

To access a dictionary value, use the key enclosed within the square bracket. A KeyError exception is raised if the key is not present in the dictionary.

>>> a= { ' sape ' : 4139 , ' guido ' : 4127 , ' jack ' : 4098 }
>>> a [ ' guido ' ]
4127

Updating dictionary elements

It is possible to add a new item in a dictionary and can also change the value for a given key.

>>> a= { 'sape ' : 4139 , ' guido ' : 4127 , ' jack ' : 4098 }
>>> a [ ' mike ' ]=2299 # Add new item
>>> a [ ' guido ' ]=1000 # Update existing item
>>> a
{ ' sape ' : 4139 , ' mike ' : 2299 , ' jack ' : 4098 , ' guido ' : 1000 }

It is also possible to update a dictionary with another dictionary using the update ( ) method (discussed later).

Deleting dictionary elements

To remove a dictionary item (key-value pair) or the entire dictionary, one can use the del statement. To remove all items (resulting in an empty dictionary), the clear ( ) method (discussed later) can be used.

>>> a= { ' sape ' : 4139 , ' guido ' : 4127 , ' jack ' : 4098 } 
>>> del a [ ' guido ' ]
>>> a
{ ' sape ' : 4139 , ' jack ' : 4098 }
>>> del a
>>> a
Traceback ( most recent call last ) :
File " <stdin> ", line 1, in <module>
NameError: name ' a ' is not defined

Membership operation

Dictionary support membership operation i.e. checking the existence of a key in the dictionary.

>>> a= { 'sape ' : 4139 , ' guido ' : 4127 , ' jack ' : 4098 }
>>> ' jack ' in a 
True
>>> ' tom ' not in a 
True
>>> 4127 in a 
False

Looping techniques

When looping through the dictionary, the key and corresponding value can be retrieved at the same time using the iteritems ( ) method.

>>> a= { ' sape ' : 4139 , ' guido ' : 4127 , ' jack ' : 4098 }
>>> for k , v in a . iteritems ( ) :
. . . print k , v
sape 4139 
jack 4098 
guido 4127

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

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

Python Programming – Modules

Modules

A module can contain executable statements as well as function definitions. These statements are intended to initialize the module. They are executed only the first time the module name is encountered in an import statement; they also run if the file is executed as a script.

Each module has its own private symbol table, which is used as the global symbol table by all functions defined in the module. Thus, the author of a module can use global variables in the module without worrying about accidental clashes with a user’s global variables.

Modules can import other modules. It is customary but not required to place all import statements at the beginning of a module. The imported module names are placed in the importing module’s global symbol table.

There is a variant of the import statement that imports specific names from a module directly into the importing module’s symbol table. For example, specific attributes of fibo module are imported in the local namespace as:

>>> from fibo import fib, fib2 
>>> fib ( 500 )
1 1 2 3 5 8 13 21 34 55 89 144 233 377

This does not introduce the module name from which the imports are taken in the local symbol table (so in the example, fibo is not defined).

There is even a variant to import all names that a module defines:

>>> from fibo import *
>>> fib ( 500 )
1 1 2 3 5 8 13 21 34 55 89 144 233 377

This imports all names except those beginning with an underscore ( _ ).

Note that in general, the practice of importing * from a module or package is discouraged, since it often causes poorly readable code. However, it is touse it to save typing in an interactive sessions. For efficiency reasons, each module is only imported once per interpreter session. If changes are made in many modules, it is a wise approach to restart the interpreter or if it is just one module that needs to be tested interactively, use reload (), e.g. reload (modulename).

Executing modules as scripts

When a Python module is run at command prompt

$ python fibo . py <arguments>

the code in the module will be executed, just as if it imported, but with the ___name___ set to ___main___ . That means, by adding the following code at the end of the module:

if __name___ == " ___main___ " :
import sys
fib ( int ( sys . argv [ 1 ] ) )

the file is made usable as a script as well as an importable module, because the code that parses the command line only runs if the module is executed as the “main” file:

$ python fibo . py 50 
1 1 2 3 5 8 13 21 34

The Module Search Path

When a module named f ibo is imported, the interpreter first searches for a built-in module with that name. If not found, it then searches for a file named fibo.py in a list of directories given by the variable sys. path. The variable sys. the path is initialized from some of these locations:

  • The current directory.
  • PYTHONPATH environment variable (a list of directory names, with the same syntax as the shell variable PATH).

After initialization, Python programs can modify sys .path. The directory containing the script being run is placed at the beginning of the search path, ahead of the standard library path. This means that scripts in that directory will be loaded instead of modules of the same name in the library directory.

Math module

Python has math module and it is always available. The functions provided in this module cannot be used with complex numbers; use the functions of the same name from the cmath module for support of complex numbers. The distinction between functions which support complex numbers and those which does not is made since most users do not want to learn quite as much mathematics as required to understand complex numbers. Except when explicitly noted otherwise, all functions return float values.

Python Programming – Random module

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

Python Programming – Random module

Random module

This module implements pseudo-random number generators for various distributions. Almost all module functions depend on the basic function random ( ), which generates a random float uniformly in the semi-open range [0 . 0 , 1 . 0 ). Python uses the “Mersenne Twister” as the core generator. However, Mersenne Twister being completely deterministic, it is not suitable for all purposes and is completely unsuitable for cryptographic purposes.

Functions for integers

random.randrange ( stop )

Return a randomly selected integer element from range ( 0 , stop ) .

>>> random . randrange ( 88 )
17
>>> random . randrange ( -88 )

Traceback ( most recent call last ) :
File "<pyshell#l>" , line 1 , in <module> 
random . randrange ( -88 )
File " C : \ Python27 \ lib \ random . py " , line 191 , in randrange 
raise ValueError , " empty range for randrange ( ) "
ValueError: empty range for randrange ( )

random . randrange ( start , stop [ , step ] )
Return a randomly selected integer element from range ( start , stop , step ) .

>>> random . randrange ( 3 , 100 , 5 )
83

random . randint ( a , b )
Return a random integer N such that a<=N<=b.

>>> random . randint ( 5 , 86 )
70

Functions for sequences

random . choice ( seq )
Return a random element from the non-empty sequence seq. If seq is empty, raises IndexError.

>>> random . choice ( ' abcdefghij ' )
' e ' 
>>> random . choice ( [ ' aa ' , ' bb ' , ' cc ' , 11 , 22 ] )
' cc '

random . shuffle ( x [ , random ] )
Shuffle the sequence x in place. The optional argument random is a O-argument function returning a random float in [ 0 . 0 , 1 . 0 ); by default, this is the function random ( ).

>>> items= [ 1 , 2 , 3 , 4 , 5 , 6 , 7 ]
>>> random . shuffle ( items )
>>> items
[ 4 , 7 , 2 , 6 , 3 , 5 , 1 ]

random . sample ( population , k )
Return a k length list of unique elements chosen from the population sequence; used for random sampling without replacement. Return a new list containing elements from the population, while leaving the original population unchanged. If the population contain repeating elements, then each occurrence is a possible selection in the sample.

>>> random . sample ( [ 1 , 2 , 3 , 4 , 5 ] , 3 )
[ 4 , 5 , 1 ]

To choose a sample from a range of integers, use an xrange ( ) object as an argument. This is especially fast and space efficient for sampling from a large population.

>>> random . sample ( xrange ( 10000000 ) , 5 )
[ 2445367 , 2052603 , 975267 , 3021085 , 6098369 ]

Functions for floating point values

random . random ( )
Return the next random floating point number in the range [ 0 . 0 , 1 . 0 ).

>>> random . random ( )
0.6229016948897019

random . uniform ( a , b )
Return a random floating point number N, such that a<=N<=b for a<=b and b<=N<=a for b<a.

>>> random . uniform ( 0 . 5 , 0 . 6 )
0.5795193565565696

random . triangular ( low , high , mode )
Return a random floating point number N such that low<=N<=high and with the specified mode between those bounds. The low and high bounds default to 0 and 1, respectively. The mode argument defaults to the midpoint between the bounds, giving a symmetric distribution.

>>> random . triangular ( 2 . 8 , 10 . 9 , 7 . 5 )
6.676127015045406

random . betavariate ( alpha , beta )
Beta distribution; conditions of the parameters are alpha>0 and beta>0. Returned values range between 0 and 1.

>>> random . betavariate ( 2 . 5 , 1 . 0 )
0.543590525336106

random . expovariate ( lambd )
Exponential distribution; lambd is 1.0 divided by the desired mean. It should be nonzero. Returned values range from 0 to positive infinity; if lambd is positive, and from negative infinity to 0, if lambd is negative.

>>> random . expovariate ( 0 . 5 )
1.5287594548764503

random . gammavariate ( alpha , beta )
Gamma distribution (not the gamma function). Conditions of the parameters are alpha>0 and beta>0.

>>> random . gammavariate ( 1 . 3 , 0 . 5 )
0.5893587279305473

random . gauss ( mu , sigma )
Gaussian distribution; mu is the mean, and sigma is the standard deviation. This is slightly faster than the normalvariate () function defined below.

>>> random . gauss ( 0 . 5 , 1 . 9 )
-1.8886943114939512

random . lognormvariate ( mu , sigma )
Log normal distribution; if natural logarithm of this distribution is taken, a normal distribution with mean mu, and standard deviation sigma is received, mu can have any value, and sigma must be greater than zero.

>>> random . lognormvariate ( 0 . 5 , 1 . 9 )
4.621063728160664

random . normalvariate ( mu , sigma )
Normal distribution; mu is the mean, and sigma is the standard deviation.

>>> random . normalvariate ( 0 . 5 , 1 . 9 )
1.6246107732503214

random . vonmisesvariate ( mu , kappa )
mu is the mean angle, expressed in radians between 0 and 271, and kappa is the concentration parameter, which must be greater than or equal to zero. If kappa is equal to zero, this distribution reduces to a uniform random angle over the range 0 to 2K .

>>> random . vonmisesvariate ( 0 . 5 , 1 . 9 )
-0.4664831190641767

random . paretovariate ( alpha )
Pareto distribution; alpha is the shape parameter.

>>> random . paretovariate ( 0 . 5 )
60.471412103322585

random . weibullvariate ( alpha , beta )
Weibull distribution; alpha is the scale parameter and beta is the shape parameter.

>>> random . weibullvariate ( 0 . 5 , 1 . 9 )
0.9229896561284915

Alternative generators

Apart from Mersenne Twister, there are more core random number generator, such as generator based on “Wichmann-Hill” algorithm.

>>> rnd=random . WichmannHill ( )
>>> rnd . random ( )
0.4065226158909223
>>>
>>> rnd=random . SystemRandom ( )
>>> rnd . random ( )
0.46579102190832355

Python Programming – List

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

Python Programming – List

List

Python has a number of built-in types to group together data items. The most versatile is the list, which is a group of comma-separated values (items) between square brackets. List items need not be of the same data type.

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

Python allows adding a trailing comma after the last item of list, tuple, and dictionary, There are several reasons to allow this:

  • When the list, tuple, or dictionary elements spread across multiple lines, one needs to remember to add a comma to the previous line. Accidentally omitting the comma can lead to errors that might be hard to diagnose. Always adding the comma avoids this source of error (the example is given below).
  • If the comma is placed in each line, it can be reordered without creating a syntax error.

The following example shows the consequence of missing a comma while creating a list.

>>> a=[
         ' hi ' , 
         ’ hello ’ 
         ' bye ’ , 
         ' tata ' , 
         ] 
>>> a
[ ' hi ' ,  ' hellobye ' ,  ' tata ' ]

This list looks like it has four elements, but it actually contains three: ‘ hi ‘,  ‘ hellobye ‘, and  ‘ tata ‘. Always adding the comma avoids this source of error.

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 – 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 – 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 – Basic Operations

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

Python Programming – Basic Operations

Basic Operations

Arithmetic operations when applied on NumPy arrays, they are implemented element-wise.

>>> a=np . array ( [ 20 , 30 , 40 , 50 ] )
>>> b=np . arange ( 4 ) 
>>> c=a - b 
>>> c
array ( [ 20 , 29 , 38 , 47 ] )
>>> b**2
array ( [ 0 , 1 , 4 , 9 ] )
>>> a<39
array ( [ True , True , False , False ] , dtype=bool )

The product operator * operates element-wise in NumPy arrays. The matrix product can be performed using the dot ( ) function or creating matrix objects (refer section 7.8).

>>> a=np . array ( [ [ 1 , 1 ] ,
. . . [ 0 , 1 ] ] )
>>> b=np . array ( [ [ 2 , 0 ] ,
. . . [ 3 , 4 ] ] )
>>> a*b 
array ( [ [ 2 , 0 ] ,
[ 0 , 4 ] ] )
>>> np . dot ( a , b ) 
array ( [ [ 5 , 4 ] ,
[ 3 , 4 ] ] )

Some operations, such as +=, *=, etc., modifies an existing array, rather than creating a new array.

>>> a=np . array ( [ [ 1 , 2 ] ,                        # a is integer type
. . . [ 3 , 4 ] ] )
>>> b=np . array ( [ [ 1 . , 2 . ] ,                   # b is float type
. . . [ 3 . , 4 . ] ] )
>>> a*=2 
>>> a
array ( [ [ 2 , 4 ] ,
[ 6 , 8 ] ] )
>>> b+=a 
>>> b
array ( [ [ 3 . , 6 . ] ,
[ 9 . , 12 . ] ] )
>>> a+=b                                                  # b is converted to integer type
>>> a
array ( [ [ 5 , 10 ] ,
[ 15 , 20 ] ] )

When operating with arrays of different types, the type of the resulting array corresponds to the more general or precise one (a behavior known as “upcasting”).

>>> a=np . array ( [ 1 . 1 , 2 . 2 , 3 . 3 ] )
>>> a . dtype . name
' float64 ' 
>>> b=np . array ( [ 4 , 5 , 6 ] )
>>> b . dtype . name ' int32 '
>>> c=a+b 
>>> c
array 0( [ 5 . 1 , 7 . 2 , 9 . 3 ] )
>>> c . dtype . name ' float64 '

Many unary operations, such as computing the sum of all the elements in the array, are implemented as methods of the ndarray class .

>>> a=np . array ( [ [5 , 8 ] ,
. . . [ 3 , 6 ] ] )
>>> a . sum ( )
22
>>> a . min ( )
3
>>> a . max ( )
8

By default, these operations apply to the array as though it were a list of numbers, regardless of its shape. However, by specifying the axis parameter you can apply an operation along the specified axis of an array:

>>> a=np . arange ( 12 ) . reshape ( 3 , 4 )
>>> a
array ( [ [ 0 , 1 , 2 , 3 ] ,
[ 4 , 5 , 6 , 7 ] ,
[ 8 , 9 , 10 , 11 ] ] )
>>> a.sum(axis=0)                                             # Sum of each column
array ( [12, 15, 18, 21] )
>>> a.min(axis=1)                                             # Minimum of each now
array ( [ 0 , 4 , 8 ] )
>>> a . cumsum ( axis=1 )                                  # Cumulative sum along each now
array ( [ [ 0 , 1 , 3 , 6 ] ,
[ 4 , 9 , 15 , 22 ] ,
[ 8 , 17 , 27 , 38 ] ] )

Python Programming – NumPy Array

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

Python Programming – NumPy Array

NumPy array

NumPy’s main object is the homogeneous multi-dimensional array. It is a table of elements (usually numbers), all of the same type, indexed by a tuple of positive integers. In NumPy, array dimensions are called “axes”, and the number of axes is known as “rank”. For example, the coordinates of a point in 3D space [ 1, 2, 1 ] is an array of rank 1, because it has one axis and that axis has a length of 3. In the following example, the array has rank 2 (it is two-dimensional). The first dimension (axis) has a length of 2, the second dimension has a length of 3.

[ [ 1 . , 0 . , 0 . ] , 
[ 0 . , 1 . , 2 . ] ]

Some of the attributes of an ndarray object are:

ndarray . ndim
The number of axes (dimensions) or rank of the array.

ndarray . shape
The dimensions of the array. This is a tuple of integers indicating the size of the array in each dimension. For an array of n rows and m columns, shape will be (n, m). The length of the shape tuple is therefore the rank ndim.

ndarray.size
The total number of elements of the array. This is equal to the product of the elements of shape.

ndarray.dtype
An object describing the type of the elements in the array. One can create or specify dtype using standard Python type. Additionally, NumPy provides types of its own, numpy.int32, numpy. intl6, and numpy. f loat64 are some examples.

ndarray.itemsize
The size in bytes of each element of the array. For example, an array of elements of type float 6 4 has itemsize as 8 (=64/8), while one of type complex32 has itemsize as 4 (=32/8). It is equivalent to ndarray. dtype . itemsize.’

>>> import numpy as np
>>> a=np . array ( [ [ 0 , 1 , 2 , 3 , 4 ] ,
. . .                           [ 5 , 6 , 7 , 8 , 9 ] , 
. . .                           [ 10 , 11 , 12 , 13 , 14 ] ] )
. . . 
>>> type ( a )
<type ' numpy . ndarray ' > 
>>> a . shape 
( 3 , 5 )
>>> a . ndim 
2
>>> a.dtype 
dtype ( ' int32 ' )
>>> a . dtype . name
' int32 '
>>> a.itemsize 
4
>>> a . size 
15

Array creation

There are several ways to create NumPy array, one approach is from a regular Python list or tuple using the array () method. The type of the resulting array is deduced from the type of the elements in the sequences.

>>> import numpy as np 
>>> a=np.array ( [ 1 , 2 , 3 ] )
>>> a . dtype 
dtype ( ' int32 ' )
>>> b=np . array ( ( 1 . 2 , 3 . 4 , 5 . 6 ) )
>>> b. dtype 
dtype ( ' float64 ' )

A frequent error consists in calling array ( ) with multiple numeric arguments, rather than providing a single list or tuple of numbers as an argument.

>>> a=np . array ( 1 , 2 , 3 , 4 )      # WRONG
>>> a=np . array ( [ 1 , 2 , 3 , 4] )  # RIGHT

array ( ) transforms sequence of sequences into two-dimensional arrays, sequences of sequences of sequences into three-dimensional arrays, and so on.

>>> b=np . array ( [ ( 1 . 5 , 2 , 3 ) , ( 4 , 5 , 6 ) ] )
>>> b
array ( [ [ 1 . 5 , 2 . , 3 . ] ,
[ 4 . , 5 . , 6 . ] ] )

The type.of the array can also be explicitly specified at creation time:

>>> c=np . array ( [ [ 1 , 2 ] , [ 3 , 4 ] ] , dtype=np.complex)
>>> c
array ( [ [ 1 .+0 . j , 2 . + 0 . j ] ,
[ 3 . +0 . j , 4 . + 0 . j ] ] )

Often the elements of an array are initially unknown, but array size is known. Hence, NumPy offers several functions to create array with initial placeholder content. The function zeros ( ) create an array full of zeros, the function ones ( ) create an array full of ones, and the function empty ( ) create an array whose initial content is random. By default, the dtype of the created array is f loat6 4.

>>> np. zeros ( ( 3 , 4 ) )
array ( [ [ 0 . , 0 . , 0 . , 0 . ] ,
             [ 0 . , 0 . , 0 . , 0 . ] ,
             [ 0 . , o . , 0 . , 0 . ] ] )
>>> np . zeros [ 3 , 4] ) 
array ( [ [ 0 . , o . , o . , 0 . ] ,
           [ o . , o . , o . , 0 . ] ,
           [ o . , o . , o . , 0 . ] ] )
>>> np . ones ( ( 2 , 3 , 4 ) , dtype=np . int16 ) 
array ( [ [ [ 1 , 1 , 1 , 1 ] ,
           [ 1 , 1 , 1 ] ,
           [ 1 , 1 , 1 , 1] ] ,

           [ [ 1 , 1 , 1 , 1 ] ,
           [ 1 , 1 , 1 , 1 ] ,
           [ 1 , 1 , 1 , 1 ] ] ] , dtype=intl6 )
>>> np . empty ( ( 2 , 3 ) )
array ( [ [ 1 . 39069238e-309 , 1 . 39069238e-309 , 1 . 39069238e-309 ] ,
           [ 1 . 39069238e-309 , 1 . 39069238e-309 , 1 . 39069238e-309 ] ] )

 

To create sequences of numbers, NumPy provides a function arange ( ), analogous to Python’s built- in function range ( ), that returns array instead of list.

>>> np . arange ( 10 , 30 , 5 ) 
array ( [ 10 , 15 , 20 , 25 ] )
>>> np . arange ( 0 , 2 , 0 . 3 )
array ( [ 0 . , 0 . 3 , 0 . 6 , 0 . 9 , 1 . 2 , 1 . 5 , 1 . 8 ] )

When arange ( ) is used with floating point arguments, it is generally not possible to predict the number of elements obtained, due to the finite floating point precision. For this reason, it is usually better to use the function linspace ( ), that receives as an argument the number of elements that we want, instead of the step:

>>> np . linspace ( 0 , 2 , 5 )
array ( [ 0 . , 0 . 5 , 1 . , 1 . 5 , 2 . ] )
>>> np . linspace ( 0 , np . pi , 4 )
array ( [ 0 . , 1 . 04719755 , 2 . 0943951 , 3 . 14159265 ] )

Printing array

While printing an array, NumPy display it in a similar way to nested lists, but with the following layout:

  • the last axis is printed from left to right.
  • the second-to-last is printed from top to bottom.
  • the rest are also printed from top to bottom, with each slice separated from the next by an empty line.
>>> np . arange ( 6 )                                                     # Id array
array ( [ 0 , 1 , 2 , 3 , 4 , 5 ] )
>>>
>>> np . arange ( 12 ) . reshape ( 4 , 3 )                       # 2d array
array ( [ [ 0 , 1 , 2 ] ,
           [ 3 , 4 , 5 ] ,
           [ 6 , 7 , 8 ] ,
           [ 9 , 10 , 11 ] ] )
>>>
>>> np . arange ( 24 ) . reshape ( 2 , 3 , 4 )                    # 3d array
array ( [ [ [ 0 , 1 , 2 , 3 ] ,
           [ 4 , 5 , 6 , 7 ] , 
           [ 8 , 9 , 10 , 11 ] ]

          [ [12 , 13 , 14 , 15 ] ,
          [ 16 , 17 , 18 , 19 ] ,
          [ 20 , 21 , 22 , 23 ] ]

If an array is too large to be printed, NumPy automatically skips the central part of the array and only print the corners:

>>> np . arange ( 10000 )
array ( [ 0 , 1 , 2 , 9997 , 9998 , 9999 ] )
>>>
>>> np . arange ( 10000 ) . reshape ( 100 , 100 )
array ( [ [ 0 , 1 , 2 , . . . , 97 , 98 , 99 , ] , 
[ 100, 101, 102, . . . , 197 , 198 , 199 ] ,
[ 200 , 201 , 202 , . . . , 297 , 298 , 299 ] ,
. . . 
[ 9700 , 9701 , 9702 , . . . , 9797 , 9798 , 9799 ] ,
[ 9800 , 9801 , 9802 , . . . , 9897 , 9898 , 9899 ] ,
[ 9900 , 9901 , 9902 , . . . , 9997 , 9998 , 9999 ] ]

To disable this behaviour and force NumPy to print the entire array, the printing option set_printoptions need to be changed.

>>> np . set_printoptions ( threshold=' nan '