Download as pdf or txt
Download as pdf or txt
You are on page 1of 230

See discussions, stats, and author profiles for this publication at: https://www.researchgate.

net/publication/337414937

Python with Spyder: An Experiential Learning Perspective

Book · November 2019

CITATION READS

1 8,434

2 authors:

Poornima Naik Kavita Oza


CHHATRAPATI SHAHU INSTITUTE OF BUSINESS EDUCATION AND RESEARCH Shivaji University, Kolhapur
124 PUBLICATIONS   124 CITATIONS    85 PUBLICATIONS   136 CITATIONS   

SEE PROFILE SEE PROFILE

Some of the authors of this publication are also working on these related projects:

Soft Computing Model for Secure Auto Program Evaluator View project

Virtual Digital Library of Department of Computer Studies, CSIBER, Kolhapur View project

All content following this page was uploaded by Poornima Naik on 21 November 2019.

The user has requested enhancement of the downloaded file.


This book aims at providing fundamental concepts of Python
programming. It is a good text book as well as reference book. Here concepts
are presented in the form of programs making it quite easy and simple for

Python with Spyder Dr. Poornima G. Naik & Dr. Kavita.S.Oza


students to understand. It showcases actual screen shots of the programs
from the programming environment to make it more student friendly.
Because of the user friendly interface provided in the book a novice learner
can also learn Python programming without any difficulty. As Python is open
source, programs written in this book can execute on different operating
systems like Windows, Linux, and Mac etc.
Topics covered in this book Python Language Basics, Python Collections-
Compound Data Types, List, Tuple, Dictionary and Set, Setting up
Development Environment, Introduction to Anaconda and Installation of
Anaconda. All the concepts are explained with practical examples and
screenshots of the same are embedded.

Dr. Poornima G. Naik


pgnaik@siberindia.edu.in
Python
Dr. Kavita.S.Oza with Spyder
An Experiential Learning Perspective

ACADEMIC
ISBN 978-81-943858-1-3
Dr. Poornima G. Naik
www.shashwatpublication.com Dr. Kavita.S.Oza
9 788194 385813 >
contact.shashwatpublication@gmail.com
Python with Spyder: An Experiential
Learning Perspective

i
© Copyright, 2019, Authors
All rights reserved. No part of this publication may be reproduced or transmitted in any form or by any means, electronic or
mechanical, including photocopy recording, or any information storage or retrieval system, without permission in writing from
the publisher.

The opinions/ contents expressed in this book are solely of the author and do not represent the opinions/ standings/ thoughts of
Publications Name. No responsibility or liability is assumed by the publisher for any injury damage or financial loss sustained to
persons or property form the use of the information, personal or otherwise, either directly or indirectly. While every effort has
been made to ensure reliability and accuracy of the information within, all liability, negligence or otherwise, form any use ,
misuses or abuse of the operation of any methods, strategies, instructions or ideas contained in the material herein is the sole
responsibility of the reader. Any copyrights not held by publisher are owned by their respective authors. All information is
generalized, presented informational purposes only and presented “as is” without warranty or guarantee of any kind.

All trademarks and brands referred to in this book are for illustrative purposes only, are the property of their respective owners
and not affiliated with this publication in any way. Any trademarks are being used without permission and the publication of the
trademark is not authorized by associated with or sponsored by the trade mark owner.

ISBN: 978-81-943858-1-3

Price: 200.00
Publishing Year 2019

Published and Printed by:


Shashwat Publication
Office Address: Ram Das ,
Bilaspur, Chhattisgarh – 495001
Phones: +91 999368164 +91 9993603865
Email: contact.shashwatpublication@gmail.com
Website: www.shashwatpublication.com

Print in India

ii
Python with Spyder: An Experiential
Learning Perspective

By

Dr. Poornima G. Naik


Dr. Kavita S. Oza

iii
Acknowledgements
Many individuals share credit for this book’s preparation. We extend our sincere thanks
to Late Prof. A. D. Shinde, the Founder Director and Managing Trustee who has been a constant
source of inspiration for us throughout our career. His support is really a driving force for us.
Also, we would like to thank Dr. R. A. Shinde, Hon’ble Secretary, SIBER for his whole hearted
support and continuous encouragement. We take this opportunity to thank Dr. V. M. Hilage,
Trustee Member, SIBER Trust, Dr. R. V. Kulkarni, H.O.D., Department of Computer Studies for
showing a keen interest in the matter of this book and extending all support facilities for the in-
timely completion of this book. The material covered in this book is a systematic effort taken
towards solving the various queries which we received from our students time to time, during our
20+ years tenure of teaching various programming languages at PG level. Last but not the least
we thank all faculty members and non-teaching staff of department of computer studies,
CSIBER, Kolhapur and department of Computer Science, Shivaji University, Kolhapur who
have made contribution to this book either directly or indirectly.

Dr. Poornima .G. Naik


Dr. Kavita. S. Oza

iv
Preface
The altruistic revolution evidenced by the Computer Science arena is the Free Open
Source Software (FOSS) movement which is now encompassing the entire scholastics world
never than ever before. The free licensing and more than that the openness has attracted many
software professionals and there is seemingly an absolute migration of the computer science
fraternity from its proprietary counterpart.

However inspite of the benefits paved by the FOSS such as security, stability, reliability,
stability and cost effectiveness, there are not many guiding sources for opening oneself as a
programmer in this exciting part of the realm. Undoubtedly ‘Python’, has emerged as the widely
accepted programming platform. Most of the UG / PG students are not that familiar with Python
platform. But as per the new curriculum, Python programming is an important component
introduced.

This book aims at providing fundamental concepts of Python programming. It is a good


text book as well as reference book. Here concepts are presented in the form of programs making
it quite easy and simple for students to understand. It showcases actual screen shots of the
programs from the programming environment to make it more student friendly. Because of the
user friendly interface provided in the book a novice learner can also learn Python programming
without any difficulty. As Python is open source, programs written in this book can execute on
different operating systems like Windows, Linux, and Mac etc.

Topics covered in this book Python Language Basics, Python Collections- Compound
Data Types, List, Tuple, Dictionary and Set, Setting up Development Environment, Introduction
to Anaconda and Installation of Anaconda. All the concepts are explained with practical
examples and screenshots of the same are embedded.

v
Contents

Chapter Page No.


1. Python Language Basics 1
1.1 Salient Features of Python Language 1
1.2 Comments in Python 1
1.2.1 Single Line Comments in Python 2
1.2.2 Multi Line Comments in Python 2
1.3 Python Data Types and Variables 3
1.4 Primitive Data Types in Python 4
1.5 Checking the Type of the Variable 6
1.6 Checking Variable’s Data Type – isinstance() Function 7
1.7 Deleting a Variable in Python 8
1.8 Python Numbers 9
1.9 Strings in Python Strings in Python Strings in Python Strings in 10
Python Strings in Python
1.10 12
1.11 Raw String in Python 13
1.12 Repetition Operator - * 14
1.13 Index Operator in Python 14
1.14 Bounds Checking for String 16
1.15 Slicing Operator in Python 16
1.16 Compact Method for Reversing a String 20
1.17 Complex Data Type 21
1.18 Determining Size of Variables in Python 23
1.19 Boolean Data Type in Python 28
1.20 Conversion Between Python Data Types 30
1.20.1 Implicit Type Conversion (Widening of Conversion) 30
1.20.2 Explicit Type Conversion 31
1.21 Python I/O Processing 32
1.21.1 Accepting Input From User Interactively – input() 32
Function
1.21.2 Formatted Output 33
1.21.3 Generating Output on the Same Line 35
1.22 Initializing Variables in Python 36
1.22.1 Assigning Value to Multiple Variables in a 36
Single Statement
1.22.2 Assigning Multiple Values to Multiple Variables 36
in a Single Statement
1.23 None – A Special Data Type 39
1.24 Logical Grouping – Indentation 39
vi
2. Python Collections- Compound Data Types 40
2.1 List in Python 40
2.1.1 Creating List in Python 40
2.1.2 Creating a List Using List Constructor 43
2.1.3 List is Ordered 44
2.1.4 comp() Method 45
2.1.5 List Concatenation 46
2.1.6 Repeating the Elements of the List - * Operator 49
2.1.7 Memory Organization for List 50
2.1.8 Accessing the Elements of a List 50
2.1.9 IndexError in List 51
2.1.10 Accessing Multiple Contiguous Elements from a List 52
2.1.11 Slicing Operator 52
2.1.12 Changing Multiple Elements of a List Using Slicing 56
Operator
2.1.13 Checking the Existence of the Element in the List – 58
Testing List Membership
2.1.14 Determining Size of the List 60
2.1.15 Operations on List 60
2.1.16 Using range() Function for Creating a List 64
2.1.17 Deleting Elements of a List – del() Method 65
2.1.18 Difference Between del l[:] and del l 67
2.1.19 Deleting the Element Using pop() Method 69
2.1.20 Deleting All Elements From the List – clear() Method 69
2.1.21 Removing the Specified Item From the List – remove() 71
Method
2.1.22 Removing Multiple Elements From the List Using 72
Iterator
2.1.23 Cloning a List in Python 76
2.1.24 Testing Object Equivalence Using ‘is’ operator 78
2.1.25 Sorting the List – sort() Method 79
2.1.26 Bi-directional Sorting Using sorted() Method 80
2.1.27 Reversing the Elements of the List – reverse() method 81
2.1.28 Counting the No. of Elements in a List with a Specified 82
Value – count() Method
2.1.29 To Find the Index of the Element in the List – index() 83
Method
2.1.30 List Comprehension 84
2.1.31 Nested List Comprehension 89
2.1.31.1 Case 1: Finding transpose of a matrix without 89
list comprehension.
2.1.31.2 Case 2: Using Single List Comprehension 91

vii
2.1.31.3 Case 3: Using Nested List Comprehension 92
2.1.32 Nested Lists in Python 93
2.1.33 Membership Testing in Nested Lists 96
2.1.34 Converting An Iterable to a List 97
2.1.35 Finding the Smallest and Largest Element in a List 98
2.1.36 Miscellaneous In-Built List Functions in Python 98
2.1.37 Implementation of AND Logic Using all() 98
2.1.38 Implementation of OR Logic Using any() 100
2.1.39 enumerate() Method 102
2.1.40 Using List as Stack 102
2.1.41 List is Not Efficient Queue Data Structure 104
2.2 Tuple in Python 104
2.2.1 Creating Tuple in Python 105
2.2.1.1 Creating Tuple Using Tuple Class Constructor 106
2.2.1.2 Creating a Tuple With a Single Element 107
2.2.2 Tuple Packing 108
2.2.3 Tuple Unpacking 111
2.2.4 Combining Tuple Packing and Unpacking 113
2.2.5 Repeating the Elements of the Tuple - * Operator 114
2.2.6 Iterating Through Elements of a Tuple 115
2.2.7 Tuple is Hashable 116
2.2.8 Accessing the Elements of a Tuple 118
2.2.9 Negative Step Value 119
2.2.10 Index Error in Tuple 121
2.2.11 Determining Size of Tuple 122
2.2.12 Testing Tuple Membership 122
2.2.13 Tuple is Ordered 123
2.2.14 Testing Equality Using is Operator 124
2.2.15 Operations on Tuple 127
2.2.16 Functions Common to List and Tuple 127
2.2.17 List Functionality which is not applicable to Tuple 128
2.2.18 Additional Functionality Not Supported By List 128
2.2.19 Tuple Concatenation 129
2.2.20 Deleting a Tuple in Python 132
2.2.21 Nested Tuples 135
2.2.22 Converting An Iterable to a Tuple 139
2.2.23 Aggregate Functions Applicable to Tuple 139
2.2.24 A Note on Choice of Proper Data Structure (a list or a 140
tuple?)
2.3 Python Dictionary 140
2.3.1 Creating Dictionary 141
2.3.1.1 Creating Empty Dictionary 141

viii
2.3.1.2 Creating Non-empty Dictionary 141
2.3.1.3 Creating Dictionary Using dict class 143
Constructor
2.3.1.4 Creating Dictionary from a List 144
2.3.1.5 Creating a Dictionary Using fromkeys() Method 145
of dict Class
2.3.2 Looking Up Dictionary – KeyError 146
2.3.3 Checking the Existence of a Key Using has_key() 148
Method of dict class
2.3.4 setdefault() Method of dict class 149
2.3.5 Retrieving List of Keys and Values 150
2.3.6 Three Distinct Methods for Printing Key-Value Pairs of a 153
Dictionary
2.3.6.1Method 1: By iterating over keys 153
2.3.6.2 Method 2: By iterating over values 153
2.3.6.3 Method 3: By iterating over items 154
2.3.7 Formatted Printing 155
2.3.8 Python Dictionary Comprehension 156
2.3.9 Modifying a Dictionary 157
2.3.10 Deleting Elements From a Dictionary 158
2.3.11 Membership Testing in a Dictionary 158
2.3.12 Concatenation of Two Dictionaries – update() Method 159
of dict class
2.3.13 list() Method 160
2.4 Set in Python 161
2.4.1 Creating Set in Python 161
2.4.1.1 Creating Empty Set 162
2.4.1.2 Creating Non-Empty Set 162
2.4.2 Nesting of Set Elements 165
2.4.3 Set Elements are Immutable 165
2.4.4 Creating a Set Using Set Constructor 166
2.4.5 Using range() Function for Constructing a List 168
2.4.6 Set Does Not Support Duplicate Elements 168
2.4.7 Set Does Not Support Duplicate Elements 169
2.4.8 Repetition Operator - * 170
2.4.9 Concatenation Operator 170
2.4.10 Indexing 171
2.4.11 Testing Set Membership Using ‘in’ Operator 172
2.4.12 Determining Size of a Set 173
2.4.13 Iterating through the Elements of a Set Using for Loop 174
2.4.14 Sorting and Reversing a Set 174
2.4.15 Checking Set Equality Using ‘is’ and == operators 176

