You are on page 1of 17

PART.

D
ESSAY QUESTIONS WITH SOLUTIONS
1.1 PYTHON BASICS
Python? Explain the features of
Python language

a Simple inter•ctrve, interpreted obpct onentgd cornpted to gov.mrntr.g


programmmg
d is a very robust, elegant and a powerful language.
feøtgres d
Python
FollowsObject-oriented Programming Paradigm
pytB)n is an object-oriented programmjng language, ag it separates data from Jog;c. Moreover. python MAenfy
but also a proper combination of multiple programming
paradigms.
Easy to Learn
Veryfew keywords, simple structure and well defined
syntaxes possessed by Python mao it easy to Jean
Easily Readable
3.
Unlikeother programming languages, it does tikies acces•iog
make Of symbols like (S), sernjcoion
Rather, st defines a Simple and clear code. which •s
vüiablcs, defining code blocks and pattern matchinc
to read. Python language has been desrgned ew}y
in a way, that code written by one
'$&rstood by tbEother
EasilyMaintainable
python is simple unlike other prograrnming languages, n does rot require much difficulty for For
example, for the existence of its code, it does not depend on the presence or programmer at a company. The rood
importantadvantage of Python is that, at the time of reviewing a script wntten very 'mg time ago. the provarnrnet
require much guidance from a reference book.
5. UsesHigh-level Data Structure
has been designed tn a way, that the programrner does ntn need to look after the low level details merMjry
management.It supports high level data structures such as, realizable arrays (lists in Python), hash tables (dwt.gmary in
python). As these building blocks are defined in the core language, are extensrvely used ms reduces eve%vmeM
time, as well as the size of the code. Thereby, making the code more simpler to read.
Supports Extensibility
python allows the programmer to code some part ofthe program in different languages like, C, C++, java and utilize them
trough Python code.
1. Support Portability
Python is written in C, it can work on different platforms i.e., the Python applications built on one system, can
on my other system, with little or no modification. Any platform that contarns ANSI C compiler, supports Python. Python
is also independent of the type of architecture.
Robust
Python is more powerful in determining as well as handling error conditions, through software handlers. It guides the
progammer, by providing full details oferrors, in case ofprogram crashing due to errors. For example, the ICEationwtrre
ttE error has occurred in the codc, by specifying the filename, line number and function. It also allows the
to take an action for the elimination of the error.
exception handlers in Python are capable ofreducing debugging process, by simplifying the problem. redirecting the
progam flow, performing cleanup or maintenance measure, closing the application elegantly or just ignoring it. In cBe,
if errors could not be handled properly, Python generates a stack that displays the type and location of the error, in
additionto the location of module that contains the erroneous code.
9. Poses— the of a Memory Manager
all the functionalities related
of the main advantages of Python programminglanguageis that, it itself handles
This in turn reduces the overall development time
memory management. Thereby, reducing the programmers burden.
includes fewer bugs. It handles memory management through the use of interpreter.

ALL-IN-ONEJOURML FOR ENGINEERINGSTUDENTS SIA GROUP


