Author name: Prasanna

Python Programming – Data Structures

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

Python Programming – Data Structures

A data structure is a group of data elements grouped together under one name. Python’s data structures are very intuitive from a syntax point of view, and they offer a large choice of operations. This chapter tries to put together the most common and useful information about various data structures. Some of the Python’s data structures that are discussed in this book are list, tuple, set, and dictionary.

Types of Data Structures in Python
Python has implicit support for Data Structures which enable you to store and access data. These structures are called List, Dictionary, Tuple and Set.

Python allows its users to create their own Data Structures enabling them to have full control over their functionality. The most prominent Data Structures are Stack, Queue, Tree, Linked List and so on which are also available to you in other programming languages. So now that you know what are the types available to you, why don’t we move ahead to the Data Structures and implement them using Python.

TreeStructure-Data-Structures-in-Python

Built-in Data Structures
As the name suggests, these Data Structures are built-in with Python which makes programming easier and helps programmers use them to obtain solutions faster. Let’s discuss each of them in detail.

Python Programming – Data Structures Read More »

Python Programming – Tuple

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

Python Programming – Tuple

Tuple

There is also another sequence type- tuple. Tuples is a sequence just like list. The differences are that tuple cannot be changed i.e. tuple is immutable, while list is mutable, and tuple use parentheses, while list use square brackets. Tuple items need not to be of same data type. Also, as mentioned previously, Python allow adding a trailing comma after last item of tuple.

>>> a= ( ' spam ' , ' eggs ' , 100 , 1234 )
>>> a
( ' spam ' , ' eggs ' , 100 , 1234 )
>>> a= ( ' spam ' , ' eggs ' , 100 , 1234 , )
>>> a
( ' spam ' , ' eggs ' , 100 , 1234 )

The above expressions are examples of a “tuple packing” operation i.e. the values ‘ spam ‘, ‘ eggs ‘, 10 0, and 123 4 are packed together in a tuple. The reverse operation is also possible, for example:

>>> a1 , a2 , a3 , a4=a 
>>> a1
' spam '
>>> a2 ' eggs '
>>> a3 100
>>> a4 1234

This is called “sequence unpacking”, and works for any sequence on the right-hand side. Sequence unpacking requires the group of variables on the left to have the same number of elements as the length of the sequence. Note that multiple assignments are really just a combination of tuple packing and sequence unpacking.

>>> a , b=10 , 20 
>>> a 
10
>>> b 
20

Tuple creation

Tuple can be created in many ways.

Using parenthesis

Creating a tuple is as simple as grouping various comma-separated-values, and optionally these comma-separated values between parentheses.