ix
2.4.16 Operations on sets 177
2.4.16.1 Adding Element to a Set 177
2.4.16.2 Deleting an Element From a Set – remove() 181
and discard() Methods
2.4.17 Difference Between remove() and discard() method 182
2.4.18 Removing An Element From a Set Using pop() Method 183
2.4.19 Deleting All Elements of a Set – clear() Method 184
2.4.20 Deleting a Set – del Operator 185
2.4.21 Deep Copying Using copy() Method 186
2.4.22 Converting An Iterable to a Set 188
2.4.23 Aggregate Functions 189
2.4.24 Set Operations 181
2.4.24.1 Union Operation 181
2.4.24.2 Intersection Operation 182
2.4.24.3 Set Difference 184
2.4.24.4 Set Symmetric Difference 185
2.4.25 difference_update Method of set Class 186
2.4.26 intersection_update Method of set Class 189
2.4.27 Symmetric_difference_update Method of set Class 190
2.4.28 isdisjoint() Method of set Class 192
2.4.29 issubset() asnd issuperset() Method of set Class 194
2.4.30 Python Frozen Set 205
2.4.31 Conversion Between Collections in Python 197
2.4.32 Converting a List to a String 198
2.4.32.1 Converting a List to a Tuple 200
2.4.32.2 Converting List to a Dictionary 200
2.4.32.3 Converting List to a Set 202
2.4.32.4 Converting tuple to Other Collection Types 202
2.4.33 Salient Features of Collection Types: 214
3. Setting Up Development Environment 206
3.1 Introduction to Anaconda 206
3.2 Installation of Anaconda 206
3.3 Working with Anaconda in Off-line Mode 214
3.4 Environment in Anaconda 215
3.5 Creating Environment in Anaconda 215
3.6 Activating Environment in Anaconda 216
3.7 Deleting Environment in Anaconda 217
3.8 Exporting Environment in Anaconda 217
3.9 Importing Environment in Anaconda 217
3.10 Launching Anaconda Navigator 217
3.11 Installing Spyder from Command-Line. 219
3.12 Spyder Toolbar 220

x
3.13 Writing Python Program in Spyder 221

xi
Chapter 1
Python Language Basics
1.1 Salient Features of Python Language
1. Python is free and open source for which source code is available.
2. Unlike C and C++ which are compiled languages, Python is an interpreted language.
3. Python uses indentation for specifying the scope which signifies the grouping of
statements.
4. Unlike the programming languages such as C, C++ and Java, Python is a dynamically
typed language which means you do not have to declare the type of the variable before
using it. The variable’s type is resolved dynamically at runtime based on the value
assigned to it which makes Python a type infer language.
5. Python is cross-platform which implies it is portable on different operating systems such
as windows, linux, mac etc.
6. Python variables are case-sensitive.
7. In Python, every variable is an object and every Python object is internally implemented
as a C structure. Hence in essence, Python variable is a pointer to a C structure.
8. In Python, Strings are immutable which means once created a string cannot be modified
without re-creating it.
9. Python interprets a number without any prefix to be a decimal number. Different strings
can be prepended to a number in order to specify a base other than 10.
10. Using the variable in an expression without initializing it will generate error.

1.2 Comments in Python


Well documented programs improve the readability and aid in quick bug fixing. To facilitate this
similar to other programming languages Python supports single and multi-line comments.
Comments are abundantly used for specifying any pre-conditions, assumptions, meaning of
variables, purpose of code block etc.

1
1.2.1 Single Line Comments in Python
Any line beginning with the character ‘#’ is treated as a comment in Python as illustrated in the
following code segment:

On execution of the above code snippet, the following output is generated:

1.2.2 Multi Line Comments in Python


For specifying comments that span multiple lines use triple single or double quotes at the
beginning and end of text block to be commented as demonstrated in the following code snippet:

On execution of the above code snippet, the following output is generated:

2
Using triple single quotes achieves the same as shown below:

1.3 Python Data Types and Variables


Variable is a name used to refer to a base memory location. Every variable in Python has a
specific data type based on the value assigned to it. Since everything evaluates to an object in
Python, a data type maps to a class and a variable to an instance of a class. The feature which
distinguishes Python variable from a variable in any other programming language is that,
variable in Python has type but there is no size limitation. A variable can grow in size
indefinitely limited only by the physical memory of the system.

Python variables are case-sensitive. In the following program, ‘lang’ and ‘Lang’ are treated as
two distinct variables.
3
On execution of the above code snippet, the following output is generated:

1.4 Primitive Data Types in Python


Python3 supports 3 basic data types

 Numeric
 String
 Boolean

Floating point numbers are stored with a precision of 16 decimal places. Excess digits, if any are
stripped off as shown in the following program:

4
On execution of the above code snippet, the following output is generated:

From the output generated on execution of the above code segment it is observed that the
variable f is truncated up to 16 decimal places.

Unlike the programming languages such as C, C++ and Java, Python is a dynamically typed
language which means you do not have to declare the type of the variable before using it. The
variable’s type is resolved dynamically at runtime based on the value assigned to it which makes
Python a type infer language. The side effect is that the same variable may attain different data
types if a different value is assigned to it as demonstrated in the following code snippet:

In statement (8) the variable ‘var’ is initialized with a value 10 which is later re-initialized in
statement (10) with a string value. On execution of the above code snippet, the following output
is generated:

5
As is evident from the output generated on execution of the above code, the type of the variable
var has been changed from int to str on re-initialization.

Python does not automatically assign default values to variables. Using the variable in an
expression without initializing it will generate NameError as demonstrated in the following code
segment:

On execution of the above code snippet, NameError is generated as shown below:

1.5 Checking the Type of the Variable


Python supports a function type() for checking the type of the variable passed to it as
demonstrated in the following code segment:

6
The above program creates the four variables, i, f, s and c initialized with integer, floating point
value, string value and a complex no, respectively. type() function is used for determining the
type of the variable. On execution of the above code snippet, the following output is generated:

As is evident from the output generated on execution of the program, i, f, s and c are instances of
int, float, str and complex classes, respectively.

1.6 Checking Variable’s Data Type – isinstance() Function


isinstance() function can be used for checking whether the variable belongs to a particular class
as demonstrated in the following code segment:

7
In statement (8), the variable i is initialized with a value 10. Hence i is an instance of class int,
hence the argument to a first print function evaluates to True whereas second print function’s
argument evaluates to False. On execution of the above code snippet, the following output is
generated:

1.7 Deleting a Variable in Python


Since everything in Python is an object, a variable can be deleted by deleting a reference to the
object using del operator. In the following program, i is a reference to a number object. del
operator can be used to delete i and attempting to refer to i after it is deleted will generate
NameError as shown in the output generated on execution of the program:

On execution of the above code snippet, NameError is generated as shown below:

1.8 Python Numbers


Prior to Python 3, there were four in-built numeric types:

8
 int
 long
 float
 complex

where int was automatically converted into long when overflow occurred. However, long type
has been eliminated in Python 3, and there is absolutely no limit on the size of the integer. In the
evaluation of arithmetic expression, the numbers are automatically upcast in the order

int → float → complex

Python interprets a number without any prefix to be a decimal number. Different strings can be
prepended to a number in order to specify a base other than 10 as depicted in the following table:

Prefix Number System


0b or 0B Binary
0o or 0O Octal
0x or 0X Hexadecimal

The following Python program displays a number 11 using different base values.

On execution of the above code snippet, the following output is generated:

1.9 Strings in Python

9
A string type in Python is referred to as ‘str’. Like C, string in Python is a sequence of characters
starting with index 0. A string can be enclosed within single, double or triple quotes. When you
want to create a string spanning multiple lines use triple quotes as demonstrated in the following
code snippet:

On execution of the above code snippet, the following output is generated:

10
1.10 Using Escape Characters in Strings
Every escape character used in a string has a specific action to perform. The following table
depicts commonly used escape characters in a string:

Escape Character Description


\r It is referred to as carriage return which moves cursor to the
beginning of the line.
\n It is referred to as new line control character which starts display
on a new line
\b It is referred to as backspace control character which moves the
cursor one character in the backward direction.
\t It is referred to as horizontal tab escape character which places
spaces between strings

The following Python program demonstrates the use of escape characters in strings. In the first
print statement when the escape character ‘\r’ is encountered, the cursor is moved to the
beginning of the line before displaying the string “Python”. In the second print statement, on
encountering three escape characters ‘\b’, the cursor is moved in the backward direction by three
characters and the string “MCA Program” is displayed from the current cursor position. Finally,
in the third print statement four blank spaces are inserted between the strings “Python” and
“Programming”.

On execution of the above code snippet, the following output is generated:

11
1.11 Raw String in Python
Raw string is generated by appending the character ‘r’ to the string which signifies not to
interpret any escape characters as demonstrated in the following code snippet:

In the above program, all the strings are appended with the character ‘r’ to suppress the
interpretation of escape characters. On execution of the above code snippet, the following output
is generated:

12
1.12 Repetition Operator - *
The operator * is referred to as repetition operator which repeats the string a specified no. of
times. In the following program, the string str is repeated 5 times using * operator which is
passed as an argument to print() function for displaying the same.

On execution of the above code snippet, the following output is generated:

1.13 Index Operator in Python


The characters of a string can be accessed using index operator denoted by [] with 0 and n-1 as
the lower and upper limits of index where n is the length of a string. Python also supports
negative indexing which is used to access the element by traversing in the reverse direction. The
following table depicts the positive and negative indexing mechanisms applicable to Python
strings.

P Y T H O N
0 1 2 3 4 5
-6 -5 -4 -3 -2 -1

With negative indexing the lower and upper limits are -1 and –n, respectively where n is the
length of the string.

The relationship between two indexing mechanisms is

x[ i ] = x[ i – n ]

Hence the element at the position 4 is the same as the element at the position (4 – 6) i.e.

-2.

The following Python program uses positive and negative indexing mechanisms for retrieving
the character at the beginning and end of a string “Python”.
13
On execution of the above code snippet, the following output is generated:

1.14 Bounds Checking for String


Python performs a strict bounds checking on a string. Trying to access character beyond limits
will generate IndexError as shown in the following code segment:

In the above program, the index of the last character of a string “Python” is 5, hence attempting
to access an element at index 6 will generate IndexError. On execution of the above code
snippet, the following output is generated:

14
1.15 Slicing Operator in Python
For selecting multiple contiguous characters from a string, a slicing operator denoted by : can be
employed.

For accessing the elements from index ‘s’ to ‘e-1’ use the following syntax:

x[s:e]

where s is the start index and e-1 is the last index of the retrieved element.

The syntax for accessing multiple contiguous elements from the list is depicted in the following
table:

For This Do This Remark


Accessing the characters from x[s:e+1] The index (e+1) is excluded
index s to index e
Accessing the characters from x[s:] Since end index is not specified, all the
index s to last element of string charactes upto last charactes are retrieved.
Accessing the characters from x[:e+1] Since start index is not specified, the
beginning to index e characters are retrieved starting with first
character and since the end index is
excluded, the characters upto index e are
retrieved
Accessing the whole string x[:] Since both start and end index are not
specified, all the characters of a string are
retrieved.

Example:
Consider the following string with the corresponding positive and negative indexing of
characters:

D A T A S C I E N C E
15
0 1 2 3 4 5 6 7 8 9 10
-11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1

The following table depicts various scenarios of retrieving multiple contiguous characters
employing the syntax presented above.

Example Output
l[0:4] “DATA”
l[:4] “DATA”
l[4:] “SCIENCE”
l[:] “DATASCIENCE”
l[:-7] “DATA”
l[4:-4] “SCI”
l[-2,-1] “C”
l[-1,-2] “”

The following Python program demonstrates retrieving range of characters from a string using
slicing operator.

On execution of the above code snippet, the following output is generated:

16
The above syntax can be augmented by specifying a third component a step value as shown
below:

l[start:end:step]

If you do not specify a step value it defaults to 1.

The following Python program uses a step value to extract the characters at odd and even index
positions in a string l.

On execution of the above code snippet, the following output is generated:

17
1.16 Compact Method for Reversing a String
Use the following compact syntax for reversing a string s.

Syntax: s[::-1]

The following Python program reverses a string “Python” using the syntax given above:

On execution of the above code snippet, the following output is generated:

18
String Objects are Immutable
Python does not allow the string object to be modified, once it is created. The following Python
program attempts to append the characters “ Programming” at the end of a string “Python” which
generates TypeError.

On execution of the above code snippet, TypeError is generated as shown below:

1.17 Complex Data Type


A typical complex number takes the form, x+iy where, x and y are real and imaginary parts.
Every complex number in Python is an instance of complex class. complex class has attributes
‘real’ and ‘imag’ for retrieving the real and imaginary parts of a complex number. The following
Python program, creates a variable of complex type and displays its real and imaginary parts
using attributes ‘real’ and ‘imag’, respectively.

On execution of the above code snippet, the following output is generated:


19
Replacing the statement x=1+1j with the statement x=1+j generates “undefined name j” error as
shown below since j is treated as a variable as shown in the following figure:

1.18 Determining Size of Variables in Python

sys Class
getsizeof() method of sys class can be used for determining the size of a variable. getsizeof()
function accepts the name of the variable as a parameter.

Under 64 bit Python 3.6 from the Anaconda distribution, the size of int data type is 28 bytes.
Size of string data type is computed using the formula

49 + Length of string

In the following example, the length of string variable s is 6, hence the size of s using the above
formula is,

49 + 6 = 55

as revealed in the output generated on execution of the program.

20
On execution of the above code snippet, the following output is generated:

To verify this further, determine the size of empty string variable. The expected output is 49 and
is indeed an actual output generated on execution of the program.

On execution of the above code snippet, the following output is generated:

21
The size of int is augmented by 4 bytes for every 230 times increment in the value as depicted in
the following table:

Value of i Size of i
1 28
230 32
260 36
290 40

This is demonstrated in the following Python program:

On execution of the above code snippet, the following output is generated:

22
int in Python is very different from int data type in other programming languages. Python int is a
full-fledged object containing among other storage a reference count which amounts to 16 bytes
of storage, which accounts for the large size of int type in Python. Consider the following code
snipet:

In the above program, the size of int class is printed and not an instance of int class object. On
execution of the above code segment, the following output is generated:

23
Re-write the above program as shown below and re-execute it.

On execution of the above code snippet, the following output is generated:

On execution of the above code snippet, the following output is generated:


