Professional Documents
Culture Documents
Python With Spyder An Experiential Learning Perspective
Python With Spyder An Experiential Learning Perspective
net/publication/337414937
CITATION READS
1 8,434
2 authors:
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.
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
Print in India
ii
Python with Spyder: An Experiential
Learning Perspective
By
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.
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.
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
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
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:
2
Using triple single quotes achieves the same as shown below:
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:
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:
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.
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:
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
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:
The following Python program displays a number 11 using different base values.
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:
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:
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”.
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.
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.
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:
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:
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.
16
The above syntax can be augmented by specifying a third component a step value as shown
below:
l[start:end:step]
The following Python program uses a step value to extract the characters at odd and even index
positions in a string l.
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:
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.
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
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.
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
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.
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:
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’.
As seen from the output generated on execution of the program, the variable result evaluates to a
float type.
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.
29
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:
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.
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.
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.
34
None is a special data type in Python which means empty or non-existing.
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
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
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 = []
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.
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.
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.
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:
The following Python program demonstrates creating a list of languages using list class
constructor:
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.
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)
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.
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:
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:
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:
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.
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.
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.
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).
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
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:
46
2.1.10 Accessing Multiple Contiguous Elements from a List
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.
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:
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
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.
l[start:end:step]
The following Python program uses a step value to extract the elements at odd and even index
positions in a list l.
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.
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:
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:
55
In the following Python program, append() method is used for appending the list
‘more_even_list’ at the end of ‘even_list’.
As seen from the output generated on execution of the above program, the whole list is appended
at the end of ‘even_list’.
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:
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
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:
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:
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.
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:
61
On execution of the above code snippet, the following output is generated:
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:
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:
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:
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:
67
In general for deleting the elements at the indices i1,i2,i3,. . .in, the list to be constructed is:
Note: The list class methods append(), extend(), insert(), remove(), pop() modify the original list
and do not return the modified list.
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’.
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.
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:
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:
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:
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.
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:
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.
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:
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.
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:
80
2.1.31 Nested List Comprehension
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.
matrix = [[1,2,3],[4,5,6],[7,8,9]]
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.
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.
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]=[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]
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]
85
On execution of the above program, the following output is generated:
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
87
2.1.33 Membership Testing in Nested Lists
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:
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)
max() and min() methods are used for finding the smallest and largest element in a list.
89
On execution of the above code snippet, the following output is generated:
List is empty
All elements of list are True
On the other hand, any() method returns True if atleast one element is True.
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:
It returns an enumerate object containing the index and value of all the items of list as a tuple.
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:
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.
A tuple is preferable to a list in situations where the elements need to be protected against
accidental modification.
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.
t = ()
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:
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:
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:
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:
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:
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.
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:
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.
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:
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.
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:
109
On execution of the above code segment, the following output is generated.
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.
t[::-1]
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.
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:
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.
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.
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:
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.
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”.
116
117
2.2.15 Operations on Tuple
The following list enumerates the functions of list which are also applicable to tuple:
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.
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”)
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:
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.
The following Python program attempts to concatenate a tuple and a list and store the result ina
tuple.
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.
Trying to modify the element at index 3 of a tuple using the following expression
t[3]=4
123
However, the following statement executes successfully.
t[3][0]=7
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 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.
125
Similar to lists python tuples can be nested and nested indexing can be used for accessing
elements of nested tuples.
a=((1,2,3),(4,(5,6)))
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
a[1][0] = 4
a[1][1] = (5,6)
a[1][1][0] = 5
126
a[1][1][1] =6
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.
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:
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.
All aggregate functions such as max(), min(), sum(), count() discussed in list are also applicable
to 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.
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.
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.
There are numerous ways of creating dictionary. Few important once are presented here:
d={}
The following Python program demonstrates creating a dictionary with two keys, “os” and
“language” with the corresponding values “windows” and “python”, repsectively.
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.
dict class supports a constructor for creating a dictionary as shown in the following program:
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:
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:
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:
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:
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.
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
139
values() method of ‘dict’ class returns a list containing all values present in a dictionary as shown
in the following program:
140
Finally, items() method returns a list of tuples containing key-value pair as shown in the
following program:
141
2.3.6 Three Distinct Methods for Printing Key-Value Pairs of a Dictionary
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:
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:
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:
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:
144
On execution of the above code segment, the following output is generated.
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
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.
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:
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)
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:
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.
A set is created by placing all its elements inside a pair of curly braces {}, separated by comma.
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:
149
2.4.1.2 Creating Non-Empty Set
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.
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.
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:
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.
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:
The constructor accepts an iterable as its single parameter. The following Python program
demonstrates creating a set of numbers using set class constructor:
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:
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:
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:
Since set is unordered and duplicates are not allowed in a set, the repetition operator, * is
insignificant in a set.
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))
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:
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.
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.
Similar to other collections, for loop can be used for iterating through the elements of s set as
demonstrated in the following program:
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:
161
On execution of the above code segment, the following output is generated.
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.
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:
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)
The following program demonstrates adding the elements stored in a list to a set s.
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.
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.
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:
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.
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:
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.
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.
All aggregate functions such as max(), min(), sum() discussed in list are also applicable to a set
as demonstrated in the following program:
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:
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.
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.
A U B = B U A and
A∩B=B∩A
178
On execution of the above code segment, the following output is generated.
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.
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.
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)
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:
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,
184
2.4.27 Symmetric_difference_update Method of set Class
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:
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.
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:
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.
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:
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.
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:
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:
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:
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.
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’.
Anaconda can be downloaded by visiting the official website of Anaconda by entering the
following URL in the address bar:
https://www.anaconda.com
https://anaconda.org/
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
202
Click on “Next’ 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:
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:
209
A conda environment normally comprises of a single version of Python and R along with some
packages.
210
The environment with the name “ds” is created and ds folder is created under D:\pgn\envs as
shown below:
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.
Enter the following command for deleting the environment created above:
conda remove ds
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:
211
Enter the following command for importing the environment on a remote machine using the
textfile created above:
In the search box, enter the search string “anaconda”. Anaconda prompt and anaconda navigator
appear as shown above. Select “Anaconda Navigator”.
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
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.
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:
Select the menu option File → New File from main menu.
Enter the following line in the editor pane.
Print(“Hello Python”)
216
217