1.6
10. Interpreted and (Byte) Compiled Language
Just like Java, Python is also an interpreted and a byte-
compiled language. That is, it allows the programmer to
run the program directly from the source code without
performing the compilation process;
The process followed by Python is,
(i) It just transforms the source code into an
intermediate form knov,n as, 'bye code'.
(it) Then translates the byte code into a machine code
(o's and I's)
(iii) And then run it.
The programmer need not have •to worry about the
program compilation, proper linkage and loading of
libraries etc.
11. Supports Scalability
The term 'scalability' here, refers to the capability of
the programming language, to accept and handle the
additional performance required, upon the addition of
new hardware to the system. Unlike other programming
languages. Python can expand the code size, by adding
new or existing Python elements and reusing the code
when required. This is possible because, Python has
pluggable and modular architecture.
12. Works as an Effective Rapid Prototyping Tool
Pythoo•provides several interfaces to other systems,
which makes it rx»werfuland robust enough to prototype
the entire systems within it, in a very less time,
The type holds Immutable Sequences
single literal The values of objects cannot They be sequentially
be changed using index values.
Lists Container
Mutable Sequences
type holds multiple
accessed
0b •ects. values of objects can be They can be seqtrntialty
changed usin index values
Tuples Container
Ibe type holds multiple Immutable Sequences
'Ibe values of objects cannot accessed
objects. They can be sequentially
be changed. using index values.
Pictionanes Container
Mutable Mappmg
type holds multiple pairs.
objects. The values of objects can They are hashed key-value
and
be changed. The elements are unordered
accessed wtth keys.
'IYpes
t:øsupported
python does not SUPPONstandard types like char
or byte. pointer. vnt versus short versus long. and float versus double
or Byte
python does not supports char or byte type
for holding the Single character or 8 bit integers
pointer
python can directly manage the memory
for the users. Therefore pointer addresses need not be accessed This is
possibleby referring objects identity through id().
versus long
iotversusshort
The plain integers in Python are 'standard' integer
type that fulfill the need of int, short and lonw
float Versus Double
Float in Python is similar to double in C. It
provides decimal floating point type available in decimal module. Floats ar
for estimates such as lengths, weights and measurements.

1.3 NUMBERS
Introduction to Numbers, Integers, Floating Point Real Numbers, Complex Numbers
scuss different types of numbers in python.
wer : 020

umbers

Numbers are of immutable type i.e., when the value of a number is changed a new object is allocated also
storage and direct access.