24
1.19 Boolean Data Type in Python
Boolean data type is a sub type of int data type which can contain one of two values, True or
False which are stored internally using numeric 1 and 0, respectively. The following Python
program determines the size of boolean True and False using getsizeof() method of sys class.

On execution of the above code snippet, the following output is generated:

From the output generated on execution of the above program, it is evident that, the boolean True
and False values are stored in Python employing integer values of 1 and 0, respectively.

The following Python program uses conversion function, bool() for different arguments and
determines the truth value of its arguments in each case.

25
On execution of the above code snippet, the following output is generated:

26
1.20 Conversion Between Python Data Types
The conversion between data types in Python can be facilitated using one of the following
techniques:

 Implicit Type Conversion by Python


 Explicit Type Conversion by Programmer

1.20.1 Implicit Type Conversion (Widening of Conversion)


Implicit type conversion is automatic and does not involve any user intervention. Python always
converts smaller data type to a larger data type as a precautionary measure towards data loss.

In the following Python program, int and float values are added and the result is stored in a
variable ‘result’. Python implicitly converts int value to float value (upcasting) and stores the
value in a variable ‘result’.

On execution of the above code snippet, the following output is generated:

As seen from the output generated on execution of the program, the variable result evaluates to a
float type.

1.20.2 Explicit Type Conversion


Python supports different type conversion functions for converting between different data types
as depicted in the following table:

Conversion Function Description


bool() Converts the argument passed to a function to a boolean value
complex() Constructs an instance of complex type from the arguments
27
passed to a function
float() Converts the argument passed to a function to a float value
int() Converts the argument passed to a function to a int value
str() Stringifies the argument passed to a function
The following Python program demonstrates different type conversions employing explicit type
casting.

On execution of the above code snippet, the following output is generated:

1.21 Python I/O Processing


Python supports handful of functions for accepting input from the user interactively and for
generating formatted output.

1.21.1 Accepting Input From User Interactively – input() Function


Python supports input() function for accepting keyboard input as shown in the following
program:

28
On execution of the above code snippet, the following output is generated:

As is evident from the output generated on execution of the above program, input() function
returns a string value and use an adequate conversion function for type casting the string to the
required type.

1.21.2 Formatted Output


str class of Python supports a format() method for generating the formatted output on a standard
output device. Analogous to printf() function of C language, format() function accepts variable
number of arguments which are substituted in the place holders of a string on one-to-one basis as
shown in the following program:

29
On execution of the above code snippet, the following output is generated:

{} acts as a placeholder which is subsequently substituted by the variables specified as


arguments to format() function. Alternatively, the variables can also be initialized in a format()
function as shown below:

On execution of the above code snippet, the following output is generated:

30
Python also supports formatting string embedded with various formatting characters as shown
below:

On execution of the above code snippet, the following output is generated:

1.21.3 Generating Output on the Same Line


print() function automatically inserts a new-line character and hence multiple print() function
calls generate output on separate lines as shown below:

On execution of the above code snippet, the following output is generated:

31
To generate output on the same line specify that the line should be terminated with a single space
instead of a new line character using ‘end’ as the second named argument to print() function as
demonstrated in the following program:

Now the output is generated on the same line as the first print() function appends a single space
instead of a new line character.

1.22 Initializing Variables in Python

1.22.1 Assigning Value to Multiple Variables in a Single Statement


A value can be assigned to multiple variables in a single statement as demonstrated in the
following code segment:

In the above program, all the three variables, i, j and k are initialized with a common value of 50.
On execution of the above code snippet, the following output is generated:

32
1.22.2 Assigning Multiple Values to Multiple Variables in a Single Statement
Also, multiple values can be assigned to multiple variables in a single statement, the technique is
referred to as “Unpacking”. The values will be assigned to the variables in the order in which
they appear.

In the following Python program, the variables i, j and k are initialized with the values 10, 20 and
30, respectively.

On execution of the above code snippet, the following output is generated:

It should be noted that there is one-to-one correspondence between no. of variables and no. of
values. If the no. of values is less than no. of variables ValueError with the message “not enough
values to unpack” is generated. On the contrary, if the no. of values is more than the no. of
variables ValueError with the message “too many values to unpack” is generated as
demonstrated by the following code segment.

In the following Python program, in statement (8) the no. of variables on the left hand side is
more than the no. of values on the right hand side. The reverse is the case in statement (11).

33
On execution of the above code snippet, the following output is generated:

In the following Python program, multiple command delimited values are assigned to three
distinct variables i, j and k. Comma delimited numbers are treated as tuple in Python and each of
variables i, j and k evaluates to a tuple.

On execution of the above code snippet, the following output is generated:

1.23 None – A Special Data Type

34
None is a special data type in Python which means empty or non-existing.

1.24 Logical Grouping - Indentation


Python uses indentation for specifying the scope which specifies the grouping of statements. The
indentation level is determined by the leading white space which means a block of statements in
the same logical group must have the same indentation level.

Any unintentional inclusion of white space at the beginning generates an IndentationError as


shown in the following code snippet:

On execution of the above code snippet, the following output is generated:

Python coding standards specify using four spaces for indentation.

35
Chapter 2
Python Collections- Compound Data Types
Unlike other programming languages such as C, C++ and Java, Python does not support arrays.
However, it does support the following collection data types:

 List
 Tuple
 Dictionary
 Set

2.1 List in Python

A Python list is an ordered collection of mutable elements which can be heterogeneous. The
salient features of a list are enumerated below:

 Elements of list can be heterogeneous. List may encapsulate elements of disparate data
types such as integers, strings or even objects.
 List is ordered which implies for the two lists to be identical their corresponding elements
should be identical (not only the elements but also their order).
 List can contain duplicate elements since every element has a well-defined place in a list.
 List is mutable which means the elements of list can be changed after the list is created.
 Similar to a string, the elements of a list are indexed using both positive index and
negative index. The index starts with zero.
 List is iterable and hence enables to iterate through it’s elements employing optimized for
loop.
 List can dynamically grow and shrink

2.1.1 Creating List in Python

The list can be created by placing comma delimited elements within a pair of square brackets.
The syntax for creating an empty list is:

l = []

The syntax for creating a non-empty list is:

l = [e1, e2, e3, . . .,eN]

where e1, e2 …. eN are elements of a list.

The following Python program creates and print a list:

36
On execution of the above code segment, the following output is generated.

A list can contain elements of different data type as demonstrated in the following code segment:

meeting_info is list containing three elements of str, float and str type. The elements of the list
are accessed using index operator where the first element has index zero.

On execution of the above code segment, the following output is generated.

Since list is mutable, the elements of the list can be altered after the list is created as shown in the
following program:

37
In the above program the second and third elements of a list meeting_info corresponding to
meeting time and date are altered.

On execution of the above code segment, the following output is generated.

Since list is iterable, it enables iterating through its elements using for loop as shown in the
following code snippet:

In the above program, for loop iterates through every element of the list ‘lang’ and prints it.

On execution of the above code segment, the following output is generated.

38
2.1.2 Creating a List Using List Constructor

The list class is embedded with a constructor for creating a list. The syntax for creating a list
using list class constructor is shown below:

Syntax:

list((ele1, ele2, ele3, . . ., eleN))

The following Python program demonstrates creating a list of languages using list class
constructor:

On execution of the above code segment, the following output is generated.

2.1.3 List is Ordered

For the two lists to be equal it is necessary that they contain the same elements in the same order
i.e. the corresponding elements of the two lists are equal. If the elements of the two lists are
identical but if their orders are different, the two lists are considered to be different as
demonstrated in the following code segment:

39
In the above program, num_list1 and num_list2 contain the same elements but in different order
and hence the two lists are not identical. On the other hand, num_list1 and num_list3 contain the
same elements in the same order, as such are identical.

On execution of the above code segment, the following output is generated.

40
2.1.4 comp() Method

The elements of the list can also be compared using cmp() method which accepts the two lists to
be compared as its arguments.

The above program for comparing the elements of two lists is re-written using cmp() method.