>>> a= ( ' spam ' eggs ' 100 , 1234 )
>>> a
( ' spam ' , ' eggs ' , 100 , 1234 )
>>> a= ( ' spam ' , ' eggs ' , 100 , 1234 )
>>> a
( ' spam ' , ' eggs ' , 100 , 1234 )
>>> a= ' spam ' , ' eggs ' , 100 , 1234 
>>> a
( ' spam ' , ' eggs ' , 100 , 1234 )
>>> a= ' spam ' , ' eggs ' , 100 , 1234 ,
>>> a
( ' spam ' , ' eggs ' , 100 , 1234 )

A tuple with one item is created by a comma after the item (it is not necessary to enclose a single item in parentheses).

>>> a= ( 10 )
>>> a 
10
>>> type ( a )
<type ' int ' >
>>> b= ( 10 ,)
>>> b
( 10 , )
>>> type ( b )
<type ' tuple ' >
>>> c=10,
>>> c
( 10 , )
>>> type ( c )
<type ' tuple ' >

It is also possible to create an empty tuple by assigning parenthesis to a variable.

>>> a= ( ) 
>>> a
( )

Using other tuples

A tuple can also be created by copying a tuple or slicing a tuple.

>>> a= ( ' spam ' , ' eggs ' , 100 , 1234 )
>>> b=a [ : ]
>>> b
( ' spam ' , ' eggs ' , 100 , 1234 )
>>> c=a [ 1 : 3 ]
>>> c
( ' eggs ' , 100 )

Using built-in function

Tuple can also be created using the built-in function tuple ( ). The tuple ( [iterable] ) function return a tuple whose items are the same and in the same order as items of the iterable. The iterable may be a sequence, a container that supports iteration, or an iterator object. If iterable is already a tuple, it is returned unchanged. If no argument is given, an empty tuple is returned.

>>> tuple ( [ ' apple ' , ' pineapple ' , ' banana ' ] )
( ' apple ' , ' pineapple ' , ' banana ' )
>>> tuple ( ' apple ' )
( ' a ' , ' p ' , ’ p ' , ’ 1 ’ , ’ e ’ )
>>> tuple ( [ ' apple ' ] ) 
( ' apple ' , )

Accessing tuple elements

The tuple index starts with 0, and to access values in a tuple, use the square brackets with the index or indices to obtain a slice of the tuple.

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

Update tuple

Tuple is immutable, so changing element value or adding new elements is not possible. But one can take portions of existing tuples to create a new tuples.

>>> tuple1= ( 1 , 2 , 3 )
>>> tuple2=( ' a ' , ' b ' , ' c ' )
>>> tuple3=tuple1+tuple2 
>>> tuple3
( 1 , 2 , 3 , ' a ' , ' b ' , ' c ' )
>>> tuple3=tuple1 [ 0 : 2 ]+tuple2 [ 1 : 3 ] 
>>> tuple3
( 1 , 2 , ' b ' , ' c ' )

It is also possible to create tuple which contain mutable objects, such as lists.

>>> a= [ 1 , 2 , 3 ] , [ 4 , 5 , 6 , 7 ]
>>> a
( [ 1 , 2 , 3 ] , [ 4 , 5 , 6 , 7 ] )
>>> a [ 0 ] [ 1 ]=200
>>> a 
( [ 1 , 200 , 3 ] , [ 4 , 5 , 6 , 7 ] )

Deleting tuple

Removing individual tuple elements is not possible. To explicitly remove an entire tuple, just use the del statement.

>>> a= ( ' spam ' ' eggs ' , 100 , 1234 )
>>> del a

Swapping tuples

There might be a scenario in which multiple tuples needs 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 – Tuple Read More »

Python Programming – Some List Operations

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

Python Programming – Some List Operations

Some list operations

Some of the list operations supported by Python are given below.

Concatenation

List concatenation can be carried out using the + operator.

>>> [ 1 , 2 , 3 ] +[ ' hi ' , ' hello ' ]
[ 1 , 2 , 3 , ' hi ' , ' hello ' ] ;

Repetition

The * operator can be used to carry out repetition operations.

>>> [ ' Hey ' ] *3 
[ ' Hey ' , ' Hey ' , ' Hey ' ]

Membership operation

The list also supports membership operation i.e. checking the existence of an element in a list.

>>> 4 in [ 6 , 8 , 1 , 3 , 5 , 0 ]
False 
>>> 1 in [ 6 , 8 , 1 , 3 , 5 , 0 ]
True

Slicing operation

As list is a sequence, so indexing and slicing work the same way for list as they do for strings. All slice operations return a new list containing the requested elements:

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

List slicing can be in form of steps, the operation s [ i: j: k ] slices the list s from i to j with step k.

>>> squares=[ x**2 for x in range ( 10 ) ] 
>>> squares
[ 0 , 1 , 4 , 9 , 16 , 25 , 36 , 49 , 64 , 81 , 100 , 121 , 144 , 169 , 196 ]
>>> squares [ 2 : 12 : 3 ]
[ 4 , 25 , 64 , 121 ]

Slice indices have useful defaults, an omitted first index defaults to zero, an omitted second index defaults to the size of the list being sliced.

>>> squares= [ x**2 for x in range ( 10 ) ]
>>> squares 
[0 , 1 , 4 , 9 , 16 , 25 , 36 , 49 , 64 , 81 , 100 , 121 , 144 , 169 , 196 ]
>>> squares [ 5 : ]
[ 25 , 36 , 49 , 64 , 81 , 100 , 121 , 144 , 169 , 196 ]
>>> squares [ : 5 ]
[ 0 , 1 , 4 , 9 , 16 ]

Python Programming – Some List Operations Read More »

Python Programming – Modules and Packages

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

Python Programming – Modules and Packages

As the program gets longer, it is a good option to split it into several files for easier maintenance. There might also be a situation when the programmer wants to use a handy function that is used in several programs without copying its definition into each program. To support such scenarios, Python has a way to put definitions in a file and use them in a script or in an interactive instance of the interpreter.

Module

A module is a file containing Python definitions and statements. The file name is the module name with the suffix .py appended. Definitions from a module can be imported into other modules. For instance, consider a script file called “fibo.py” in the current directory with the following code.

# Fibonacci numbers module

def fib ( n ) :                                        # write Fibonacci series up to n
         a , b=0 , 1 
         while b<n :
            print b , 
            a, b=b , a+b

def fib2 ( n ) :                                    # return Fibonacci series up to n
          result= [ ] 
          a , b = 0 , 1 
          while b<n:
               result . append ( b ) 
          a , b=b , a+b 
   return result

Now on the Python interpreter, import this module with the following command:

>>> import fibo

Within a module, the module’s name (as a string) is available as the value of the global variable
___name___:

>>> fibo.___name___ 
' fibo '

Use the module’s name to access its functions:

>>> fibo . fib ( 1000 )
1 1 2 3 5 8  13  21  34  55  89  144  233  377  610  987 
>>> fibo . fib2 ( 1000 )
[ 1 ,  1 ,  2 ,  3 ,  5 ,  8 ,  13 ,  21 ,  34 ,  55 ,  89 ,  144 ,  233 ,  377 ,  610 ,  987 ]

If it is intended to use a function often, assign it to a local name:

>>> Fibonacci=fibo . fib 
>>> Fibonacci ( 500 )
1  1  2  3  5  8  13  21  34  55  89  144  233  377

Python Programming – Modules and Packages Read More »

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 – Modules Read More »

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 – Random module Read More »

Python Programming – Set

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

Python Programming – Set

Set

A set is an unordered collection with no duplicate elements. Basic uses include membership testing, eliminating duplicate entries from sequence, mathematical operations like union, intersection, difference, symmetric difference etc. As mentioned in chapter 2, sets are of two types: set (mutable set) and frozenset (immutable set).

>>> a=set ( [ ’ spam ’ , ' eggs ' , 100 , 1234 ] ) 
>>> a
set ( [ ' eggs ' , 100 , 1234 , ' spam ' ] ) 
>>> a=set ( ' abracadabra ' )
>>> a
set ( [ ' a ' , ' r ' , ' b ' , ' c ' , ' d ' ] )
>>> a-frozenset ( [ ' spain ' , ' eggs ' , 100 , 1234 ] ) 
>>> a
frozenset ( [ ' eggs ' , 100 , 1234 , ' spam ' ] )

Being an unordered collection, sets do not record element position or order of insertion. Accordingly, sets do not support indexing, slicing, or other sequence-like behavior.

Set creation

A set can be created in many ways.

Using curly braces

Non-empty set (not frozenset) can be created by placing a comma-separated list of elements within braces. Curly braces cannot be used to create an empty set, because it will create an empty dictionary that will be discussed in the next section.

>>> { ' spam ' , ' eggs ' , 100 , 1234 } 
set ( [ 1234 , 100 , ' eggs ' , ' spam ' ] )

Set comprehension

Python also supports set comprehension:

>>> a= { x for x in ' abracadabra ' if x not in ' abc ' }
>>> a
set ( [ ' r ' , ' d ' ] )

Using built-in function

The built-in functions set ( ) and frozenset ( ) are used to create set and frozenset, respectively, whose elements are taken from iterable. If iterable is not specified, a new empty set is returned.

>>> a=set ( ( ' spam ' , ' eggs ' , 100 , 1234 ) )
>>> a
set ( [ ' eggs ' , 100 , 1234 , ' spam ' ] )
>>> set ( )
set ( [ ] ) 
>>> a=frozenset ( ( ' spam ' , ' eggs ' , 100 , 1234 ) )
>>> a
frozenset ( [ ' eggs ' , 100 , 1234 , ' spam ' ] )
>>> frozenset ( ) 
frozenset ( [ ] ) 
>>> set ( ' abc ' )==frozenset ( ' abc ' )
True

Deleting set

To explicitly remove an entire set, just use the del statement.

>>> ss=set ( ' abracadabra ' )
>>> ss
set ( [ ' a ' , ' r ' , ' b ' , ' c ' , ' d ' ] )
>>> del SS 
>>> SS
Traceback ( most recent call last ) :
File "<stdin>", line 1 , in <module>
NameError: name ' ss ' is not defined

Looping techniques

It is also possible to iterate over each element of a set. However, since set is unordered, it is not known which order the iteration will follow.

>>> ss=set ( ' abracadabra ' )
>>> ss
set ( [ ' a ' , ' r ' , ' b ' , ' c ' , ' d ' ] ) 
>>> for item in ss:
. . . print item
a
r
b
c
d

Membership operation

Set also support membership operation.

>>> a=set ( ' abracadabra ' )
>>> a
set ( [ ' a ' , " r ' r ' b ' , ' c ' , ' d ' ] )
>>> ' r ' in a 
True 
>>> ' rrr ' not in a 
True 
>>> a=frozenset ( ' abracadabra ' )
>>> a
frozenset ( [ ' a ' , ' r ' , ' b ' , ' c ' , ' d ' ] ) 
>>> ' r ' in a
True
>>> ' rrr ' not in a 
True

Python Programming – Set Read More »

Python Programming – Set Methods

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

Python Programming – Set Methods

Set methods

Below are the methods of both set and frozenset objects. Note that the non-operator versions of these methods accept any iterable as an argument, while their operator-based counterparts require their arguments to be set (set and frozenset).

isdisjoint ( other )
Return True, if the set has no elements in common with other. Sets are disjoint, if and only if their intersection is the empty set.

>>> s1=set ( [ 5 , 10 , 15 , 20] )
>>> s2=set ( [ 30 , 35 , 40 ] )
>>> s1 . isdisjoint ( s2 )
True 
>>> s1=frozenset ( [ 5 , 10 , 15 , 20 ] )
>>> s2=frozenset ( [ 30 , 35 , 40 ] )
>>> s1 . isdisjoint ( s2 )
True
>>> s1=set ( [ 5 , 10 , 15 , 20 ] )
>>> s2=frozenset ( [30 , 35 , 40 ] ) 
>>> s1 . isdisjoint ( s2 )
True

issubset ( other )
Test whether every element in the set is in other.

>>> s1=set ( [ 5 , 15 ] )
>>> s2=set ( [ 5 , 10 , 15 , 20 ] )
>>> s1 . issubset ( s2 )
True
>>> s1 . issubset ( ( 5 , 10 , 15 , 20 ) )
True
>>> s1=frozenset ( [ 5 , 15 ] )
>>> s2=frozenset ( [ 5 , 10 , 15 , 20 ] )
>>> s1 . issubset ( s2 )
True
>>> s1 . issubset ( ( 5 , 10 , 15 , 20 ) )
True

The operator based version of the the above method is set<=other.

>>> s1=set ( [ 5 , 15 ] )
>>> s2=frozenset ( [ 5 , 10 , 15 , 20 ] )
>>> s1<=s2
True

The operator based version setcother test whether the set is a proper subset of other, that is, set<=other and set!=other.

>>> s1=set ( [ 5 , 15 ] )
>>> s2=frozenset ( [ 5 , 10 , 15 , 20 ] )
>>> s1<s2 
True

issuperset (other).

Test whether every element in other is in the set.

>>> s1=set ( [ 5 , 15 ] )
>>> s2=set ( [ 5 , 10 , 15 , 20 ] ) 
>>> s2 . issuperset ( s1 )
True
>>> s2 . issuperset ( ( 5 , 15 ) )
True
>>> s1=frozenset ( [ 5 , 15 ] )
>>> s2=frozenset ( [ 5 , 10 , 15 , 20 ] )
>>> s2 . issuperset ( s1 )
True
>>> s2 . issuperset ( ( 5 , 15 ) )

The operator based version of the the above method is set >=other.

>>> s1=set ( [ 5 , 15 ] )
>>> s2=frozenset ( [ 5 , 10 , 15 , 20 ] )
>>> s1>=s2 
False

The operator-based version set> another test whether the set is a proper superset of other, that is, set>=other and set! =other.

>>> s1=set ( [ 5 , 15 ] )
>>> s2=frozenset ( [ 5 , 10 , 15 , 20 ] )
>>> s1<s2 
False

union ( other, . . . )

Return a new set with elements from the set and all others.

>>> s1=set ( [ 5 , 15 ] )
>>> s2= [ 15 , 20 , 25 ]
>>> s3=frozenset ( [ 30 , 35 , 40 ] )
>>> s1 . union ( s2 , s3 )
set ( [ 35 , 20 , 5 , 40 , 25 , 30 , 15 ] )

The operator based version of the above method is set | other. . .

>>> s1=set ( [ 5 , 15 ] )
>>> s2=set ( [ 15 , 20 , 25 ] ) 
>>> s3=frozenset ( [ 30 , 35 , 40 ] )
>>> s1 | s2 | s3
set ( [ 35 , 20 , 5 , 40 , 25 , 30 , 15 ] )

intersection ( other , . . .)

Return a new set with elements common to the set and all others .

>>> s1=set ( [ 5 , 10 , 15 ] ) 
>>> s2= [ 15 , 20 , 25 , 10 ]
>>> s3=frozenset ( [ 30 , 15 , 35 , 40 , 10 ] ) 
>>> s4= ( 40 , 50 , 10 , 15 , 20 )
>>> si . intersection ( s2 , s3 , s4 ) 
set ( [ 10 , 15 ] )

The operator based version of the above method is set&other . . .

>>> s1=set ( [ 5 , 10 , 15] )
>>> s2=set ( [ 15 , 20 , 25 , 10 ] )
>>> s3=frozenset ( [ 30 , 15 , 35 , 40 , 10 ] )
>>> s4=frozenset ( [ 40 , 50 , 10 , 15 , 20 ] )
>>> s1&s2&s3&s4 
set ( [ 10 , 15 ] )

difference ( other, . . . )

Return a new set with elements in the set that are not in the others.

>>> s1=set ( [ 5 , 10 , 15 ] )
>>> s2= [ 15 , 20 , 25 , 10 ]
>>> s3=frozenset ( [ 30 , 15 , 35 , 40 , 10 ] )
>>> s4= ( 40 , 50 , 10 , 15 , 20 )
>>> s3.difference ( s1 , s2 , s4 ) 
frozenset ( [ 35 , 30 ] )

The operator based version of the above method is set-other- . . .

>>> s1-set ( [ 5 , 10 , 15 ] )
>>> s2=set ( [ 15 , 20 , 25 , 10 ] )
>>> s3=frozenset ( [ 30 , 15 , 35 , 40 , 10 ] )
>>> s4=frozenset ( [ 40 , 50 , 10 , 15 , 20 ] )
>>> s1 - s2 - s3 - s4 
set ( [ 5 ] )
>>> s3 - s1 - s2 - s4 
frozenpet ( [ 35 , 30 ] )

symmetric_difference ( other )

Return a new set with elements in either the set or other but not both.

>>> s1=set ( [ 5 , 10 , 15 ] )
>>> s2= [ 15 , 20 , 25 , 10 ]
>>> s1 . symmetric_difference ( s2 ) 
set ( [ 25 , 20 , 5 ] )

The operator based version of the the above method is set Aother.

>>> s1=set ( [ 5 , 10 , 15 ] )
>>> s2=frozenset ( [ 15 , 20 , 25 , 10 ] )
>>> s1∧ s2
set ( [ 25 , 20 , 5 ] ) 
>>> s2∧s1
frozenset ( [ 25 , 20 , 5 ] )

copy ( )
Return a copy of the set.

>>> s=set ( [ 5 , 10 , 15 , 20 ] )
>>> a=s.copy ( )
>>> a
set ( [ 10 , 20 , 5 , 15 ] )
>>> s=frozenset ( [ 5 , 10 , 15 , 20] )
>>> a=s.copy ( )
>>> a
frozenset ( [ 10 , 20 , 5 , 15 ] )

The following methods are available for set and do not apply to immutable instances of frozenset.

update ( other , . . . )

Update the set, adding elements from all others.

>>> s1=set ( [ 5 , 15 ] )
>>> s2= ( 15 , 20 , 25 )
>>> s3=frozenset ( [ 30 , 35 , 40] )
>>> s1 . update ( s2 , s3 )
>>> s1
set ( [ 35 , 20 , 5 , 40 , 25 , 30 , 15 ] )

The operator based version of the above method is set | =other | . . .

>>> s1=set ( [ 5 , 15 ] )
>>> s2=set ( [ 15 , 20 , 25 ] )
>>> s3=frozenset ( [ 30 , 35 , 40 ] )
>>> s1|= s2 | s3 
>>> s1
set ( ' [ 35 , 5 , 40 , 15 , 20 , 25 , 30 ] )

intersection_update ( other , . . .)

Update the set, keeping only elements found in it and all others.

>>> s1=set ( [ 5 , 10 , 15 ] )
>>> s2= [ 15 , 20 , 25 , 10 ] 
>>> s3=set ( [ 30 , 15 , 35 , 40 , 10 ] ) 
>>> s4= ( 40 , 50 , 10 , 15 , 20 )
>>> s1 . intersection_update ( s2 , s3 , s4 )
>>> s1
set ( [ 10 , 15 ] )

The operator based version of the the above method is set&=other& . . .

>>> s1=set ( [ 5 , 10 , 15] )
>>> s2=set ( [ 15 , 20 , 25 , 10] )
>>> s3=frozenset ( [ 30 , 15 , 35 , 40 , 10 ] )
>>> s4=frozenset ( [ 40 , 50 , 10 , 15 , 20 ] )
>>> s1&=s2&s3&s4 
>>> s1
set ( [10 , 15 ] )

difference_update(other, . . .)

Update the set, removing elements found in others.

>>> s1=frozenset ( [ 5 , 10 , 15 ] )
>>> s2= [ 15 , 20 , 25 , 10 ]
>>> s3=set ( [ 30 , 15 , 35 , 40 , 10 ] )
>>> s4= ( 40 , 50 , 10 , 15 , 20 )
>>> s3 . difference_update ( s1 , s2 , s4 )
>>> s3
set ( [ 35 , 30 ] )

The operator based version of the above method is set-=other | . . .

>>> s1=frozenset ( [ 5 , 10 , 15 ] )
>>> s2=frozenset ( [ 15 , 20 , 25 , 10 ] )
>>> s3=set ( [ 30 , 15 , 35 , 40 , 10 ] )
>>> s4=frozenset ( [ 40 , 50 , 10 , 15 , 20 ] )
>>> s3-=s1 | s2 | s4 
>>> s3
set ( [ 35 , 30 ] )

symmetric_difference_update(other)
Update the set, keeping only elements found in either set, but not in both.

>>> s1=set ( [ 5 , 10 , 15 ] ) 
>>> s2= [ 15 , 20 , 25 , 10 ]
>>> s1 . symmetric_dif ference_update ( s2 )
>>> s1
set ( [ 25 , 20 , 5 ] )

The operator based version of the the above method is set/’=other.

>>> s1=set ( [ 5 , 10 , 15 ] ) 
>>> s2=frozenset ( [ 15 , 20 , 25 , 10 ] )
>>> s1 A=s2 
>>> s1
set ( [ 25 , 20 , 5 ] )

add ( elem )

The method adds element elem to the set.

>>> s=set ( [ 5 , 10 , 15 , 20 ] )
>>> s.add ( 25 )
>>> s
set ( [ 25 , 10 , 20 , 5 , 15 ] )

remove ( elem )

Remove element elem from the set. Raises KeyError, if elem is not contained in the set.

>>> s=set ( [ 5 , 10 , 15 , 20 ] )
>>> s.remove ( 15 )
>>> s
set ( [ 10 , 20 , 5 ] )
>>> s=set ( [ 5 , 10 , 15 , 20 ] )
>>> s . remove ( 100 )
Traceback ( most recent call last ) :
File " <stdin> " , line 1 , in <module>
KeyError: 100

discard ( elem )

Remove element elem from the set if it is present. It is difference from remove () in a way that it does not raise KeyError if elem is not present in the set.

>>> s=set ( [ 5 , 10 , 15 , 20 ] )
>>> s . discard ( 15 )
>>> s
set ( [ 10 , 20 , 5 ] )
>>> s . discard ( 100 )
>>> s
set ( [ 10 , 20 , 5 ] )

pop ( )

Remove and return an arbitrary element from the set. Raises KeyError, if the set is empty.

>>> s=set ( [ 5 , 10 , 15 , 20] ) 
>>> s . pop ( )
10
>>> s
set ( [ 20 , 5 , 15 ] )
>>> s . pop ( )
20
>>> s
set ( [ 5 , 15 ] )

clear ( )

Remove all elements from the set.

>>> s=set ( [ 5 , 10 , 15 , 20 ] )
>>> s . clear ( )
>>> s 
set ( [ ] )

Python Programming – Set Methods Read More »

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 – Dictionary Read More »

Python Programming – Dictionary Methods

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

Python Programming – Dictionary Methods

Dictionary methods

The following are some dictionary methods supported by Python.

diet . clear ( )
Removes all items from the dictionary.

>>> a= { ' Name ' : ' Zara ' , ' Age ' : 7 }
>>> len ( a )
2 
>>> a . clear ( )
>>> len ( a )
0

diet. copy ( )
Returns a copy of the dictionary.

>>> dict1 = { ' Name ' : ' Zara ' , ' Age ' : 7 ]
>>> dict2=dict1 . copy ( )
>>> dict2
{ ' Age ' : 7 , ' Name ' : ' Zara ' }

diet. fromkeys ( seq [ , value ] )
Create a new dictionary with keys from seq and values set to value (default as None).

>>> seq= ( ' name ' , ' age ' , ' gender ' )
>>> a=dict . fromkeys ( seq )
>>> a 
{ ' gender ' : None , ' age ' : None , ' name ' : None }
>>> a=a.fromkeys ( seq , 10 )
>>> a
{ ' gender ' : 10 , ' age ' : 10 , ' name ' : 10 }

diet . get ( key [ , default ] )
Return the value for the key, if the key is in the dictionary, else default. If the default is not given, the default is None.

>>> a= { ' Name ' : ' Zara ' , ' Age ' : 7 }
>>> a.get ( ' Age ' )
7
>>> a. get ( ' Gender ' , ' Never ' )
' Never '
>>> print a.get ( ' Gender ' )
None

diet.has_key ( key )
Test for the presence of a key in the dictionary. Returns True, if the key is present in the dictionary, otherwise False.

>>> a= { ' Name ' : ' Zara ' , ' Age ' : 7 }
>>> a.has_key ( ' Age ' )
True
>>> a.has_key ( ' Gender ' )
False

diet.items ( )
Returns a list of dictionary’s key-value tuple pairs.

>>> a= { ' Name ' : ' Zara ' , ' Age ' : 7 } 
>>> a . items ( )
[ ( ' age ' , 7 ) , ( ' Name ' , ' Zara ' ) ]

diet.iteritems ( )
Returns an iterator over the dictionary’s key-value pairs.

>>> a= { ' Gender ' : ' Female ' , ' Age 1 : 7 , ' Hair color ' : None , ' Name ' : ' Zara ' } 
>>> for b in a . iteritems ( ) :
. . . print ' { 0 } - - - -{ 1 } ' . format ( b [ 0 ] , b [ 1 ] )
. . .
Gender - - - -Female 
Age - - - - 7 
Hair color- - - - None1
Name- - - - Zara

diet.iterkeys ( )
Returns an iterator over the dictionary’s keys.

>>> a= { 1 Gender 1 : ’ Female ' , ' Age ' : 7 , ' Hair color ' : None , ' Name ' : ' Zara ' }
>>> for b in a.iterkeys ( ) :
. . . print b
. . . 
Gender
Age 
Hair color 
Name

diet.itervalues ( )
Returns an iterator over the dictionary’s values.

>>> a= { 1 Gender ' : ' Female ' , ' Age ' : 7 , ' Hair color ' : None , ' Name ' : ' Zara ' }
>>> for b in a.itervalues ( ) :
. . . print b
. . .
Female
7
None
Zara

diet.keys ( )
Returns list of dictionary keys.

>>> a= { ' Name ' : ' Zara ' , ' Age ' : 7 }
>>> a . keys ( )
[ ' Age ' , ' Name ' ]

diet.pop ( key [ , default ] )
If key is.in the dictionary, remove it and return its value, else return default. If default is not given and key is not in the dictionary, a KeyError is raised.

>>> a= { ' Gender ' : ' Female ' , ' Age ' : 7 , ' Hair color ' : None , ' Name ' : ' Zara ' }
>>> a . pop ( ' Age ' , 15 )
7
>>> a . pop ( ' Age ' , 15 )
15 
>>> a
{ ' Gender ' : ' Female ' , ' Hair color ' : None , ' Name ' : ' Zara ' }

diet. popitem ( )
Remove and return an arbitrary key-value pair from the dictionary. If the dictionary is empty, calling popitem () raises an KeyError exception.

>>> a= { ' Gender ' : ' Female ' , ' Age ' : 7 , ' Hair color ' : None , ' Name ' : ' Zara ' } 
>>> a . popitem ( )
( ' Gender ' , ' Female ' )
>>> a . popitem ( )
( ' Age ' , 7 )
>>> a
{ ' Hair color ' : None , ' Name ' : ' Zara ' }

diet . setdefault ( key [ , default ] )
If key is in the dictionary, return its value. If not, insert key with a value of default and return default. The default defaults to None.

>>> a= { ' Name ' : ' Zara ' , ' Age ' : 7 }
>>> a . setdefault ( ' Age ' , 15 )
7
>>> a . setdefault ( ' Gender ' , ' Female ' )
' Female '
>>> a . setdefault ( ' Hair color ' )
>>> a
{ ' Gender ' : ' Female ' , ' Age ' : 7 , ' Hair color ' : None , ' Name ' : ' Zara ' }

diet.update ( [ other ] )
Update the dictionary with the key-value pairs from other, overwriting existing keys, and returns None. The method accepts either another dictionary object or an iterable of key-value pairs (as tuples or other iterables of length two). If keyword arguments are specified, the dictionary is then updated with those key-value pairs.

>>> dict1= { ' Name ' : ' Zara ' , ' Age ' : 7 }
>>> dict2= { ' Gender ' : ' female ' }
>>> dict1 . update ( dict2 )
>>> dict1 . update ( hair_color= ' black ' , eye_color= ' blue ' )
>>> dict1
{ ' eye_color ' : ' blue ' , ' Gender ' : ' female ' , ' Age ' : 7 , ' Name ' : ' Zara ' , ' hair_color ' : ' black ' }

diet . values ( )
Return list of dictionary values.

>>> a= { ' Name ' : ' Zara ' , ' Age ' : 7 }
>>> a . values ( )
[ 7, ' Zara ' ]

Python Programming – Dictionary Methods Read More »