tingNumber
A number is created by assigning a value to a variable.
PYTHON PROG
1.16 RAMMING
4. Complex Number (JNTu
Syntax
var value A complex number
Example real number and imaginary is an
nurnl%frred Dao
aFloat •e2.3497 Syntax
Upd•ting a Number real + imagj
Existingnumber can be updated by reassigning a Here j •t imaginary
can be a different
variable to another number. Il)e new value number
number or related to previous value.
Example
Example 24.37j, 22 + 3.4j
aComplex aComplex + 2
'I .3.2 Operators,
Deleting a Number Bunt-in
Generally a number can not be deleted but, its usage can Q26:Zbescribe different
bc stopped. However, it can be explicitly deleted by using del by Python with antypes of o
example
statement once the variable name is removed, it is no longer Answer: for each.
used. In case, if it is used then it results an "NameError"
There are three different
exception. types of
by python. They are listed
Example below, operatotl
1. Arithmetic or
del aComplex numeric
2. Comparison operators
Number Types.
3. Boolean operators.
Python supports the following number types,
1. Arithmetic or Numeric
l. Plain integer Operators
The numeric type arithmetic
2. Long integer
by python are listed below, operators
3. Floating point real numbers ate
(i) Division (l; V)
4. Complex numbers.
(ii) Modulus (%)
1. Plain Integers
(iii) Exponentiation (**)
In Python, plain integers correspond to universal numeric
type. The range of integers is —2,147, 483, 698 to 2, 147, 483, (iv) Addition (binary (+)
operator)
647 i.e., -2" to 2 31- 1. (v) Subtraction (binary
(—)operator)
Example (vi) No change (Unary(+)
operator)
89, -- 169,-o x 43, 017, 0101 (vii) Negation (Unary (—)
operator).
2. Long Integer (i) Division(/, //)
Long integersare representedas (L) or (l). They are There are three different types
superset of integers and are used when the range of number of division
exceed —231range. (a) Classic division
Those can be expressed in octal, decimal or hexadecimal (b) True division (l)
notations. (c) Floor division (//).
Example (a) Classic Division
312L, 249L In the Classic Division Operation,the
quotientn
3. Floating Point Real Numbers obtained will have the same type as thatofthecp
Floating point real numbers are represented in straight involved. That is, if integer type operands
areimi
forward decimal or scientific notations. In decimal notation, then the classic division operationretumsan•
decimal point is used while in scientific notation, 'E' or 'e' is by truncating the fraction. Similarly,forfloating
used. operands, it returns the actual floatingpointqa
Positive or negative signs betweenthe "e" and the Example
exponentrepresentsthe sign of the exponent.If sign is not 25/2
present, then it refers positive exponent.
12
Example
>>> 25.0/2.0
1.28, -2.204e -i9
12.5
'
(0
' Division

Dis type
€søøple

200. poc
•ereaat•• or tot
rte.* tutore
asn
i2.s
as.0/2.o
ta.s

Division (Il)
smallest
rounded to the
IntheFloorDivision Operation, the fractions obtained in the quotient are always truncated and
on its immediate left on the number line.
wholenumber which is
Esgmple

Fie Shea
txsc bit
python 3.7.4 (tags/v3.1.4:e093S9i12e, cui e 2019,
on Win32
type "heip•, •copyright•, •czedizs• o: •license O • tor ure intonation.
2S//2
as.0//2.o
12.0

(i) Modulus(%)
Thecomputationof modulus is different for different numeric types.
+ The modulo of two integer numbers is the remainder of their integer division.
Example

170/03-2
+ The modulo oftwo floating point numbers is obtained using the following formula.

dividend
dividend— math.floor * divisor
divisor

+ The modulo of two complex numbers is obtained using the following formula.

dividend
dividend— math. floor real* divisor
divisor

Exponentiation
numeric type. The binding between the exponentiation operat
TheExponentiationOperation, determines the power ofa
andits left operand is more tighter than that with unary operators (+, —).Whereas, the binding between the exponentia
that with unary operators (+,
Operator and its right operand is less tighter than
JOURN8L FOR ENGINEERINGSTUDENTS
8LL-1N-ONE SIA GROUP
PYTHON PROGRAMMING
1.18 tJNTu
Example

S. 3.4 (NSC

Type or for •ore

binding VS th •e than
-32
•ore

•Right bsnaang *it.h tight ser than


•e
o.osns to negative
'Integer' cannaebe
0.03123

ValueError:integerto the negative power

list of all numeric arithmetic operators in the highest-to-lowest order of precedence is given below.
S.No. Operator Syntax Function

1. expl exp2 expl power exp2 (tighter binding to its


left)
2 + (unary) Keep sign of exp, unchanged

3. —(unary) —exp Negation of exp (or) change sign of exp


to
4. expl exp2 expl power exp2 (tighter binding to its
right)
5. expl • exp2 Multiply expl and exp2

6. expl/exp2 Divide expl by exp2. This division can


eitherbea
classic or a true division

7. expl // exp2 Divide expl by exp2. ms division can be


onlya

8. expl % exp2 Module of expl divided by exp2

9. +(binary) expl + exp2 Add expl and exp2•

10. —(binary) expl —exp2 Subtract expl and exp2

2. Comparison Operators
These operators compare only the data values of the participating objects. The comparisons performedarebased
sign and magnitude for numeric values, whereas a lexicography (i.e.,) alphabetical order is followed, in writing
strings. The comparisons result in either Boolean True or False values.
The list of standard type value comparison operators in highest-to-lowest precedence order is givenbelow,
Operator Syntax Determines whether
expl < exp2 expl is less than exp2

expl > exp2 expl is greater than exp2

expl< = exp2 • exp•l is less than or equal to exp2

expl > = exp2 expl is greater than or equal to exp2

expl = exp2 expl is equal to exp2

expl ! exp2 expl is not equal to exp2

Look for the SIA GROUP LOGO on •the TITLE COVER beforeyou buy
1 pytttor uoncos
1.19

a-on,
•i
True
t rue

true

several value comparison operators


companson operators will be performed can also be applied
such left-to-right. values within a single line. The evaluation

BJßtple

EM Debug Options
Window Help
python
t 2019,
"help", •copvnght•, €4 •
or
tor nor.
True

Operator
Boolean
Theseoperators negate or link two or more expressions.
Thelistof standard type boolean operators in highest to lowest precedence order is given below:
Operator Syntax
Determines
not not exp negation or logical NOT
of exp
and expl and exp2 conjunction or logical
AND of expl and exp2
or expl or exp2 disjunctionor logical OR
of expl and exp2

tumples

Shea
Debug Help
3 • 1.4 (HSC 64 •
on
type *hexp•, •credit'" or for intorn•eson.
n.n—s.S9,
03.02
True
not
True
(0<300)
True
(03.02) and (0>300)
true
nov€n O)

ULAN-ONEJOURNRL FOR ENGINEERINGSTUDENTS SIA GROUP


1.26 PYTHON
PROGRAMMING
Syntax
variable "'any-string-either-in-one-or-multiple-lines"'
Example
Python shen
Edit Shen Debug Options Window Help
Pvchon
Twe ••n.xp••. ••eopvsxgnc••,••oreoxc.•• or ••xxaen•.o•• toe
more
vs through repr O
•••oooa morn.ng:Hya•••
vtøhtthreuoh BEr
— •Geod morning 'Hya••

Python's triple quotes are generally helpful while writing a large block of HTML
or SQL.
Example
#HTML
strings
back =
Examf

Home Page
HI ! USER

<INPUT TYPE = button VALUE signout


ONCLICK= "login(
As
characters
there are n
#SQL String Op
cursor.execute("'
CREATE TABLE students(
2.
stud_name VARCHAR( 10), 3.
stud id INTEGER, 4.

marks INTEGER) 1. Form


Pytho
Syntax
3. String Immutability
Forma
Strings are immutable data types, restricting their values to be changed. That is a new stringobject Where
time a string is modified. This can be checked using the id( ) built-in function that returns 'identity' similarto Format
of an object.
The list
Example voc : c,
Python 3.7.4 Shen
File EdR Shen Debug Options Window Help
Python 3.7.4 crags/v3.7.4:e093S9212e, 2019, tusc v. 1926 64 bit • %d or %
Type "help", •czedat.•• or "hgenze O 'or more inter—anon. : cor
•ere •ccnteat'
%o : Con
•d ( sco
%x or 0/0*
•d (øcr) %e or %E
S0220976
•contenevrf eer • %g or %G
Moreover, individual characters or substrings of a string cannot be modified, doing so will resultinanarc %%:conv
SPECTRUM
Look for the SIA GROUP LOGO on the TITLE COVER beforeyoubuy gu-l
øøpje

However.such type Of errors can be avoided by


creating new strings from the extsung strtng and then assigmng these
backto the original strjng.
Esgmple

As strings are immutable Objects,the expressions on


the left hand side of the assignment operator (z) cannot have single
(ex.'
characters J) or substrings (ex., as a variable. Instead, it can only have an entire string object (ex., str). However,
thereareno restrictions for the expressions on the right hand side of
the assignment operator
StringOperators
fie string-only operators are operators that can be applied
only to string objects. They are,
1. Format operator (%)
2. String templates
3. Raw string operator (r/R)
4. Unicode string operator (u/U)
Format Operator (%)
python supports the string format operator (%) and all the formattingcodes
defined for C's printf( ) method.
Syntax
FormatString %(list_of_arguments_to_be_ converted)
Where,
Formatstring contains % codes, which are the format operator conversion symbols.
The list of format operator conversion symbols supported by Python is given below.
%C : Converts to a character
%r : Converts to a string through repr( )
%s : Converts to a string through str( )
%d or %i : Converts to a signed decimal integer
%u : Converts to an unsigned decimal integer
%o : Converts to an unsigned octal integer
%x or %x : Converts to an unsigned hexadecimal integer represented either in lower case or upper_case letters.
%e or %E: Converts to an exponential notation either in lower case 'e' or upper case 'E'
%for %F: Converts to a floating point real numbers.
%g or %G: Converts to a shorter form of%e (or %E%) and %f(or %F%)
%%: Converts to an unescaped % character.
SPECTRUM
GU-IN-ONE JOURNRL FOR ENGINEERINGSTUDENTS SIA GROUP
1.28 PYTHON PROGRAMMING
other symbols or format operator auxiliary directives that can be used along with conversion
0)
Its argument specifies the width or precision to be followed.

To perform left justification


(iii)
To specify positive numbers using + sign
(iv)
To introduce space padding for positive numbers.
(v)
To include the octal or hexadecimal leading zero, i.e., 'O' or Ox or OX, respectively.

To introduce zero padding in formatting numbers.


(vii)
To use the % literal
(viii) (var)
To specify mapping variable
(ix) m.n
To specify minimal total width (m) and number of digits (n) following the decimal point.
Example
Python 3.7.4 Shen
File Shen Debut Option' Window•Help
Python s. 7.4 ctaq./v3.7.4:e09359112e, e 2019. tusc v.29i6
rvpe •help". •eopynghc••. •credit••• or Zor mose
•209'
•2d9'

•OX2D9'

'OX2d9•

'QC"". 92585942
•SS. 92ses9'
'642 •'56.92ses942
•S6.92S8S9'
•"6.92ses942
•u •esc. 92525942
•s. 692se6E+01
'S6.92S9'

•you need to •core


•you need co score above60' •

scored id
'rose scored 90 marks'
ers and
Sequences
string Templates 1.29
provides string Templates using
into the string module, wh,ch.
the two methods string substituting is very
substitute( ) and much simplified. When the Template module
of the substitution and safe_substitutecan be used with templateobjects.
leaves the
substitution of missing
gomple
key as it is.

Fie Edi
python
(tag'/
Jul e 2019,
.tvpe •help s , tysc 7.1916 64 bit •
•copytxght•.
•eredit.• or
tot more
mathot SVhiChzcnth
has
•the month ot ,ho•any•• d"" •)
has 31 day" • •)
'I.SUb'titute
Traceback recent c.ii :
line 1, In
•substitute
(Which—onth•
•nareh•

return
•eit.pattetn.sub(convert,
seit.teqiate)

return
hoe
(nappingtnaedl)
ReyEtxor: •ho.any•
si.sate substitute
•the ot Hatch hag )
$ho•any days•

3. RawString Operator (r/R)


The raw string operator 'r' or 'R' is
used, to display the raw
characters suchas \n, etc. strings without performing any translation to special or non-

Syntax
r' any_string'
(or)
R'any_string'
Example

• txsc •
••eopvrafie• tor •ntor—eaen.

r•.ene
tErrno •ucb or
Pyc.bon\
S . •

4. UnicodeString Operator (u/U)


The Unicode String Operator 'u' or 'U' is used, to convert the standard strings or unicode character strings to a complete
string object.
l.micode
Example
u 'abc' U +0061 U + 0062 U + 0063
u '\u1234'U+ 1234
u +0061 U t 0062 U ± 0063 U + 1234U + 0012.
mcmam NL-IN-ONE JOURNAL FOR ENCINEERINQSTUDENTS SIA GROUP
It considers the NEWLINES as, the
—ving the NEWLINES. delimiter and
splits the
string accordingly.
string.title( ) It returns the resulting list ofeach line, by
the 'titlecased' version
of string
the words
in the string begin
string.startswith(obj, begin with uppercase and are followed by all
35. It returns 0, end
'True'. if the string or len(string))
tuple, it checks. whether the its substring
string starts (identified by
with any or begin and end indices)
the strings in starts Withstring 'obj'. If 'obj• is a
36. that tuple.
It the case ('fall the letters
in string, i.e.,
it converts uppercase
31. letters to lower case and lower
adds zeros as the left Padding letters to upper case.
to the string,
in order to
obtain a total of width number of characters. It is specially used
string.translate(str,del „
38.
It translates the string as
per the
translation table
and deletes those
strings included in the 'der string.
1.4.2 Lists and
Q34e-ExpIainin detail about lists. Tuples
Answer : Lists
List is like a string, which
provides
elementsof list. The unique and flexible sequential storage mechanism.
characteristics of Through slices, we can access any ntmberofconsecutive
(i) List can contain different that, differentiate them from
types of Python strings and arrays are,
At any given time, single or multiple objects-standard types, objects and user-defined objects.
objects can be inserted,
(iii) List can grow and shrink. removed and updated to the list.
(iv) List can eyen be sorted, reversed,
empty and populated.
(v) A list can be added/removed to/from
other lists.
(vi) Creatinga list is also very simple.
(vii) Individual or multiple elements of a
list can be easily added, updated
or removed.
Creatingand Assigning Lists
Creating list is simple and similar
as assigning a value to a variable.
be created, as 'empty' or with elements. The List is created by an assignment operator. A list can
elements of a list are enclosed in a square
usingthe factory function namely list( ). bracket ([ J). A list can also be created
Example
Python
File Edit Deb. Options Window Help
Python 3.7,4 (taga/v3.7.4:e09359ii2e,Jul S
2029, cysc v.1916 64 bit
(AMD") 1 on Win32
Type "heib% •copynght•, "credit'" or "license()"tot
more
Ll—tJ
(12)

L2•t11, t'vv•,
pnnt (L2)
•t•vv', 'dd'J, 3.5)
list (•sure')

ALL-IN-ONE JOURNAL FOR ENGINEERINGSTUDENTS


SPECTRUM SIA GROUP
Accessing Values in a List
An element of a list is accessed using the slice operator J) along with the index or indexes.
Python 3.74 Shea

Fie 9teN Debug Options Wmdow


Python 3.7.4 Oui e 2019, 9.1916
on Win32
type "heip•, •copyright", •credit"' ot •license tor •ore intoaation.
'tue% '*ed')

•wed'
Lito:2J
t •nn% •cue')

Updating Elements to a List


A list is updating using the slice operator along with the .index on the left-hand side of the assignment

Alt0)c'xxx'

('al', 'bi t), 3.521

New elements can be added to a list using the append( ) method.

S» pl.append( id')

pi

Removing Elements of a List


An element of a list can be deleted, using either the del statement if the index of the elementis
method, which takes the value of the element as an argument. The entire list can also be removedusing
Python 3.74
"e o Wmdow Help
3.1.4 (z.g•/v3.7.4te093S9N2e, e 2019. txsc
on
type •eopyzighe•, or •rseen•e O • 'tor nose •otorøva•n•

Odel•ce•entire
esas'cs, Numbers
and Sequences
1.37
1.5 MAPPING
AND SET TYPES
Whatare dictionaries? Explain with
examples.

picn00 ModelPaper-I,Q3(b)
Dictionariesrefer to python's mapping
type. are
entry is key : value. Keys correspond
python object. to any python similar to mssociativearrays, or hashes in perl. The syntax of a
arbitrary Dictionaries are type and it is usually
numbers or strings. Whereas, values correspond
enclosed by curly
Dictionariesare created by simply
assigning a dictionary
or not. The syntax is as follows.
elements to a variable, without considering whether dictionary contains

: 'CYR' , 'port'
:100}
dicta, dittb
('nee': 'Jack', ipo:t•:
100))

As shown in the example, dictionary


consists of keys and
bya colon(:), the items are separated by their corresponding values. Each key is separated from its value
commas and the whole
thing is enclosed in curly braces. In version 2.2, factory function

{dict

The fromkeys( ) method, creates


a new dictionary with the given keys, each with a default corresponding value of none.

ddict

edict—I}
(' , 'bar'))
edict
('too': Jone, 'bat': None)

AccessingValues from Dictionaries


User can access the values of the dictionary by using unique
keys.
>>>dictb = ('name' : 'Ramana', 'Port' : 90)

>>>for key in dictb.keys( y:


print 'key = %s, value = %s'% (key, dictb[keyl)
key name, value Ramana
key = port, value 90.
In version 2.2. the function keys( is not used to retrievea list of keys. Sequence objects like, dictionaries and
files are
simplyaccessed by creating iterators.
The dictionary name itself creates an iterator over the dictionary,which is to be used in for loop.
>>>dictb {'name' : 'Ramana', 'port' : 90}

>>>for key in dictb :


print 'key = %s' %(key, dictb[key])
key = name, value = Ramana
key port, value = 90.
SPECTRUMRLL-IN-ONE JOURML FOR ENGINEERING STUDENTS SIA GROUP
PYTHON PROGRAMMING
Along key, be dictionary

00

running 90,
tv dieuonacy two items, The keys dictb ore 'onme' and •port'
onci'90' and Its
if through Key is not in the dictionary, then e
rror occurs.
Whichi'

tine).
: Sni
in the jibove example. key 'SOC ih not present in the dictionary 'dictb', Ilence error
key( ) jnethod, which whether has key or not.
and not in operators ore boolean. that i", they return true it' key exists in the dictionary
otherwjsc returns

in diet // or key('nojnc')

•Ratnnna'
•rhe 10110wingexample shows the key os combination of numbers and strings.

»•>djeic121 •s 'Shiva'

*diete14.91'abc'

{4.9 : 'abc'. 2 : 'Shiva', '2' : 4.567)


If user knows all kcy_value pairs in advance. then user can add all the data items
simultaneously, instead
dictc {4.9 : 2 : 'Shiva'. '2' .•'4.567}
Updating Dictionaries
User can update a dictionary. by adding a new key_value pair, modifying an
already existing key_value
an existing key_value pair. pairor
I• // adding new key_value
'Shiva' t/ updating existing key_value
'port') •a" 99tt updating existing key_value

'host is running on port %(pOrt)d' %dict2 host Shiva is running


on port 99,
If the key added already exists then the old value will be
replaced by its new value.
Removing Dictionaries and Elements of Dictionaries
Users can delete the elements of the dictionary. or an entire
•dictionary can be removed
dictionary, using del statement.The entirecone:
using clear statement as follows,
del dictb( iname'l // Delete entry with key 'name'
dictb.clear() Delete the entire contents of dict b
del dictb Delete entire dictionary
dictb.pop('name') // Delete and return entry w/key
on Basics, Numbers and Sequences 1.39
type operators of dictionaries.
piscussvarious What are dictionary keys.

operatorsof dictionaries are classified into two operators.


namely standard type operators and mapping type
Type Operators
stgødgrd
ndard type operators Of dictionaries are comparison operators including than less than
to less than greater
IV Stagreaterthan equal (> ) etc.
Vito (

:rue

true

Mapping Type Operators


Thereare two different types of mapping type operators, they are,
(i) DictionaryKey-Lookup Operator (l l)
The key-lookUPoperator is specific to dictionaries.
It similar to that of single element slice operator for sequence
types. The index offset is passed as an argument
to sequence types for accessing single element of it. And in case
of dictionary the lookups are by key. "Iherefore
it is not an index rather it is considered as argument. The lookup
operator can assign as well as retrieve the values from dictionary.
(ii) (key) Membership (in, not in)
The membership can be checked by using the in and not in operators.
10 d3
Fulge

Eaiae

DictionaryKeys
Thedictionary values does not have restrictions imposed on them. Any python object ranging from standard objects to user
Objectscan be dictionary value. But its not same for dictionary keys. The properties of dictionary keys are as follows,
&fined
Morethan one entry per key not allowed one major constraint is for each dictionary key only one value is allowed rather
thanmultiple values for same key. If there are any key collisions, the assignment that is done at last will be fixed.
3.7A
•Debug
Python 3.7.' cysc v.
Peopyzaqht•,•credit'"or O• ere

I •nexxø•: •abe•i
dit

Pythonwill not check for any key collisions because it needs memory •forall the key-value pain
2. Keysmust be hashable
The python objects can be used as keys and they must be hashable objects. The mutable types like lists and dictionaries
are supported by Python because they cannot be hashed. All the immutable types can be used as keys because they are
hashable. Certain mutable objects are hashable and they can be used as keys.
The key need to be hashable. The hash function that is used by interpreterfor computing the iocation to store the data
dependsupon key value. The value is modifiable when key is mutable object. The hash function can map to a different
locationif the key is modified. Therefore, the hash function can never reliably store or retrieve the associated value. The
hashable keys can be selected because their values cannot be modified.
RLL-IN-ONE JOURN8L FOR ENGINEERING STUDENTS
SPECTRUM SIA GROUP

You might also like