num_list1=[1,2,3,4,5]
num_list2=[5,4,3,2,1]
num_list3=[1,2,3,4,5]
if (cmp(num_list1,num_list2):
print(“num_list1 is equal to num_list2)
else:
print(“num_list1 is not equal to num_list2)
if (cmp(num_list1,num_list3):
print(“num_list1 is equal to num_list3)
else:
print(“num_list1 is not equal to num_list3)

Note: cmp() function is not supported in Python version 3.

2.1.5 List Concatenation

Two lists can be concatenated using “+” operator as demonstrated in the following Python code
segment:

When the two lists are concatenated using “+” operator, the second list is iterated over and the
elements are appended to the first list. Hence second operand of “+” operator should strictly be
an iterable.

On execution of the above code segment, the following output is generated.

41
It should be noted that the list concatenation operator is not commutative, hence

l1 + l2 is not same as l2 + l1

Also, the augmented assignment operator += is functionally same as extend() function (to be
covered) as shown in the following code segment:

On execution of the above code segment, the following output is generated.

A single element cannot be appended to a list using += operator since int type is not iterable.
Doing so will generate a TypeError as demonstrated in the following code segment:

42
On execution of the above code segment, the following output is generated.

This is not the case with a string since str class objects are iterable. This is demonstrated in the
following code segment:

On execution of the above code segment, the following output is generated.

Even though we have succeeded in getting rid of error, the result is not what is expected. The
string has been iterated and the characters of a string are simply appended to the list. In order to

43
get a desired result a list containing a single element “Python” must be concatenated to lang_list
as shown in the following program:

On execution of the above code segment, the following output is generated.

Now, instead of stripping off the characters of a string “Python”, the string itself is appended to
the list as revealed in the output generated on execution of the code segment.

2.1.6 Repeating the Elements of the List - * Operator

Similar to a string, a repitition operator, “*” can be used for generating a list containing the same
elements as shown in the following code segment:

In the above code, the list is constructed by repeating the string “Python” five times.

On execution of the above code segment, the following output is generated.

44
2.1.7 Memory Organization for List

Since everything in Python is an object, the list is also an object with the underlying C structure.
List in essence contains a reference to C structure. One of the members of a structure is an array
of pointers to the list elements.

2.1.8 Accessing the Elements of a List

Index operator, [] can be used for accessing the element(s) of a list. If the list conatains n
elements, the index can vary from 0 to (n-1).

Consider the following list:

l = [‘D’, ‘A’, ‘T’, ‘A’, ‘S’, ‘C’, ‘I’, ‘E’ ,’N’, ’C’, ‘E’]

The elements of the list can be accessed using either positive or negative index as shown below:

D A T A S C I E N C E
0 1 2 3 4 5 6 7 8 9 10
-11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1

The indices -1, -2, . . . refer to the last element, second last element and so on. In general, -n
index is used for specifying nth last element.

The index operator is used for accessing the elements of a list. Hence for accessing the element
at the index position i, the syntax is:

l[i]

If the list is of length N, then the syntax for accessing the element at the index position i using
negative indexing mechanism is

l[i-N]

Hence in the above list l, the element at the positive index of 5 is the same as the element at the
negative index of (5-11) = -6 where the length of the list l is 11. (i.e. C)

45
2.1.9 IndexError in Python

Attempting to access an element beyond the limits generates an IndexError as demonstrated in


the following program:

The list l contains 11 elements with the index in the range 0 to 10. Attempting to access an
element at position 11 will generate IndexError. On execution of the above code segment, the
following output is generated.

Similarly, attempting to access an element outside the list using negative indexing generates
IndexError as shown below:

On execution of the above code segment, the following output is generated.

46
2.1.10 Accessing Multiple Contiguous Elements from a List

List indexing is exactly similar to string indexing.

You can select multiple elements from a list using a slicing operator :

Syntax:

For accessing the elements from index ‘s’ to ‘e-1’ use the following syntax:

l[s:e]

where s is the start index and e-1 is the last index of the retrieved element.

2.1.11 Slicing Operator

For selecting multiple contiguous elements from a list, a slicing operator denoted by : can be
employed.

For accessing the elements from index ‘s’ to ‘e-1’ use the following syntax:

x[s:e]

where s is the start index and e-1 is the last index of the retrieved element.

The syntax for accessing multiple contiguous elements from the list is depicted in the following
table:

For This Do This Remark


Accessing the elements from x[s:e+1] The index (e+1) is excluded
index s to index e
Accessing the elements from x[s:] Since end index is not specified, all the
index s to last element of a list elements upto last element are retrieved.
Accessing the elements from x[:e+1] Since start index is not specified, the
beginning to index e elements are retrieved starting with first
elements and since the end index is
excluded, the elements upto index e are
retrieved
Accessing the whole list x[:] Since both start and end index are not

47
specified, all the elements of a list are
retrieved.

Example:
Consider the following list with the corresponding positive and negative indexing of elements:

D A T A S C I E N C E
0 1 2 3 4 5 6 7 8 9 10
-11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1

The following table depicts various scenarios of retrieving multiple contiguous


elementsemploying the syntax presented above.

Example Output
l[0:4] “DATA”
l[:4] “DATA”
l[4:] “SCIENCE”
l[:] “DATASCIENCE”
l[:-7] “DATA”
l[4:-4] “SCI”
l[-2:-1] “C”
l[-1:-2] “”

The following Python program demonstrates retrieving range of elements from a list using
slicing operator.

On execution of the above code snippet, the following output is generated:


48
The above syntax can be augmented by specifying a third component a step value as shown
below:

l[start:end:step]

If you do not specify a step value it defaults to 1.

The following Python program uses a step value to extract the elements at odd and even index
positions in a list l.

On execution of the above code snippet, the following output is generated:

49
2.1.12 Changing Multiple Elements of a List Using Slicing Operator

In the following program, the elements at the index positions 2, 3 and 4 are replaced with the
elements 30, 40 and 50 contained in the list, respectively.

On execution of the above code snippet, the following output is generated:

In the above program, the number os elements in a list is exactly equal to no. of indices. Hence,
no. of indices is equal to no. of elements inserted. However, this may not always be the case, the
no. of elements may be more or less than the no. of indices, the list is simply grown or shrinked
as needed to accommodate new elements as demonstrated in the following code segment. This is
attributed to the dynamic nature of a list.

50
In the above program, in the first example, the five elements, 30, 40, 50, 55 and 59 are inserted
starting at the index position 2. In the second example, the list is shrinked to accommodate a
single element at the index positions 2 to 4. On execution of the above code snippet, the
following output is generated:

Emphasis should be laid on understanding the difference involved in replacing a single element
and a range of elements with a new list. When a single element is replaced with a list, the whole
list gets inserted at the specified position. On the contrary, when the range is replaced with a list,
the elements of the list get inserted in the specified range as demonstrated in the following code
segment:

51
On execution of the above code snippet, the following output is generated:

Hence the thumb rule is for replacing a single element of a list with multiple elements of a list
use range instead of a single index.

2.1.13 Checking the Existence of the Element in the List – Testing List
Membership
The syntax for checking whether the element ‘ele’ is present in the list ‘l’ or not, use the
following syntax:

if ‘ele’ in l

The following Python program checks whether the langauge accepted from the end user is
present in the list, lang_list or not:

52
On execution of the above code snippet, the following output is generated:

53
2.1.14 Determining Size of the List

len() method is used for determining the size of the list as demonstrated in the following code
segment:

On execution of the above code snippet, the following output is generated:

2.1.15 Operations on List

Adding items to the list


The list can be extended using one of the following methods:

i. Appending an element at the end of the list using append() method. append() method
modifies the target list and does not return a new list.
ii. Inserting an element in the list using insert() method
iii. Appending one or more elements at the end of the list using extend() method.

The following table provides a quick glance at the various methods available for extending the
list:

Method Name Syntax Description


append l.append(ele) Appends an element ‘ele’ at the end of the list ‘l’. append
enables adding only one element to the list. Lists can also
be added using append method which creates a nested list.
Insert l.insert(i,ele) Inserts an element ‘ele’ in the list ‘l’ at the index position
‘i’
Extend l.extend(l1) extend() accepts a parameter which is iterable. It appends
the elements of the list ‘l1’ at the end of the list ‘l’. Unlike
append method extend method enables appending multiple
54
elements at the end of a list in a single go.

The following Python program demonstrates the usage of above methods:

On execution of the above code snippet, the following output is generated:

55
In the following Python program, append() method is used for appending the list
‘more_even_list’ at the end of ‘even_list’.

On execution of the above code snippet, the following output is generated:

As seen from the output generated on execution of the above program, the whole list is appended
at the end of ‘even_list’.

Consider the modified version of the above program as shown below:

In the above program, append() method is replaced with extend() method. On execution of the
above code snippet, the following output is generated:

56
The output generaed above reveals the difference between append() and extend() methods.
append() method appends the whole list at the end of original list, while extend() method iterates
through the list and appends the elements to the original list on one-to-one basis.

A word of caution. It should be noted that append() method modifies the target list and does not
return a new list. This is demonstrated in the following code segment:

On execution of the above code snippet, the following output is generated:

In the above program, the return value of append() method is stored in lang_list and is printed in
statement(10). The printed value does not correspond to a modified list but is an empty value
denoted by ‘None’.
The following points must be kept in mind while adding element to a list:
 Extend is equivalent to += operator
 Append() does not iterate throught the list appends the entire list as a single object
 + iterates though the list
 Extend iterates through the list and appends the individual elements to the list

2.1.16 Using range() Function for Creating a List

57
range() function yields sequence of numbers within the specified limits. For example, range(m,n)
generates a sequence of numbers ranging from m to n-1. The common application of range()
function is to generate a list containing required sequence of numbers.

The following Python code segment demonstrates generating a list containing numbers from 1 to
10 using range() function:

In the above program, num_list is constructed by iterating trough the numbers generated by the
range() function and using append() method. On execution of the above code snippet, the
following output is generated:

2.1.17 Deleting Elements of a List – del() Method


del() method can be used for any one of the following purposes:

 deleting an element from the list at the specified index position


 deleting range of elements from the list using slicing operator
 deleting an entire list

The following table provides a quick glance at the various methods available for extending the
list:

Action Syntax
Deleting a single element from the list l at the del l[i]

58
specified index position, i
Deleting a range of elements from the list l del l[i:j+1]
from the index position I to j
Deleting the list l del l

The following Python program demonstrates the various scenarios depicted above:

On execution of the above code snippet, the following output is generated:

59
Since list is an object, deleting the list deletes a reference to the object and ceases to be accessed
in the code further. An attempt to access the deleted list generates NameError as revealed in the
output generated on execution of the above program.

2.1.18 Difference Between del l[:] and del l


The expression
del l[:]
deletes all the elements of a list l but the reference is intact while the expression
del l
delete all the elements of the list followed by a reference and any reference to l after the
reference is deleted will generate a NameError as demonstrated in the following code segment:

On execution of the above code snippet, the following output is generated:

60
Yet another handy way of deleting a range of elements from the list is assigning an empty list to
the range as demonstrated in the following program:

In the above program, an empty list is assigned to a range of elements in the index positions 1 to
3 which in effects deletes the elements at those index positons. On execution of the above code
snippet, the following output is generated:

2.1.19 Deleting the Element Using pop() Method


Like del method, pop() method can be used for deleting the element from the specified index
position. If the pop() method is invoked without any argument, then the element at the end of the
list will be deleted as demonstrated in the following program:

61
On execution of the above code snippet, the following output is generated:

2.1.20 Deleting All Elements From the List – clear() Method


clear() method is used for deleting all the elements of a list in a single invocation, but the list
itself is not deleted as shown in the following code segment:

62
On execution of the above code snippet, the following output is generated:

Note:
Syntactically clear() method is functionally equivalent to the following expression:
del lang_list[:]
This is demonstrated in the following program:

On execution of the above code snippet, the following output is generated:

63
2.1.21 Removing the Specified Item From the List – remove() Method

remove() method can be used for deleting the element from the list by specifying its name as an
argument to the method. If the list contains duplicate elements, remove() method only deletes the
first occurrence of the specified element from the list as demonstrated in the following program:

In the above program, the element ‘C’ occurs at two positions in the list, lang_list, at the
beginning and at the end. remove() method only deletes the first occurrence of the element from
the beginning of the list as revealed in the output generated on execution of the above code
segment:

64
If the specified element is not in the list, then remove method will generate an error as
demonstrated in the following Python program:

On execution of the above code snippet, ValueError is generated as shown below:

2.1.22 Removing Multiple Elements From the List Using Iterator

remove() method can be used for removing only a single element at a time. For removing
multiple elements use iterator as demonstrated in the following code segment:

The following Python program deletes the even elements from num_list using remove() method:

On execution of the above code snippet, the following output is generated:


65
For deleting the non-contiguous elements from the list, the trick is to store all the elements to be
deleted in another list and invoking remove() method by iterating over it as demonstrated in the
following Python program:

On execution of the above code snippet, the following output is generated:

Rewriting the above program using del keyword requires careful thought since del uses index of
the element to be deleted and each time the element is deleted using del keyword, the remaining
elements are re-indexed. For instance, assume you need to delete the elements at index positions,
0, 3 and 6 in a list [1,2,3,4,5,6,7,8,9]. Hence the resulting list should be [2,3,5,6,8,9]. The
erroneous program by a novice would be written as shown below:

66
In the above program, after deleting the element at index position 0, the resulting list is [2, 3, 4,
5, 6, 7, 8, 9], hence the element 4 is now at index position 2 and not 3, with the similar argument
after deleting the element 4, the resulting list is [2,3,5,6,7,8,9] and the element 7 is now at
position 4 and not 6.
Hence the erroneous output generated on execution of the above program is shown below:

For generating the desirable output the indices are to be adjusted properly as demonstrated in the
following program:

On execution of the above code snippet, the following output is generated:

67
In general for deleting the elements at the indices i1,i2,i3,. . .in, the list to be constructed is:

[i1,i2 - 1,i3 - 2,. . .in-(n-1)]

Note: The list class methods append(), extend(), insert(), remove(), pop() modify the original list
and do not return the modified list.

2.1.23 Cloning a List in Python

Assigning one list variable to another will only create a new reference pointing to the original list
and will not create a new list. The side effect of this is a single list is referenced by two reference
variables. Changing the list via any of these reference variables will affect the other as both the
reference variables see the same list.This is referred to as “Shallow Copying”. In the following
program, both l and l1 refer to the same list. In statement (10), the list is modified using
reference ‘l’ and in the subsequent statement, the list ‘l1’ is printed. From the generated output it
is seen that, l1 also gets modified accordingly. A similar exercise in statements (13) and (14)
show that the variable ‘l’ sees any changes to the list carried out by ‘l1’.

On execution of the above code snippet, the following output is generated:

68
For creating a clone of a list use copy() method. clone() methodcreates an exact copy of the list.
This is referred to as “Deep Copying” and is demonstrated in the following program:

In the above program, the list l is cloned using copy() method. Hence the variables ‘l’ and ‘l1’
reference two distinct lists. In statement (17), the list is modified by reference ‘l’ by appending
the string “C++” which does not change the list referenced by ‘l1’ now, since they are two
distinct lists. Similarly, in statement (24), the list is modified by reference ‘l1’ by appending the
string “Swift” which does not change the list referenced by ‘l’ as revealed in the output generated
on execution of the above program:
69
2.1.24 Testing Object Equivalence Using ‘is’ operator

A quick method for testing object equivalence is by using ‘is’ operator which returns one of
boolean values ‘True’ or ‘False’ depending on the situation. In the following Python program,
the shallow copying and deep copying are demonstrated using “is” operator.

On execution of the above code snippet, the following output is generated:

70
2.1.25 Sorting the List – sort() Method

Use sort() method for sorting the elements of a list as demonstrated in the following program:

On execution of the above code snippet, the following output is generated:

71
2.1.26 Bi-directional Sorting Using sorted() Method
The sort() method re-organizes the elements of a list in a sorted order and does not return a
sorted list. In order to sort the elements into a new list while keeping the original list intact use
sorted() method which accepts the name of the list to be sorted and returns a new sorted list.
Further, sorted() method accepts a second optional argument namely ‘reverse’ for specifying the
sort order. The default value of argument ‘reverse’ is false. Setting it to true sorts the elements in
descending order as demonstrated in the following program:

On execution of the above code snippet, the following output is generated:

2.1.27 Reversing the Elements of the List – reverse() method


The list class supports a reverse() method which reverses the elements of a list as shown in the
following program:

72
On execution of the above code snippet, the following output is generated:

Alternatively, the compact expression l[::-1] returns a new list containing the reversed elements
of list l as demonstrated in the following program:

On execution of the above code snippet, the following output is generated:

73
2.1.28 Counting the No. of Elements in a List with a Specified Value – count()
Method
The list class supports a count() method which returns the size of the list.

On execution of the above code snippet, the following output is generated:

2.1.29 To Find the Index of the Element in the List – index() Method

Use index() method of a list class to find the position of the element in the list passed to it.
ValueError is generated if the element passed to index() method is not present in the list as
demonstrated in the following program:

74
On execution of the above code snippet, the following output is generated:

2.1.30 List Comprehension

List comprehension refers to a concise way of creating a list from an existing list. List
comprehension consists of square brackets enclosing an expression followed by a for loop.

Applications of list comprehension are:

 To create a new list which is a sub-list of the original list based on specified condition.
 To create a new list by performing some operations on the elements of original list

In the following Python program, two lists even_list and odd_list consisting of even and odd
elements of num_list are generated using list comprehension.
75
On execution of the above code snippet, the following output is generated:

The code without list comprehension is depicted below:

On execution of the above code snippet, the following output is generated:

76
List comprehension is extremely powerful which supports conditionals and iterations to any
level. In the following Python program, the list l is constructed by concatenating every element
of list [‘Java’, ‘VB’] is concatenated with every element of list [‘Programming’,’Script’]. The
outer for loop iterates through every element of first list and concatenates it by iterating through
every element of second list.

On execution of the above code snippet, the following output is generated:

The code without list comprehension is depicted below:

77
Same output as above is generated on execution of above code block.

The following Python program generates all possible triplets of three elements 1, 2 and 3

78
On execution of the above code snippet, the following output is generated:

79
The code without list comprehension is shown below:

On execution of the above code snippet, the following output is generated:

80
2.1.31 Nested List Comprehension

List comprehension consists of two parts:

i. Initial Expression
ii. One or more for loops

If the initial expression itself is another list comprehension, we end up with nested list
comprehension.

Nested list comprehension provides an extremely concise way of generating the nested list. Here
we apply nested list comprehension for finding the transpose of a given matrix. Three different
cases are dealt with, with and without list comprehensions.

Consider the following 3 x 3 matrix,

matrix = [[1,2,3],[4,5,6],[7,8,9]]

2.1.31.1 Case 1: Finding transpose of a matrix without list comprehension.

In this case two different for loops are required, one to navigate through the column index and
other for navigating through different rows of a matrix as demonstrated in the following
program:

81
On execution of the above code snippet, the following output is generated:

82
2.1.31.2 Case 2: Using Single List Comprehension

Using a single list comprehension, we can compactify the inner for loop as demonstrated in the
following program. In statement(12), the variable i, iterates over the values 0 to 2 and in each of
these iterations, a list is created by appending the elements in that column of each of the elements
of a matrix which is appended to a transpose.

On execution of the above code snippet, the following output is generated:

83
2.1.31.3 Case 3: Using Nested List Comprehension

The above code can further be rendered compact using nested list comprehension as
demonstrated in the following program. In this case, the transpose of a matrix is created in a
single step, the outer for loop iterates through elements in the range 0..2 and in the same
statement, the inner loop constructs list containing all elements of matrix in that column position
and appends it to transpose.

On execution of the above code snippet, the following output is generated:

84
2.1.32 Nested Lists in Python

The elements of a list themselves can be lists which generates a nested list. The nesting of lists
can be to any level constrained only by the readability of alist. The list l shown below depicts
nesting of lists.

l = [[[1, 2], [3, 4], 5], [6, 7]]

The above list consists of two elements as follows:

l[0]= [[1,2], [3,4] ,5]

l[1]=[6,7]

Both the elements thermselves are lists. The list l[0] consists of three elements as shown below:

l[0][0] = [1,2]

l[0][1] = [3,4]

l[0][2] = [5]

To access the element 4 the syntax is:

l[0][1][1]

The following table depicts the indexing used for accessing different elements of a list l:

Element Indexing
1 l[0][0][0]
2 l[0][0][1]
3 l[0][1][0]
4 l[0][1][1]
5 l[0][2]
6 l[1][0]
7 l[1][1]

Following Python program shows the implementation of the above indexing:

85
On execution of the above program, the following output is generated:

A more real-life example of a nested list is given below:

Cosider the following nested list,

marks_list=[[“C”,70,10], [“CPP”,65,12], [“Java”,68,11], [“Python”,71,12]]

mark_list is a nested list containing four elements where each element itself is a list containing
three elements subject name, external marks and internal marks, respectively. Hence,

marks_list[0] =[“C”,70,10]

marks_list[1] = [“CPP”,65,12]

marks_list[2] = [“Java”,68,11]

86
marks_list[3] = [“Python”,71,12]

Hence all the subjects can be accessed using the following indexing;

marks_list[0][0] = “C”

marks_list[1][0] = “CPP”

marks_list[2][0] = “Java”

marks_list[3][0] = “Python”

Similarly, the indexing used for accessing external and internal marks are

marks_list[i][1] where 0 <= i <= 3 and

marks_list[i][2] where 0 <= i <= 3, respectively.

The following Python program demonstrates the use of nested lists:

On execution of the above code snippet, the following output is generated:

87
2.1.33 Membership Testing in Nested Lists

Consider the list l defined as follows:

l=[1,[2,3,[4,5]]]

l has only two elements. The first element is of type int and the second element is a sublist.
Hence,

l[1] = [2,3,[4,5]]

l[1] has three elements, the first two elements are of type int while the third element is a sublist.
Hence,

l[1][2]=[4,5]

Thus, 4 is not a direct member of a list l, but is a member of list l[1][2]. This is demonstrated in
the following Python code segment:

On execution of the above code snippet, the following output is generated:

88
2.1.34 Converting An Iterable to a List

list() method can be used for converting any interable such as string, tuple, set, dictionary (to be
discussed) to a list.

s=”Python”

print(type(s),s)

l=list(s)

print(type(l),l)

2.1.35 Finding the Smallest and Largest Element in a List

max() and min() methods are used for finding the smallest and largest element in a list.

In the following program, salary_list is a list of salaries of all employees belonging to IT


department. max() and min() methods are used for finding lowest and highest salaries. sum()
method along with len() method is used for finding average salary:

89
On execution of the above code snippet, the following output is generated:

2.1.36 Miscellaneous In-Built List Functions in Python

all() and any()


all() method returns True if one of the following condition is satisfied:

 List is empty
 All elements of list are True

On the other hand, any() method returns True if atleast one element is True.

2.1.37 Implementation of AND Logic Using all()

The characteristic of all() and any() functions make them appropriate for implementing logical
AND and OR logic gates as demonstrated in the following Python program:

In the above code segment, the block of statements in the range 13 to 20, are executed for all
combinations of elements in the lists cond1 and cond2. The function all() returns True, if and

90
only if both the operands are True, otherwise returns False. On execution of the above code
snippet, the following output is generated:

91
2.1.38 Implementation of OR Logic Using any()

Replacing the function all() by any() in statement (19) generates the truth table for OR gate as
demonstrated in the following program:

The function any() returns TRUE, if at least one of operands is True, otherwise returns False. On
execution of the above code snippet, the following output is generated:

In the following Python program, result_list stores the result of a student in five different
subjects. The element has a value True if the student passes in the subject, otherwise False. If the
student fails in any of the subjects then final result is declared as ‘Fail’, otherwise ‘Pass’, if
student passes in all the subjects.
92
On execution of the above code snippet, the following output is generated:

Change one of the elements of result_list to False and re-execute the program as shown below.
The following output is generated:

93
The if statement in statement (11) checks the length of the list since all() method returns True
even if the list is empty. Make the list empty and re-execute the program, the following output is
generated:

2.1.39 enumerate() Method

It returns an enumerate object containing the index and value of all the items of list as a tuple.

2.1.40 Using List as Stack

The append() and pop() methods of list class make it possible to use list as a stack data structure
where the element popped out is the last element appended, (Last-In-First-Out data structure).

append() method is used for adding the element at the top of the stack and pop() method is used
for removing the element from the top of the stack. A simple stack application is demonstrated in
the following Python program:

On execution of the above code snippet, the following output is generated:

94
2.1.41 List is Not Efficient Queue Data Structure

While list can be used as a stack efficiently, using list as a queue is less efficient. Appending and
retrieving the element from the end of the list is efficient since it does not involve any shifting of
elements. On the contrary, appending and retrieving the elements from the beginning of the list
encounters an overhead of shifting elements which is associated with a cost. Hence list is
efficient LIFO data structure but less efficient FIFO data structure.

2.2 Tuple in Python

A tuple in Python is an ordered collection of immutable elements which can be heterogeneous.


Tuple is similar to list in many aspects but is immutable which means the elements of a tuple
cannot be modified once the tuple is created. Neither the tuple nor the elements of a tuple are
modifiable once the tuple is created. Many features of list are shared by a tuple except being
mutable and hashable. Nevertheless, for completeness the salient features of a tuple are
enumerated below:

 Elements of tuple can be heterogeneous.


 Tuple is ordered
 Tuple can contain duplicate elements since every element has a well-defined place in a
tuple.
 Tuple is immutable which means the elements of tuple cannot be changed after the tuple
is created.Also, a tuple does not allow adding a new element or deleting an existing
element. One exception to this is if a tuple contains list as one of its elements, the list
being mutable allows modifications. Hence even if tuple is immutable, it can contain
mutable objects.
 Similar to a string and a list, the elements of a tuple are indexed using both positive index
and negative index. The index starts with zero.
 Tuple is iterable and hence enables to iterate through it employing optimized for loop.
95
 Tuple cannot dynamically grow and shrink
 Tuples are hashable which accounts for the high performance of tuples compared to lists.

A tuple is preferable to a list in situations where the elements need to be protected against
accidental modification.

2.2.1 Creating Tuple in Python

A tuple is created by placing all the items (elements) inside a parentheses (), separated by
comma. In declaration of a tuple the parentheses are completely optional but is a good practice to
write it as it improves the readability of a code. The main syntactic difference between a list and
tuple is that list encloses comma delimited elements within a pair of square brackets whereas a
tuple encloses comma delimited elements within a pair of parentheses.

The syntax for creating an empty tuple is:

t = ()

The syntax for creating a non-empty tuple is:

t = (e1, e2, e3, . . .,eN)

where e1, e2 …. eN are elements of a tuple.

The following Python program creates and prints a tuple:

On execution of the above code segment, the following output is generated.

As seen from the output generated on execution of the program, every tuple is an instance of a
class ‘tuple’. The following Python code segment shows creating a tuple without using
parentheses.

96
On execution of the above code segment, the following output is generated.

Even if the parentheses are omitted in the declaration of a tuple, are included automatically by
Python when the tuple is printed to indicate that it is indeed a tuple.

97
2.2.1.1 Creating Tuple Using Tuple Class Constructor

Similar to other collection classes, tuple class class contains a constructor for creating a tuple as
shown in the following program:

On execution of the above code segment, the following output is generated.

2.2.1.2 Creating a Tuple With a Single Element

Creating a tuple with a single element is quite tricky. When a single element is enclosed within a
pair of parentheses it is treated as a primitive data type as shown in the following program. In the
following program, in statement (7) the variable a is initialized and to figure out the type of a
variable type() function is used in statement(8).

On execution of the above code segment, the following output is generated. As seen from the
output generated on execution of the program, the type of a is ‘int’ and not ‘tuple’. A trailing
comma as used in statement (10) is required to convert an ‘int’ into a ‘tuple’. Hence, the
preceding print statement now displays the type of variable ‘a’ to be tuple as shown below:

98
In the above program, even if comma is placed at the end while declaring a tuple a, empty
element will not be appended to the tuple. This can be verified by using len() function to count
the no. of elements in a tuple ‘t’ or printing the first and last elements of a tuple ‘t’ as shown in
the following program:

On execution of the above code segment, the following output is generated.

2.2.2 Tuple Packing

Creating a tuple without parenthesis is referred to as ‘tuple packing’.


The following statement creates a tuple with five elements.
t = 1, 2, 3, 4, 5
In the following program, the tuple is created by the mechanism of ‘tuple packing’ and is printed
in a subsequent statement.

99
On execution of the above code segment, the following output is generated.

Tuple packing does not work in concatenation of two tuples. In the following program, in
statement(11) the tuple (6, 7, 8) is concatenated with tuple t and the result is stored in a variable
t1.

On execution of the above code segment, the following output is generated. As seen from the
output generated on execution of the program, Python will complain with the TypeError, since
statement(11) in the above program is interpreted as adding ‘int’ to a ‘tuple’ and not
concatenation of two tuple as + operator has higher precedence over command operator.

100
Even appending a comma at the end of statement(11) will not solve the problem. To remove the
error, place the elements of a tuple in statement(11) in a pair of parentheses as shown in the
following program:

On execution of the above code segment now, the tuples are concatenated and the following
output is generated.

101
2.2.3 Tuple Unpacking

Assigning values from a tuple to a set of variables is referred to as tuple unpacking. In the
following example, the tuple ‘t’ is created with three elements 1, 2 and 3 which are used for
initializing the three variables a,b and c using ‘tuple unpacking’.

t = (1, 2, 3)
a, b, c = t
The same is demonstrated in the following program:

On execution of the above code segment, the following output is generated.

It should be kept in mind that the no. of variables should exactly match the no. of elements in a
tuple. If the no. of elements in a tuple is greater than no. of variables, ValueError, with the
message “too many values to unpack” is generated as shown in the following program:

On execution of the above code segment, the following output is generated.

102
On the contrary, if the number of variables is greater than the no. of elements in a tuple,
ValueError with the message “not enough values to unpack” is generated as shown in the
following program:

On execution of the above code segment, the following output is generated.

2.2.4 Combining Tuple Packing and Unpacking

Tuple packing and unpacking can be combined into a single statement for initializing multiple
variables in the same statement as demonstrated in the following program:

103
On execution of the above code segment, the following output is generated.

Again, the same rule must be observed, the no. of variables on the left hand side must be equal to
the no. of values on the right hand side.

A tuple can contain elements of different data type as demonstrated below. Commonly a tuple is
used for storing heterogeneous elements while list is used for storing homogeneous elements.

On execution of the above code segment, the following output is generated.

Any attempt to modify the element of a tuple will generate a TypeError as shown below since a
tuple is immutable. In the following program, statement (8) attempts to modify the first element
(at index position 0) of a tuple created in statement(7).

104
On execution of the program, TypeError is generated as shown below:

2.2.5 Repeating the Elements of the Tuple - * Operator

Similar to a string and a list, a repetition operator, “*” can be used for generating a tuple
containing the same elements as shown in the following code segment. In the above code, the
tuple is constructed by repeating the string “tuple” ten times.

On execution of the above code segment, the following output is generated.

105
2.2.6 Iterating Through Elements of a Tuple

Since tuple is iterable, it enables iterating through its elements using for loop as shown in the
following code snippet:

On execution of the above code segment, the following output is generated.

2.2.7 Tuple is Hashable

All immutable types are hashable so is the tuple. Every hashable object is characterized by a
unique hash value which does not change during the life time of the object. Python supports
__hash__() method for listing the hash value associated with the object. This hash value is
further used for checking equivalence of two objects using __cmp__() and __equ__() methods.
For the two objects to be equal their hash values must be identical.

If the corresponding elements of two tuples are same, then the two tuples will have same hash
values as demonstrated in the following program. This feature makes them suitable to be used as
keys of dictionary (to be discussed later).

106
On execution of the above code segment, the following output is generated.

The following Python program uses hash value associated with a tuple to check the equality of
two tuples. Under the hood, the equality operator works similarly.

107
On execution of the above code segment, the following output is generated.

108
2.2.8 Accessing the Elements of a Tuple

Similar to list, index operator, [] can be used for accessing the element(s) of a tuple. The same
rules specified earlier for accessing the elements of a list also apply to a tuple.

The syntax for accessing the element using indexing is:

Syntax: [start_index:end_index:step_value]

For example, t[::2], retrieves all alternate elements of a tuple t starting with a first element (at
index position 0) upto last element. The more readable version of the above expression is:

t[0:n-1:2], where n is the size of the tuple.

This is demonstrated in the following program:

109
On execution of the above code segment, the following output is generated.

2.2.9 Negative Step Value

The negative step value only reverses the direction of data retrieval as shown in the following
program.

The above program prints every alternate element starting from last element to first element in a
tuple t.On execution of the above code segment, the following output is generated.

The side-effect of this is the expression

t[::-1]

which reverses the elements of a tuple as shown in the following program:

110
On execution of the above code segment, the following output is generated.

Here is a quick example of accessing different parts of a tuple using index operator.

On execution of the above code segment, the following output is generated.

111
2.2.10 Index Error in Tuple

Similar to a list, attempting to access an element of a tuple beyond the limits generates
IndexError as shown in the following program:

On execution of the above code segment, the following output is generated.

2.2.11 Determining Size of Tuple

len() method of a tuple class can be used for determining the size of a tuple as shown in the
following program:

112
On execution of the above code segment, the following output is generated.

2.2.12 Testing Tuple Membership

in() method or its complement, not in() method can be used for checking whether an element
exists in a tuple or not as shown in the following program.

On execution of the above code segment, the following output is generated.

113
2.2.13 Tuple is Ordered

Every element of a tuple is characterized by not only value but also by position. Hence for two
tuples to be equal not only the values of the elements but also their positions need to be identical
as shown in the following program:

On execution of the above code segment, the following output is generated.

114
2.2.14 Testing Equality Using is Operator

is operator checks object identity and return True if and only if both are same objects or if both
objects have the same identifier. id() function can be used for checking the object identifier. On
the other hand, if the two tuples have the same content, then their hash values are identical,
equality operator is also based on a hash value. Hence the thumb rule is:

 __hash__() function and equality operator, == return True, if the two objects have the
same content, otherwise return False.
 id() function and is operator return True, if the two objects are same, otherwise return
False.

This is demonstrated in the following program.

115
In the above program the tuple objects t1 and t2 have the same content but the objects are not
same. On the other hand, the objects t1 and t3 are same. Hence the hash value of all the three
objects are same whereas identifier of t1 and t3 is same which is different from identifier of t2.
Thus, comparison of t1, t2 and t3 using ‘is’ operator outputs “t1 and t2 are Not Equal” and “t1
and t3 are Equal”.

On execution of the above code segment, the following output is generated.

116
117
2.2.15 Operations on Tuple

List class methods Applicable to tuple


list Class Construct Supported Remark
in tuple
class?
[], *, is [:], in, + Yes Indexing, repetition, object comparison,
slicing,membership testing and
concatenation are supported in a tuple
Iteration using for loop Yes
len() Method Yes For determining size of a tuple
del operator Partially Available only for deleting the object, not
a single element or range of elements
Aggregate functions, max(), Yes
min(), sum(), count()
sorted() Function Yes
index() Function Yes
all(), any() Functions Yes
append(), inert()
clear()
pop()
No Tuple is immutable
remove()
copy()
sort() and reverse() Methods

2.2.16 Functions Common to List and Tuple

The following list enumerates the functions of list which are also applicable to tuple:

 Repeating the elements using * operator


 Indexing
 Slicing
 Iterating through elements using for loop
 len() method to determine size
 in operator to check membership
 concatenation of two tuples using ‘+’ operator
 deleting object using ‘del’ operator
 aggregate functions such as max(), min(), sum(), count()
 sorted() function
 index() function
 Tuple comprehension
 all() and any() methods

2.2.17 List Functionality which is not applicable to Tuple


118
The following list enumerates the functions of list which are not applicable to a tuple:

 Modification of element of a tuple


 Methods for inserting or appending an element to a tuple
 Partial deletion of a tuple
 Deleting all elements using clear() method
 Deleting the element using pop() method
 remove() method for deleting a specific element
 Object cloning
 sort() and reverse() methods

2.2.18 Additional Functionality Not Supported By List

 Tuple is hashable

As shown in the following figure, tuple only supports count() and index() method and does not
support any methods which would modify the tuple as tuple is immutable.

2.2.19 Tuple Concatenation

Two tuples can be concatenated using “+” operator which creates a new tuple containing the
elements of both the tuples as shown in the following program.

119
In the above program, statement (8) will not modify the tuple ‘t’ but creates a new tuple.
On execution of the above code segment, the following output is generated.

In the above program, re-write statement (8) as shown below and re-execute the program:

t= t + (“Java”)

On execution of the above code segment, the following output is generated.

In the above program, the expression

t= t + (“Java”)
120
is interpreted as concatenation of a tuple and a string as stated earlier.

Consider the following program which concatenates two tuples using the += operator.

To convince yourself, that a new tuple is indeed generated, print the hash value of a tuple both
before and after the concatenation using __hash__() method of tuple class as shown in the
following program:

On execution of the above code segment, the following output is generated.

121
From the hash value of a tuple before and after concatenation it is clear that the original tuple is
destroyed and a new tuple with new set of elements is created.

Note: A list cannot be concatenated with a tuple.

The following Python program attempts to concatenate a tuple and a list and store the result ina
tuple.

On execution of the above code segment, TypeError is generated as shown below.

2.2.20 Deleting a Tuple in Python

Tuple being immutable, a part of it cannot be deleted. You can, however, delete the whole tuple
using ‘del’ keyword as shown in the following Program. Once the tuple is deleted it cannot be
further used in a program:

122
On execution of the above code segment, the following output is generated.

The situation is different when a tuple contains a list.

Consider the following declaration:

t = (1, 2, 3, [4, 5, 6])

Trying to modify the element at index 3 of a tuple using the following expression

t[3]=4

produces error as shown in the following program as tuple is immutable.

On execution of the above code segment, the following output is generated.

123
However, the following statement executes successfully.

t[3][0]=7

since it refers to an element of a list and list is mutable.

t = (1, 2, 3, [7, 5, 6]) is the new tuple generated on execution of the statement. This is
demonstrated in the following program:

On execution of the above code segment, the following output is generated.

On the similar lines, a list can also contain tuple as one of its elements as shown below. In the
following program, config_list is a list of three tuples containing information about operating
system, front-end and back-end. In statement(12), the element at index 2 is updated with a new
tuple which is allowed as it modified a list and not a tuple.

124
On execution of the above code segment, the following output is generated.

However, any attempt to modify a tuple contained in a list will generate a TypeError as shown
below. In the following program, config_list[2][0] refers to the first element of a tuple located at
index position 2 of a config_list.

On execution of the above code segment, the following output is generated.

2.2.21 Nested Tuples

125
Similar to lists python tuples can be nested and nested indexing can be used for accessing
elements of nested tuples.

Consider the following nested tuples.

a=((1,2,3),(4,(5,6)))

Nested tuples can be visualized as depicted in the following figure:

The above tuple consists of two elements as follows:

a[0]= (1,2,3)

a[1]=(4,(5,6))

Both the elements themselves are tuples. The tuple a[0] consists of three elements as shown
below:

a[0][0] = 1

a[0][1] = 2

a[0][2] = 3

The tuple a[1] consists of two elements as shown below:

a[1][0] = 4

a[1][1] = (5,6)

The tuple a[1][1] consists of two elements as shown below:

a[1][1][0] = 5

126
a[1][1][1] =6

To access the element six, the syntax is

a[1][1][1]

a[1]=(4,(5,6))

a[1][1]=(5,6)

a[1][1][1]=6

The following table depicts the indexing used for accessing different elements of a tuple :

Element Indexing
1 a[0][0]
2 a[0][1]
3 a[0][2]
4 a[1][0]
5 a[1][1][0]
6 a[1][1][1]
The following program demonstrates accessing the elements of a nested tuple.

On execution of the above code segment, the following output is generated.

127
sort() reverse() methods are applicable to tuple, since these methods change the order of
elements in a tuple which implies modification of a tuple. However sorted() method is supported
by tuple class since it creates and returns new tuple containing the elements of original tuple in a
sorted order while keeping the original tuple intact as demonstrated in the following program:

On execution of the above code segment, the following output is generated.

2.2.22 Converting An Iterable to a Tuple

tuple() method can be used for converting any iterable such as string, list, set, dictionary (to be
discussed) to a tuple. But once the list is converted into a tuple, it cannot be modified further.

The following Python program converts a string to a tuple. The types of the variable ‘s’ are
displayed before and after conversion.
128
On execution of the above code segment, the following output is generated.

2.2.23 Aggregate Functions

All aggregate functions such as max(), min(), sum(), count() discussed in list are also applicable
to a tuple.

2.2.24 A Note on Choice of Proper Data Structure (a list or a tuple?)

Coding standards dictate that tuples must be used for storing heterogeneous sequence of objects
which are commonly accessed through tuple unpacking or indexing and lists must be used for
storing homogeneous sequence of objects which are accessed by iterating through the list.

Since tuple is hashable while list is not, there is a performance boost in using tuples compared to
lists.

2.3 Python Dictionary

Python dictionary is an unordered collection of mutable elements in the form of a key value pair
which is optimized for searching based on a key. To create a dictionary separate keys from
values with a colon(:), and a pair from another by a comma(,). Finally, put it all in curly braces.
Key is unique which can contain multiple values.

The general form of Python dictionary is shown below:

d = {K1:V1, K2:V2,. . . . . ,KN:VN }

129
where, K1, K2,. . . . . ,KNare keys and V1, V2,. . . . . ,VNare corresponding values.

The data types which qualify as keys must be immutable types which can be one of strings,
numbers and tuples while any data type can be a value.

Few salient features of dictionary are enumerated below:

 Dictionaries play the role of associative arrays in other languages.


 Dictionaries are indexed by unique keys of immutable type.
 Each key can be associated with one or more values of any type.
 Dictionary is an unordered collection of elements.
 Dictionary cannot be sliced.
 Dictionary is stored as hash table
 Dictionary is mutable which means the elements of dictionary can be changed after the
dictionary is created New key-value pairs can be added or existing values can be
modified.
 The elements of a dictionary are indexed using keys.
 Dictionary is iterable and hence enables to iterate through it’s elements employing
optimized for loop.
 Dictionary can dynamically grow and shrink
2.3.1 Creating Dictionary

There are numerous ways of creating dictionary. Few important once are presented here:

2.3.1.1 Creating Empty Dictionary

The syntax to create an empty dictionary is shown below:

d={}

2.3.1.2 Creating Non-empty Dictionary

The following Python program demonstrates creating a dictionary with two keys, “os” and
“language” with the corresponding values “windows” and “python”, repsectively.

On execution of the above code segment, the following output is generated.

130
As seen from the output generated on execution of the above program, the variable ‘d’ is of type
‘dict’,

When duplicate keys are encountered during creation of a dictionary, no error message is
generated but the last assignment overwrites all preceding assignments as demonstrated in the
following program:

A single key can point to multiple values as demonstrated in the following program:

On execution of the above code segment, the following output is generated. In the following
program, the last element overwrites the key “opensource_languages” of all preceding elements
with a value ‘ruby’.

For assigning multiple values to a single key place all the values in a list and assign the list to a
key as shown in the following program:

131
On execution of the above code segment, the following output is generated.

2.3.1.3 Creating Dictionary Using dict class Constructor

dict class supports a constructor for creating a dictionary as shown in the following program:

On execution of the above code segment, the following output is generated.

2.3.1.4 Creating Dictionary from a List

For creating a dictionary from a list, dict() function is used and it is necessary that each element
of a list contains a tuple enclosing a key-value pair as shown below:

On execution of the above code segment, the following output is generated.

132
In the above program, dictionary is created from a list of tuples roll nos of the students as keys
and the corresponding names as the values. If the list does not contain a key-value pair in the
form of tuple elements, TypeError is generated as shown in the following program:

On execution of the above code segment, the following output is generated.

2.3.1.5 Creating a Dictionary Using fromkeys() Method of dict class

For the quick creation of a dictionary consisting of keys all of which are initialized to a single
default value, use fromkeys() method of dict class which has the following general syntax:

{}.fromkeys([K1, K2,. . . . ,KN],V)

Using the above syntax the following dictionary is created:

{K1:V, K2:V, . . . . ,KN:V}

In the following Python program, a dictionary with the keys ‘Max1’, ‘Max2’, ‘Max3’ and
‘Max4’, each of which is initialized to 100 using fromkeys() method of dict class is created.

133
On execution of the above code segment, the following output is generated.

134
2.3.2 Looking Up Dictionary - KeyError

The general syntax for searching a value in a dictionary corresponding to the specified key is

d[“K”]

The above expression returns value(s) corresponding to the key, K, if present, otherwise
KeyError is generated as demonstrated in the following program:

On execution of the above code segment, the following output is generated.

In the above program, the dictionary d does not contain a key with a value 6. Hence a KeyError
is generated. There are few approaches available for getting rid of this error.

The safe way to retrieve a value, if you have doubt about the existence of a corresponding key is
to use the key membership testing using ‘in’ operator as demonstrated in the following program.
The following program uses ‘in’ operator to check whether specified key is present in the
dictionary or not, if it is present, the corresponding value is printed else the message ‘key is
missing’ is printed.

135
On execution of the above code segment, the following output is generated.

The second approach is to use the method get() of dict class. The get() method returns the value
if the corresponding key is present, otherwise returns ‘None’, if the key does not exist. The
following Python program prints the value of a specified key only if the key is present in the
dictionary. The presence of a key is checked using get() method of ‘dict’ class.

136
On execution of the above code segment, the following output is generated.

2.3.3 Checking the Existence of a Key Using has_key() Method of dict class

An alternate approach to safely retrieve a value if a key exists is by using has_key() method of
dict class which returns True if the key passed to it exists, otherwise returns False.

Note: has_key has been eliminated in Python 3.x

2.3.4 setdefault() Method of dict class

This is another handy method which is similar to get() method in its functionality. get() method
returns the value of a key passed to it as an argument, if the key exists, otherwise returns ‘None’.
setdefault() method takes two parameters of which the first parameter is a key like get() method
and the second parameter is a default value. setdefault() method works as follows: It checks
whether the first parameters specified as a kay is present in the dictionary, if present it returns the
corresponding value, otherwise creates a new key with the specified default value as
demonstrated in the following program:

137
On execution of the above code segment, the following output is generated.

In the above program, the dictionary ‘d’ is initially created in statement(7) with 5 keys ranging
from 1 to 5. In statement(9), setdefault() method of ‘dict’ class is invoked to retrieve the value of
a key 6. Since the key does not exist in a dictionary, a new key-value pair (6,’NoName’) is
created and inserted in a dictionary and setdefault() method returns the value of a newly inserted
key.

In the second case, in statement(13), setdefault() method of ‘dict’ class is invoked again to
retrieve the value of a key 5. Since the key now exists in a dictionary setdefault() method simply
returns its value.

138
2.3.5 Retrieving List of Keys and Values

By default for loop iterates over all the keys of a dictionary, hence both the code segments shown
below serve the same purpose.

for key in d:
print(key)
and

for key in d.keys():


print(key)
In the above code call to a method keys() is redundant as , both d and d.keys() are identical as
demonstrated in the following Python program:

On execution of the above code segment, the following output is generated.

139
values() method of ‘dict’ class returns a list containing all values present in a dictionary as shown
in the following program:

On execution of the above code segment, the following output is generated.

140
Finally, items() method returns a list of tuples containing key-value pair as shown in the
following program:

On execution of the above code segment, the following output is generated.

141
2.3.6 Three Distinct Methods for Printing Key-Value Pairs of a Dictionary

2.3.6.1 Method 1: By iterating over keys

In this method a for loop can be used for iterating through the keys of a dictionary retrieved
using keys() method of a dict class and using index operator for retrieving the corresponding
values as demonstrated in the following program:

On execution of the above code segment, the following output is generated.

2.3.6.2 Method 2: By iterating over values

In this method a for loop can be used for iterating through the values of a dictionary retrieved
using values() method of a dict class as demonstrated in the following program:

On execution of the above code segment, the following output is generated.

142
2.3.6.3 Method 3: By iterating over items

In this method a for loop can be used for iterating through the elements of a dictionary retrieved
using items() method of a dict class and unpacking the tuple containing a key-value pair in a set
of variables k and v, respectively as demonstrated in the following program:

On execution of the above code segment, the following output is generated.

2.3.7 Formatted Printing

The % operator can be used as a place holder for substituting the values from a dictionary
depending on the specified keys. The syntax for specifying a placeholder is:

%(key)s, if the value associated with a key k is of type string

%(key)d, if the value associated with a key k is of type int.

In the following program


143
On execution of the above code segment, the following output is generated.

2.3.8 Python Dictionary Comprehension

Similar to list comprehension, Python supports dictionary comprehension as a concise way of


creating a dictionary. The main difference is list contains only values whereas dictionary
contains a key-value pair which are separated with a colon. Hence in generating a dictionary
using comprehension both key and values must be appropriately generated as demonstrated in
the following program:

On execution of the above code segment, the following output is generated.

Without dictionary comprehension, the code is:

144
On execution of the above code segment, the following output is generated.

2.3.9 Modifying a Dictionary

Since dictionary is mutable, new elements can be added to the dictionary or existing elements
can be modified. The general syntax to achieve this is shown below:

d[‘K’]=V

where K and V correspond to the key-value pair.

If the key, K is already present in the dictionary, it’s value is updated to ‘V’, otherwise new
element with the key-value pair (K,V) is added to the dictionary as shown in the following
example:

145
In the above program, in statement(7) a dictionary with keys, ‘name’ and ‘elective’ is created. In
statement(9) a new key with the name ‘marks’ and value 78 is created which is later updated in
statement(11). On execution of the above code segment, the following output is generated.

2.3.10 Deleting Elements From a Dictionary

dict class supports the following methods for deleting elements:

Method Name Description


pop() pop() method accepts the key of the item to be deleted and returns the
corresponding value.
clear() clear() method deletes all the elements of a dictionary in a single call.
popitem() popitem() removes and returns an arbitrary item from a dictionary in
versions prior to 3.7 and last inserted item in versions later than 3.7.
del keyword
The usage of del keyword is two-fold:

 for deleting an element of a dictionary with a specified key


 for deleting the entire dictionary

146
2.3.11 Membership Testing in a Dictionary

The membership testing applies to dictionary keys and not dictionary values. The keyword ‘in’
used for checking whether the specified key is present in a dictionary or not as demonstrated in
the following program:

On execution of the above code segment, the following output is generated.

In the above program, in statement(8), since 4 is present as a key in a dictionary, the


corresponding value is printed. Since ‘Maya’ is not a key but a value corresponding to a key 2, if
condition evaluates to false and the string ‘Does not Exist’ is printed.

2.3.12 Concatenation of Two Dictionaries – update() Method of dict class

It accepts a single parameter a dict object and appends its elements to invoking dict object. The
following program demonstrates the concatenation of two dictionaries:

147
On execution of the above code segment, the following output is generated.

As seen from the output generated on execution of the program, update() method of a ‘dict’ class
concatenates the elements of dictionary passed to it as an argument to the dictionary object
invoking the method and does not return anything (print(d3) prints None)

2.3.13 list() Method

The list() method accepts a dictionary as its single parameter and return a list containing all keys
in a dictionary as demonstrated in the following program:

On execution of the above code segment, the following output is generated.

148
2.4 Set in Python

A set is an unordered collection of elements. Every element of a set is unique (no duplicates) and
immutable. However, the set itself is mutable. We can add or remove elements from it. The
common application of sets is to perform mathematical set operations like union, intersection,
symmetric difference etc.

Some salient features of set are enumerated below:

 Set is unordered, hence no duplicates are allowed.


 Set can contain heterogeneous elements.
 Set does not support indexing and slicing since set is unordered
 Elements of set are immutable, i.e. the set elements cannot be modified once the set is
created.
 Set is mutable, i.e. set can dynamically grow and shrink by adding new elements and
deleting existing elements.
 Set is iterable, hence for loop can be used for iterating through the elements of a set.
 Set does not have insertion order and the order in which elements are displayed is
unpredictable.
 The common application of sets is to perform mathematical operations such as union,
intersection, difference, symmetric-difference etc.

2.4.1 Creating Set in Python

A set is created by placing all its elements inside a pair of curly braces {}, separated by comma.

2.4.1.1 Creating Empty Set

Creating empty set can be quite tricky, since {} is interpreted as empty dictionary. Hence for
creating empty set use default constructor of the set class, set() as demonstrated in the following
program:

On execution of the above code segment, the following output is generated.

149
2.4.1.2 Creating Non-Empty Set

The syntax for creating a non-empty set is:

s = {e1, e2, e3, . . .,eN}

where e1, e2 …. eN are elements of a set.

The following Python program creates and prints a set:

On execution of the above code segment, the following output is generated.

Set is like a dictionary with keys but no values, and are both implemented using a hash table.A
set can contain only immutable element as its member, mutable elements such as list and
dictionary cannot be members of set. Since the immutable elements are hashable are used for
generating keys implicitly. Using any mutable element as a member of a set generates a
TypeError with the message “unhashable type” as shown below:

150
In the above program, in statement(12), the first element of a set s is a list l. Since list is mutable,
it is not allowed as a set member.

On execution of the above code segment, the following output is generated.

The elements of a set can be any one of primitive data types, or tuples which are immutable,
hence hashable, but mutable elements such as list, set or dictionary can not be the members of a
set. In the following program, the set s contains two elements of type tuple.

On execution of the above code segment, the following output is generated.


151
2.4.2 Nesting of Set Elements

Since set is unhashable, nesting of sets is not allowed for the same reason stated above. Trying to
nest one set inside another set generates TypeError with the message “unhashable type” as
shown in the following program:

On execution of the above code segment, the following output is generated.

2.4.3 Set Elements are Immutable

Any attempt to modify an element of a set generates TypeError with the message “set object
does not support item assignment” as demonstrated in the following program:

152
On execution of the above code segment, the following output is generated.

2.4.4 Creating a Set Using Set Constructor

The set class contains both a default and a parameterized constructor for creating empty and non-
empty sets. The syntax for creating a set using set class constructor is shown below:

Syntax:

set({ele1, ele2, ele3, . . ., eleN})

The constructor accepts an iterable as its single parameter. The following Python program
demonstrates creating a set of numbers using set class constructor:

On execution of the above code segment, the following output is generated.

153
A set class constructor also accepts a string as an argument, iterates through a string and
constructs a set containing individual characters of a string as demonstrated in the following
program:

The no. of elements rendered to a set is equal to the length of a string. On execution of the above
code segment, the following output is generated.

The set class constructor also accepts list and if the list contains any duplicate elements, those are
eliminated before creating a set as demonstrated in the following program:

On execution of the above code segment, the following output is generated.

154
2.4.5 Using range() Function for Constructing a List

Similar to other collection types, range() function can be used for constructing a set by iterating
through sequence of numbers generated by range() function and using add() method of set class
as demonstrated in the following program:

On execution of the above code segment, the following output is generated.

2.4.6 Set Does Not Support Duplicate Elements

If the set is created with duplicate elements, no error message is generated, the duplicate
elements are simply dropped as shown in the following program:

In the above program, the set s contains duplicate elements 4 and 12, only one copy of all
duplicate elements is retained and also insertion order of elements and print order of elements is
different as can be seen from the output generated on execution of the program:

155
2.4.7 Set Does Not Maintain Insertion Order

The following Python program creates two sets, sorted and unsorted in statements (8) and (10),
respectively. When the set is sorted, the elements are printed in sorted sequence. On the other
hand when the set is unsorted, the print order cannot be predicted as demonstrated in the
following program:

On execution of the above code segment, the following output is generated.

2.4.8 Repetition Operator - *

Since set is unordered and duplicates are not allowed in a set, the repetition operator, * is
insignificant in a set.

2.4.9 Concatenation Operator

Concatenation operator, cannot be used for concatenating two sets. Attempting to do so will
generate TypeError with the message “unsupported operand type(s) for +: 'set' and 'set'” is
generated as shown in the following program:
156
On execution of the above code segment, the following output is generated.

A trick is to first convert the sets into lists using the conversion function, concatenate the list
using ‘+’ operator and then convert the concatenated list back to set using conversion function
again as shown below:

set(list(s1) + list(s2))

This is demonstrated in the following program:

On execution of the above code segment, the following output is generated.

157
2.4.10 Indexing

Since set is unordered, it does not support indexing. An attempt to access the elements using
index operator, [], generates TypeError with the message “set object does not support indexing”
as shown in the following program:

On execution of the above code segment, the following output is generated.

2.4.11 Testing Set Membership Using ‘in’ Operator

The syntax for checking whether the element ‘ele’ is present in the set ‘s’ or not, use the
following syntax:

if ‘ele’ in s

The above statement evaluates to True if the element ‘ele’ is present in the set ‘s’, otherwise
evaluates to False.

The following Python program checks whether the number accepted from the end user is present
in the set, s or not:

158
On execution of the above code segment, the following output is generated.

2.4.12 Determining Size of a Set

len() function is used for determining the size of the set as demonstrated in the following code
segment:

159
On execution of the above code segment, the following output is generated.

2.4.13 Iterating through the Elements of a Set Using for Loop

Similar to other collections, for loop can be used for iterating through the elements of s set as
demonstrated in the following program:

On execution of the above code segment, the following output is generated.

160
2.4.14 Sorting and Reversing a Set

Since the order of the elements is insignificant in a set, sorting and reversing the elements do not
create new sets. For example, the set {1, 2, 3} is same as {2, 1, 3} which is again same as {3, 2,
1} and so on. Hence sorting and reversing elements of a set do not carry an significance.

However, sorted() and reversed() methods are supported, but both of them return lists and not
sets as demonstrated in the following program:

On execution of the above code segment, the following output is generated.

161
On execution of the above code segment, the following output is generated.

2.4.15 Checking Set Equality Using ‘is’ and == operators

Similar to list and tuple ‘is’ and == operators are applicable to a set for testing object identity and
object equality, respectively, as demonstrated in the following program. In the program given
below, three set references s1, s2 and s3 are created. The set references s1 and s2 point to the
different objects having same elements whereas the set references s1 and s2 point to the same set
object. Hence the following statements become valid:

 s1 is not s2
 s1 is s3
 s1 is equal to s2
 s1 is equal to s3

162
On execution of the above code segment, the following output is generated.

163
2.4.16 Operations on sets

A set element is immutable but a set is mutable. Hence a set class supports the methods for
adding and removing elements from a set.

2.4.16.1 Adding Element to a Set

A single element can be added to set using add() method as demonstrated in the following
program:

164
On execution of the above code segment, the following output is generated.

If the set is not sorted, the position where the element is inserted will be completely arbitrary as
demonstrated in the following program:

On execution of the above code segment, the following output is generated.

165
To add more than one element to a set use update() method(). The update() method accepts a
single parameter, the list, tuple or a set containing the elements to be added to the set.The
update() method has a general syntax:

s.update(it)

where it is an iterable such as a list, tuple or a set.

The following program demonstrates adding the elements stored in a list to a set s.

On execution of the above code segment, the following output is generated.

String can also be passed as a parameter to an update() method. In this case, the string is iterated
over and individual characters are added to the set. The following Python program demonstrates
invoking overloaded update() method by passing list, tuple, set and a string as an argument.

166
On execution of the above code segment, the following output is generated.

Notice the order in which characters of a string “Python” are added to a set.

2.4.16.2 Deleting an Element From a Set – remove() and discard() Methods

The remove() and discard() methods are used for deleting a single element from the set. The
following program demonstrates the use of remove() method:

167
On execution of the above code segment, the following output is generated.

The following Python program demonstrates the use of discard() method.

On execution of the above code segment, the following output is generated.

2.4.17 Difference Between remove() and discard() method

168
If the item to be removed does not exist, then remove() will generate KeyError while discard()
just ignores it as demonstrated in the following program:

In the above program, the element 6 is not present in a set s. On execution of the above code
segment, the following output is generated.

In the above program, replace remove() method with discard() method and re-execute the
program.

On execution of the above code segment now, the following output is generated. As revealed by
the generated output, the discard() method does not generate KeyError even if the element to be
deleted is not present in the set. It simply ignores and proceeds.
169
2.4.18 Removing An Element From a Set Using pop() Method

remove() and discard() methods simply remove an element from the list but do not return any
value as demonstrated in the following program:

On execution of the above code segment, the following output is generated.

For removing and returning an element use pop() method. It does not accept any arguments. The
element popped is completely arbitrary since set is unordered.

170
On execution of the above code segment, the following output is generated.

2.4.19 Deleting All Elements of a Set – clear() Method

clear() method is used for deleting all elements from a set as demonstrated in the following
program:

The clear() method does not delete set reference which can be used again for inserting new
elements using add() or update() methods. On execution of the above code segment, the
following output is generated.

171
2.4.20 Deleting a Set – del Operator

Since set does not support indexing and slicing, del operator can only be used for deleting the
entire set and not a single element or a range of elements of a set. The following program
demonstrates deleting a set using del operator:

On execution of the above code segment, the following output is generated.

2.4.21 Deep Copying Using copy() Method

set class supports a copy() method for cloning a set. copy() method creates a new set instance
and return the reference. In the following program, s1 and s are two independent set class
instances which can be manipulated separately. Any changes made by s and not visible to s1 and
vice versa.

172
On execution of the above code segment, the following output is generated.

In the above program, replace the statement(9) with the following statement and re-execute the
program:

s1= s

Now, s and s1 are two distinct references pointing to the same set object. Thus, any changes
made by the reference s to a set object are visible to a reference s1 and vice versa.

173
On execution of the above code segment, the following output is generated.

2.4.22 Converting An Iterable to a Set

se4() method can be used for converting any iterable such as string, tuple, list, dictionary to a set.
However, converting one collection type to another has an associated cost. For example, consider
174
converting a list to a set. These are two contrasting collection types. On one hand, list is an
ordered collection type where duplicates are allowed, while on the other hand set is an unordered
collection type where duplicates are not allowed. Hence when a list is converted into a set, all
duplicate elements in a list are lost and the order as well.

The conversion of a list to a set is demonstrated in the following program:

On execution of the above code segment, the following output is generated.

2.4.23 Aggregate Functions

All aggregate functions such as max(), min(), sum() discussed in list are also applicable to a set
as demonstrated in the following program:

On execution of the above code segment, the following output is generated.

175
2.4.24 Set Operations

All mathematic set operations are applicable to set instances. Following table depicts the various
operations supported by a set class:

Set Operation Method Equivalent


Expression
Union of sets A and B A.union(B) which is same as A | B
B.union(A)
Intersection of sets A and B A.intersect(B) which is same as A & B
B.intersect(A)
Difference of sets A and B A.difference(B) which is not A – B
same as B.difference(A)
Symmetric Difference of sets A A.symmetric_difference(B) is A^B
and B same as
B.symmetric_difference(A)
difference_update Updates the calling set with the
difference of calling set and set
passed as argument
intersection_update() Updates the calling set with the
intersection of calling set and set
passed as argument
Symmetric_difference_update() Updates the calling set with the
symmetric difference of calling
set and set passed as argument
2.4.24.1 Union Operation

Union of two sets A and B is a set containing elements from both the sets where the elements
common to both the sets are considered only once. Mathematically, union operation can be
represented as shown below:

A U B = {x, x ϵ A OR x ϵ B}

Union of two sets can also be performed using | operator as demonstrated in the following
program:

176
On execution of the above code segment, the following output is generated.

2.4.24.2 Intersection Operation

Intersection of two sets A and B is a set containing elements common to the two sets A and B.
Mathematically, union operation can be represented as shown below:

A U B = {x, x ϵ A AND x ϵ B}

Intersection of two sets can also be performed using & operator as demonstrated in the following
program:

177
On execution of the above code segment, the following output is generated.

Union and intersection operations are commutative, i.e.

A U B = B U A and

A∩B=B∩A

This is demonstrated in the following program:

178
On execution of the above code segment, the following output is generated.

2.4.24.3 Set Difference

Difference of two sets A and B is a set of elements present in A and not present in B and is
denoted by notation -. Mathematically, union operation can be represented as shown below:

A - B = {x, x ϵ A AND x ∈ B}

Difference of two sets can also be performed using - operator as demonstrated in the following
program:

179
On execution of the above code segment, the following output is generated.

2.4.24.4 Set Symmetric Difference

Symmetric difference of two sets A and B is a set of elements present in either A or B but not in
both and is denoted by notation ^. Mathematically, union operation can be represented as shown
below:

A ^ B = {x, x ∈ A OR x ∈ B and x ∈ 𝐴 ∩ 𝐵}

An alternate definition of A ^ B is

A ^ B = (A-B)U(B-A)

Symmetric difference of two sets can also be performed using ^ operator as demonstrated in the
following program:

180
On execution of the above code segment, the following output is generated.

2.4.25 difference_update Method of set Class

The difference() method of a set class returns a new set containing the elements of a calling set
which are not present in the set passed to it as argument. It does not modify either set A or set B.
In contrast to this difference_update() method of set class modifies the calling set with the set
difference. Hence

A.difference_update(B)

updates the set A with (A-B) and returns nothing (None).

This is demonstrates in the following program. For comparison, difference() method of set class
is also demonstrated.

181
On execution of the above code segment, the following output is generated.

182
Similarly, B.difference_update(A) updates the set B with (B-A) and returns nothing. The
following points should be kept in mind:

 A.difference(B) does not modify A or B and returns (A-B).


 A.difference_update(B) updates A with (A-B) and returns nothing
 B.difference_update(A) updates B with (B-A) and returns nothing

183
2.4.26 intersection_update Method of set Class

Similar to difference_update method, the intersection_update() method of set class updates the
invoking set with the intersection of two sets. Thus,

A.intersection_update(B) updates A with A ∩ B.

B.intersection_update(A) updates A with B ∩ A.

This is demonstrated in the following program:

On execution of the above code segment, the following output is generated.

184
2.4.27 Symmetric_difference_update Method of set Class

Similar to difference_update and intersection_update() methods of set class,


symmetric_difference_update() method updates the invoking set with the symmetric difference
of two sets. Thus,

A.symmetric_difference_update(B) updates A with (A – B) U (B – A).

B.symmetric_difference_update(A) updates A with (A – B) U (B – A).

This is demonstrated in the following program:

185
On execution of the above code segment, the following output is generated.

186
2.4.28 isdisjoint() Method of set Class

isdisjoint() method returns True if the two sets have no element in common, otherwise returns
False as demonstrated in the following program:

187
On execution of the above code segment, the following output is generated.

188
2.4.29 issubset() asnd issuperset() Method of set Class

These are two complementary methods of set class. issubset() method returns True if the
invoking set is a subset of a set passed as an argument, otherwise returns False. Similarly,
issuperset() method returns True if the invoking set is a superset of a set passed as an argument
as demonstrated in the following program:

On execution of the above code segment, the following output is generated.

issubset() is False does not mean issuperset() is True, since A may contain the elements which
are not present in B and B may contain the elements which are not present in A. In such a case
neither A is a subset of B nor B is a subset of A. Thisis demonstrated in the following program:

189
On execution of the above code segment, the following output is generated.

2.4.30 Python Frozen Set

As the name implies, frozen set is an immutable version of a set. Since set is mutable, it is not
hashable and hence cannot be used as a key of a dictionary where as a frozen set can be. A set
can be converted into a frozen set using frozenset() method, but once converted, all the methods
of set class which modify it, such as add(), clear(), update() cease to be applicable to a frozen set.
All the set operations and copy() method can also be applied to a frozen set.

Similar to tuples which are mutable version of sets, a frozen set is a mutable version of a set. The
following figure depicts the methods which are applicable to frozen set.
190
In the above program, F is a frozen set of A. Statement(10) in the above program attempts to add
an element 6 to a frozen set. On execution of the program, AttributeError with the message
“frozen set has no attribute add” is generated as shown below:

2.4.31 Conversion Between Collections in Python

191
There are methods available for converting from one collection type to another. But since each
collection type is unique in its functionality, after conversion, the new collection type created
might attain new properties and loose some existing properties.

The following figure depicts the conversion between collection types. Python supports list(),
tuple(), dict() and set() for converting from any collection type to list, tuple, dictionary and set,
respectively.

192
2.4.32 Converting a List to a String

A list can be converted to a string by using ‘’.join() method of str class which glues together all
strings in thelist and return them as a single string as demonstrated in the following program:

In the above program, fullname_list is a list of three elements corresponding to first name,
middle name and last name. join() method is used in statement(9) for converting list to a string.
On execution of the above code segment, the following output is generated.

If the list contains integers, you should convert the elements to strings before performing the join
on them as demonstrated in the following program:

In the above program, in statement(9) an iterator is used for converting each element of num_list
to a string before joining together into a num_string using join() method of a str class. On
execution of the above code segment, the following output is generated.

193
The following program demonstrates converting a tuple and a set into a string using join()
method of a string class.

On execution of the above code segment, the following output is generated.

Observe the string generated in the two cases. Since set is unordered, the order in which the
elements are joined cannot be predicted.

194
2.4.32.1 Converting a List to a Tuple

A list can be changed to a tuple in Python by using the tuple() function. A mutable, non-
hashablelist passed to the function is morphed into an immutable, hashable tuple as demonstrated
in the following program:

On execution of the above code segment, the following output is generated.

2.4.32.2 Converting List to a Dictionary

Since dictionary contains a key-value pair, two lists one hosting a set of keys and second hosting
corresponding values is needed for converting a list into a dictionary as demonstrated in the
following program:

195
On execution of the above code segment, the following output is generated.

The same is applicable to a tuple as demonstrated in the following program:

On execution of the above code segment, the following output is generated.

196
2.4.32.3 Converting List to a Set

A set is an unordered collection of unique items which means that any duplicates present in the
original list will be lost once it is converted in to a set, also the order of the list elements might
change.

Converting a list into a set is as simple as wrapping it into a set() function as demonstrated in the
following program:

On execution of the above code segment, the following output is generated.

2.4.32.4 Converting tuple to Other Collection Types

The following program demonstrates converting tuple to a list, set and dictionary. Among these
converting tuple to a dictionary is extremely challenging since tuple contains elements whereas
dictionary contains a key-value pair. Hence a tuple must render properly the set of keys and
values required for creation of a dictionary. Two cases arise:

197
Case 1:

tuple contains a sequence of tuples with a key-value pair as shown below:

t=(('os','windows'),('language','python'))

In this case a dictionary can be created by iterating over the elements of a tuple using for loop as
shown in the following code snippet:

d=dict((x,y) for x, y in t )

Case 2:

tuple contains two elements, first element is a tuple containing all keys and second element is a
tuple containing all values as shown below:

t=(('os','language'),('windows','python'))

The above tuple contains only two elements, the first element t[0] contains keys and the second
element t[1] contains corresponding values. The range() function is used for extracting the
elements in ith index position in t[0] and t[1] and a dictionary is created by iterating over the
elements of t[0] and t[1] as shown below:

d=dict((t[0][i],t[1][i]) for i in range(0,2) )

The following program demonstrates the same:

198
On execution of the above code segment, the following output is generated.

As revealed from the output generated on execution of the above program, the same output is
generated in both the cases discussed above.

The following table summarizes the salient features of collections in Python:

Ordered Heterogeneous Mutable Iterable Hashable Duplicates Indexed


List Y Y Y Y N Y Y
Tuple Y Y N Y Y Y Y
Dictionary N Y Y Y Y N Y
Set N Y Y Y N N N

2.4.33 Salient Features of Collection Types:

Salient Features of the Collection are enumerated below:

 All collections can contain heterogeneous elements and are iterable.


 Tuple is the only immutable collection type.
 Set is the only collection type which does not support indexing.
 List and tuple are ordered and hence indexed whereas set is unordered and un-indexed.
 List and tuple allow duplicate elements whereas set does not and dictionary does not
allow duplicate keys.

199
200
Chapter 3
Setting Up Development Environment
3.1 Introduction to Anaconda
Anaconda is a free and open-source distribution of the Python and R programming languages for
scientific computing (data science, machine learning applications, large-scale data processing,
predictive analytics, etc.) which aims to simplify package management and deployment.

Environments and package versions are managed by the package management system referred to
as ‘conda’.

3.2 Installation of Anaconda

Anaconda can be downloaded by visiting the official website of Anaconda by entering the
following URL in the address bar:

https://www.anaconda.com

or by visiting Anaconda cloud

https://anaconda.org/

The following page is displayed:

201
Click on “Download Anconda” menu option.

Scroll down and click on “Python 3.7 version” Download button. The name of the executable
file is

Anaconda3-5.3.1-Windows-x86_64.exe

Double-click on the executable to install it.

202
Click on “Next’ button.

Click on “I Agree” button.

203
Click on “Next” button.

204
Click on “Install” button to begin Anaconda installation as shown below:

205
When prompted for installing Microsoft Visual Studio Code, click on “Skip” button.

206
Click on “Finish” button.

Enter the details in sign up form and click on “Sign Up!” button.

Click on “Sign In” menu option and enter the authentication details.

207
On successful authentication, the following window is displayed:

Hands/on with Anaconda


You can work with Anaconda in two modes:

1. On-line mode by signing up with Anaconda cloud.


2. Off-line mode.

208
3.3 Working with Anaconda in Off-line Mode

In the search box, enter the search string “anaconda”. Anaconda prompt and anaconda navigator
appear as shown below:

Click on “Anaconda Prompt”. The following command window is displayed:

3.4 Environment in Anaconda

209
A conda environment normally comprises of a single version of Python and R along with some
packages.

3.5 Creating Environment in Anaconda

For creating a new environment enter the command:

conda create –n ds python=3.5

Press ‘y’ to continue.

210
The environment with the name “ds” is created and ds folder is created under D:\pgn\envs as
shown below:

3.6 Activating Environment in Anaconda

Enter the following command for activating the environment created above:

activate ds

After activating the environment all the commands will be applicable to the selected
environment.

3.7 Deleting Environment in Anaconda

Enter the following command for deleting the environment created above:

conda remove ds

3.8 Exporting Environment in Anaconda

On many occasions it is required to port an environment from one machine to another. This can
be achieved using pip command (Python Package Manager). Enter the following command for
creating the text file for exporting the environment created above:

pip freeze <textfile_name>

3.9 Importing Environment in Anaconda

211
Enter the following command for importing the environment on a remote machine using the
textfile created above:

pip install <textfile_name>

3.10 Launching Anaconda Navigator

In the search box, enter the search string “anaconda”. Anaconda prompt and anaconda navigator
appear as shown above. Select “Anaconda Navigator”.

The following window is displayed:

Open “Applications on” drop-down list. There are two entries in the list. Base (root) which is
created by default and ds, which is created above. Select ‘ds’.

212
213
3.11 Installing Spyder from Command-Line.

Spyder is a free integrated Development Environment (IDE) that comes with anaconda which
includes editing, testing and debugging in a single GUI. Spyder also supports intelliscence
though introspection or reflection.

Spyder is used here as a python editor. For installing spyder from command-line, enter the
following command

pip install spyder

After successful installation, enter the following command to launch spyder:


spyder3

The following window is displayed.

214
The window is divided into two panes. The left pane is the editor where Python code is written.
The right pane is a console window which displays the output generated on execution of the
code.

3.12 Spyder Toolbar

Spyder toolbar has common IDE operations pertaining to

 File operations
 Code debugging
 Executing Code

Also, hot keys or keyboard shortcuts are available for performing various tasks quickly.

The following table depicts various functions keys used for performing some common tasks:

Function Key Task Performed


F5
Run File
F6 Run again last file
F9
Run current line or a selection
Ctrl+F5 Debug File
215
Ctrl+F10 Run current line
Ctrl+F11 Step into method or function of current line
Ctrl+Shift+F11 Run until current function or method returns
Ctrl+F12 Continue execution until next break point
Ctrl+Shift+F12 Stop Debugging

3.13 Writing Python Program in Spyder


 Launch Spyder3 from command-line and open ‘File’ menu as shown below:

 Select the menu option File → New File from main menu.
 Enter the following line in the editor pane.

Print(“Hello Python”)

To execute the code use one of the following options:

 Select ‘Run’ option from the main menu.


 Press ‘F5’ function key
 Place the cursor on the line and select the tool ‘Run Selection’ or press ‘F9’ function
key.

The output is displayed in the console window as shown below:

216
217

View publication stats

You might also like