PYTHON
FOR
DATA SCIENCE
( 3150713 )
Dr. Kruti J Dangarwala
Associate Professor & Head
Department of CSE & IT @ SVMIT
Unit 1-The Basics
Contents:
Basics of Python including data types
variables, expressions,
objects and functions.
Python data structures including
String, Array, List, Tuple, Set, Dictionary and
operations them.
Python Keywords and
Identifiers
Python Keywords
Keywords are the reserved words in Python.
cannot use a keyword as variable name, function name
or any other identifier. They are used to define the syntax
and structure of the Python language.
In Python, keywords are case sensitive.
There are 33 keywords in Python 3.7. This number can
vary slightly over the course of time.
All the keywords except True, False and None are in
lowercase and they must be written as they are. The list of
all the keywords is given below
Keywords
False await else Import pass
None break except in raise
True class finally is return
and continue for lambda try
as def from nonlocal while
assert del global not with
async elif if or yield
Code to display keywords
>>> import keyword
>>> print(keyword.kwlist)
Output:
['False', 'None', 'True', 'and', 'as', 'assert', 'async',
'await', 'break', 'class', 'continue', 'def', 'del', 'elif',
'else', 'except', 'finally', 'for', 'from', 'global', 'if',
'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or',
'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
Python Identifiers/Variables
An identifier is a name given to entities like class,
functions, variables, etc. It helps to differentiate
one entity from another.
Rules for writing identifiers
1. Identifiers can be a combination of letters in
lowercase (a to z) or uppercase (A to Z) or
digits (0 to 9) or an underscore _. Names
like myClass, var_1 and print_this_to_screen, all
are valid example.
2. An identifier cannot start with a digit. 1variable is
invalid, but variable1 is a valid name.
3. Keywords cannot be used as identifiers.
Examples
Legal variable names:
myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"
Single values
X= 1
y=1.2
Many Values to Multiple Variables
x, y, z = "Orange", "Banana", "Cherry“
print(x)
print(y)
print(z)
One Value to Multiple Variables
x = y = z = "Orange"
print(x)
print(y)
print(z)
Python Statement, Indentation
and Comments
Instructions that a Python interpreter can execute are
called statements.
Multi-line statement
In Python, the end of a statement is marked by a newline character. But
we can make a statement extend over multiple lines with the line
continuation character (\). For example:
a=1+2+3+\
4+5+6+\
7+8+9
This is an explicit line continuation. In Python, line continuation is
implied inside parentheses ( ), brackets [ ], and braces { }. For instance,
we can implement the above multi-line statement as:
a = (1 + 2 + 3 +
4+5+6+
7 + 8 + 9)
Here, the surrounding parentheses ( ) do the line
continuation implicitly.
Same is the case with [ ] and { }.
For example:
colors = ['red',
'blue',
'green']
We can also put multiple statements in a single line
using semicolons, as follows:
a = 1; b = 2; c = 3
Python Indentation
Most of the programming languages like C, C++, and
Java use braces { } to define a block of code. Python,
however, uses indentation.
A code block (body of a function, loop, etc.) starts
with indentation and ends with the first unindented
line. The amount of indentation is up to you, but it
must be consistent throughout that block.
Example:
for i in range(1,11):
print(i)
if i == 5:
break
Python Comments
In Python, we use the hash (#) symbol to start writing
a comment.
Example:
#This is a comment
#print out
Multi-line comments
#This is a long comment
#and it extends
#to multiple lines
Another way of doing this is to use triple quotes,
either ''' or """.
"""This is also a perfect example of multi-line
comments"""
Python Data Types
Built-in Data Types
Text Type: str
Numeric Types: int, float, complex
Sequence Types: list, tuple, range
Mapping Type: dict
Set Types: set, frozenset
Boolean Type: bool
Binary Types: bytes, bytearray, memoryview
None Type: NoneType
Example Data Type
x = "Hello World" str
x = 20 int
x = 20.5 float
x = 1j complex
x = ["apple", "banana", "cherry"] list
x = ("apple", "banana", "cherry") tuple
x = range(6) range
x = {"name" : "John", "age" : 36} dict
x = {"apple", "banana", "cherry"} set
x = frozenset({"apple", "banana", "cherry"}) frozenset
x = True bool
x = b"Hello" bytes
x = bytearray(5) Bytearray
x = memoryview(bytes(5)) memoryview
x = None NoneType
Operators
Python divides the operators in the following groups:
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Identity operators
Membership operators
Bitwise operators
Python Arithmetic Operators
Operator Name Example
+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus x%y
** Exponentiation x ** y
// Floor division x // y
Python Assignment Operators
Operator Example Same As
= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
&= x &= 3 x=x&3
|= x |= 3 x=x|3
^= x ^= 3 x=x^3
>>= x >>= 3 x = x >> 3
<<= x <<= 3 x = x << 3
Python Comparison Operators
== Equal x == y
!= Not equal x != y
> Greater than x>y
< Less than x<y
>= Greater than or equal to x >= y
<= Less than or equal to x <= y
== Equal x == y
Python Logical Operators
Operator Description Example
and Returns True if both statements are true x < 5 and x < 10
or Returns True if one of the statements is x < 5 or x < 4
true
not Reverse the result, returns False if the not(x < 5 and x <
result is true 10)
Python Identity Operators
Operator Description Example
is Returns True if both x is y
variables are the same
object
is not Returns True if both x is not y
variables are not the
same object
Python Membership Operators
Operator Description Example
in Returns True if a sequence with the x in y
specified value is present in the object
not in Returns True if a sequence with the x not in y
specified value is not present in the object
Python Bitwise Operators
& AND Sets each bit to 1 if both bits are 1
| OR Sets each bit to 1 if one of two bits is 1
^ XOR Sets each bit to 1 if only one of two bits is 1
~ NOT Inverts all the bits
<< Zero fill left shift Shift left by pushing zeros in from the right
and let the leftmost bits fall off
>> Signed right shift Shift right by pushing copies of the leftmost
bit in from the left, and let the rightmost bits
fall off
& AND Sets each bit to 1 if both bits are 1
| OR Sets each bit to 1 if one of two bits is 1
A Code Sample (in IDLE)
x = 34 - 23 # A comment.
y = “Hello” # Another one.
z = 3.45
print(“x=“ x)
print(y)
print(type(x))
print(type(y))
print(type(z))
Basic Datatypes
Integers (default for numbers)
z = 5 / 2 # Answer 2, integer division
Floats
x = 3.456
Strings
• Can use “” or ‘’ to specify with “abc” ==
‘abc’
• Unmatched can occur within the string:
“matt’s”
• Use triple double-quotes for multi-line strings or
strings than contain both ‘ and “ inside of them:
“““a‘b“c”””
Branching Programs
Python supports the usual logical conditions from
mathematics:
• Equals: a == b
• Not Equals: a != b
• Less than: a < b
• Less than or equal to: a <= b
• Greater than: a > b
• Greater than or equal to: a >= b
Branching Programs- if--else
• In Python, a conditional statement has the form
if boolean expression:
block of code
elif boolean expression:
block of code
else:
block of code
Example – loop1.py
Source Code:
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
Output:
a is greater than b
Branching Programs
• compound Boolean expressions.
if x < y and x < z:
print 'x is least'
elif y < z:
print 'y is least'
else:
print 'z is least'
Iteration - while loop :
while boolean expression:
block of code
Example :
i=1
while i < 6:
print(i)
i += 1
Output:
1
2
3
4
5
While with break
Source Code
i=1
while i < 6:
print(i)
if i == 3:
break
i += 1
Output:
1
2
3
While with continue
i=0
while i < 6:
i += 1
if i == 3:
continue
print(i)
# Note that number 3 is missing in the result
Output:
1
2
4
5
6
While with else
Source Code:
i=1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")
Output
1
2
3
4
5
i is no longer less than 6
For loop
for iterator_var in sequence:
statements(s)
Example:
# Python program to illustrate
# Iterating over range 0 to n-1
n=4
for i in range(0, n):
print(i)
Output:
0123
range() function
The range() function returns a sequence of numbers,
starting from 0 by default, and increments by 1 (by
default), and ends at a specified number.
for x in range(6): # display numbers from 0 to 5
print(x)
for x in range(2, 6): # display numbers from 2 to 5
print(x)
for x in range(2, 30, 3): # start with 2 end with 29 and
#increment with 3
print(x) # output : 2,5,8,11,14,17,20,23,26,29
Strings and Input
• Objects of type str are used to represent strings of characters.
• Literals of type str can be written using either single or double
quotes, e.g., 'abc' or "abc".
• Exercise:
• Try typing the following expressions in to the Python interpreter
(remember that the >>> is a prompt, not something that you type):
>>> 'a‘ >>> 3*4
>>> 3*'a‘ >>> 3+4
>>> 'a'+'a‘
• The operator + is said to be overloaded:
– It has different meanings depending upon the types of the objects to
which it is applied.
– type checking exists is a good thing. It turns careless (and
sometimes subtle) mistakes into errors that stop execution, rather
than errors that lead programs to behave in mysterious ways.
Strings and Input
Strings are one of several sequence types in Python.
They share the following operations with all
sequence types.
• The length
• Indexing
—Python uses 0 to indicate the first element of a
string,
—Negative numbers are used to index from the end
of a string. For example, the value of 'abc'[-1] is 'c'.
• Slicing
—used to extract substrings of arbitrary length
—For example, 'abc'[1:3] = 'bc'.
Input – take input from user
input treats the typed line as a Python expression and infers a type.
• Consider the code
>>> name = input('Enter your name: ')
Enter your name: George Washington
>>> a=int(input(“Enter no”))
Enter no 2
Assignment
You can assign to multiple names at the
same time
>>> x, y = 2, 3
>>> x
2
>>> y
3
This makes it easy to swap values
>>> x, y = y, x
Assignments can be chained
>>> a = b = x = 2
DATA STRUCTURE
What is a Data Structure?
Organizing, managing and storing data is
important as it enables easier access and
efficient modifications.
Data Structures allows you to organize your data
in such a way that enables you to store
collections of data, relate them and perform
operations on them accordingly.
39
Types of Data Structures in Python
Python has implicit support for Data Structures
which enable you to store and access data.
These structures are called List, Dictionary, Tuple
and Set.
Python allows its users to create their own Data
Structures enabling them to have full control over
their functionality.
The most prominent Data Structures are Stack,
Queue, Tree, Linked List and so on which are also
available to you in other programming languages
40
Types of Data Structures in Python
41
Mutable vs Immutable Objects
in Python
Every variable in python holds an instance of an
object.
There are two types of objects in python
i.e. Mutable and Immutable objects.
Whenever an object is instantiated, it is assigned
a unique object id. The type of the object is
defined at the runtime and it can’t be changed
afterwards. However, it’s state can be changed if
it is a mutable object.
To summarise the difference, mutable objects can
change their state or contents and immutable
objects can’t change their state or content
42
Mutable Objects : It can changed after it is
created.
These are of type list, dict, set .
Custom classes are generally mutable.
Immutable Objects : It can not be changed after it
is created.
These are of in-built types like int, float, bool,
string, unicode, tuple.
43
Python collections/Data
structures
There are four collection data types in the Python
programming language:
List
It is a collection which is ordered and changeable.
Allows duplicate members. It is mutable.
Tuple
It is a collection which is ordered and unchangeable.
Allows duplicate members. It is non-mutable.
Set
It is a collection which is unordered and unhindered.
No duplicate members. It is mutable.
Dictionary
It is a collection which is unordered, changeable and
indexed. It is mutable. No duplicate members. 44
List
A list is a collection which is ordered and changeable.
In Python lists are written with square brackets.
Example :
L1 = ["apple", "banana", "cherry"]
print(L1)
Output: [‘apple’, ’banana’, ’cherry’]
45
Access items from list
>> L1=["a","b","c"]
>>> print(L1)
['a', 'b', 'c']
>>> L1[0]
'a'
>>> L1[1]
'b'
>>> L1[2]
'c'
>>> L1[-1]
'c'
>>> L1[-2]
'b'
>>> L1[-3]
46
'a'
Range of Indexes
Specify a range of indexes by specifying where to
start and where to end the range.
When specifying a range, the return value will be a
new list with the specified items.
Example:
Return the second, third, fourth, and item:
a = [“ apple", "banana", "cherry", "orange“]
print(a[1:3])
Output :['banana', 'cherry']
>>print(a[0: ]) - ['apple', 'banana', 'cherry', 'orange']
>>print(a[:4]) -['apple', 'banana', 'cherry', 'orange']
47
Range of Negative Indexes
starts from right to left with indexing -1.
a = [“ apple", "banana", "cherry", "orange“]
print(a[-4:-1])
Output : ['apple', 'banana', 'cherry']
48
Change Item Value –as List is
mutable
Example :
>>> a=["apple","banana","cherry","orange"]
>>> a
['apple', 'banana', 'cherry', 'orange']
>>> a[1]="mango"
>>> a
['apple', 'mango', 'cherry', 'orange']
>>>
49
Loop Through a List
You can loop through the list items by using
a for loop:
Example :Print all items in the list, one by one:
a = ["apple", "banana", "cherry"]
for x in a:
print(x)
Output:
apple
banana
cherry
50
Check if Item Exists
Example:
a = ["apple", "banana", "cherry"]
if "apple" in a:
print("Yes, 'apple' is in the fruits
list")
51
List methods
Method Description
append() Adds an element at the end of the list
clear() Removes all the elements from the list
copy() Returns a copy of the list
count() Returns the number of elements with the specified value
extend() Add the elements of a list (or any iterable), to the end of the current list
index() Returns the index of the first element with the specified value
insert() Adds an element at the specified position
pop() Removes the element at the specified position
remove() Removes the first item with the specified value
reverse() Reverses the order of the list
sort() Sorts the list
52
1. List Length - To determine how many items a list
has, use the len() function:
Example- Print the number of items in the list:
a = ["apple", "banana", "cherry"]
print(len(a))
2. Add Items -To add an item to the end of the list,
use the append() method:
Example :
a= ["apple", "banana", "cherry"]
a.append("orange")
print(a)
Output : [‘apple’,’banana’,’cherry’,’orange’]
53
3. Insert-To add an item at the specified index, use
the insert() method:
a = ["apple", "banana", "cherry"]
a.insert(1, "orange")
print(thislist)
4. Remove Item -There are several methods to
remove items from a list:
a = ["apple", "banana", "cherry"]
a.remove("banana")
print(a)
.
54
5. Pop - The pop() method removes the specified
index, (or the last item if index is not specified):
a = ["apple", "banana", "cherry"]
a.pop()
print(a)
6. del- The del keyword removes the specified index:
a= ["apple", "banana", "cherry"]
del a[0]
print(a)
The del keyword can also delete the list completely:
a = ["apple", "banana", "cherry"]
del a
7. Clear - clear() method empties the list:
a = ["apple", "banana", "cherry"]
a.clear()
print(a) 55
Copy list
You cannot copy a list simply by typing list2 = list1,
because: list2 will only be a reference to list1, and
changes made in list1 will automatically also be made
in list2.
There are ways to make a copy, one way is to use the
built-in List method copy().
a = ["apple", "banana", "cherry"]
a1 = a.copy()
print(a1)
Another way to make a copy is to use the built-in
method list().
Example - Make a copy of a list with the list() method:
a = ["apple", "banana", "cherry"]
a1 = list(a) 56
print(a1)
Join Two Lists
Method 1 : using the + operator.
Example - Join two list:
list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]
list3 = list1 + list2
print(list3)
Method 2:Another way to join two lists are by
appending all the items from list2 into list1, one by
one:
list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]
for x in list2:
list1.append(x)
print(list1) 57
Method 3: you can use the extend() method,
which purpose is to add elements from one list to
another list:
list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]
list1.extend(list2)
print(list1)
o list() constructor:
>>> a=list(('a','b'))
>>> a
['a', 'b']
58
Tuple – immutable
A tuple is a collection which is ordered
and unchangeable.
In Python tuples are written with round brackets.
Create a Tuple:
a = ("apple", "banana", "cherry")
print(a)
Output :
('apple', 'banana', 'cherry')
59
There are four collection data types in the
Python programming language:
List is a collection which is ordered and
changeable. Allows duplicate members.
Tuple is a collection which is ordered and
unchangeable. Allows duplicate members.
Set is a collection which is unordered and
unindexed. No duplicate members.
Dictionary is a collection which is unordered and
changeable. No duplicate members.
60
Access Tuple Items
Print the second item in the tuple:
a = ("apple", "banana", "cherry")
print(a[1])
Negative Indexing - Print the last item of the
tuple:
a = ("apple", "banana", "cherry")
print(a[-1])
Return the third, fourth, and fifth item:
a = ( "apple", "banana", "cherry", "orange“)
print(a[1:3])
61
Change Tuple Values
Once a tuple is created, you cannot change its
values. Tuples are unchangeable,
or immutable as it also is called.
But there is a workaround. You can convert the
tuple into a list, change the list, and convert the
list back into a tuple.
Example - Convert the tuple into a list to be able
to change it:
x = ("apple", "banana", "cherry")
y = list(x)
y[1] = “manago"
x = tuple(y)
62
print(x)
Add ITems
Once a tuple is created, you cannot add items to
it. Tuples are unchangeable.
Example -You cannot add items to a tuple:
a= ("apple", "banana", "cherry")
a[3] = "orange" # This will raise an error
print(a)
63
Create Tuple With One Item
To create a tuple with only one item, you have
add a comma after the item, unless Python will
not recognize the variable as a tuple.
Example - One item tuple, remember the
commma:
thistuple = ("apple",)
print(type(thistuple))
#NOT a tuple
thistuple = ("apple")
print(type(thistuple))
64
Remove Items
Tuples are unchangeable, so you cannot remove
items from it, but you can delete the tuple
completely:
del keyword can delete the tuple completely:
a= ("apple", "banana", "cherry")
del a
print(a) #this will raise an error because
the tuple no longer exists
65
Join Two Tuples
Join two tuples:
tuple1 = ("a", "b" , "c")
tuple2 = (1, 2, 3)
tuple3 = tuple1 + tuple2
print(tuple3)
Output: ('a', 'b', 'c‘, 1, 2, 3)
The tuple() Constructor
a = tuple(("apple", "banana", "cherry")) # note the
double round-brackets
print(a)
66
Tuple methods
Method Description
count() Returns the number of times a specified value occurs in a tuple
index() Searches the tuple for a specified value and returns the position
of where it was found
67
Dictionary
A dictionary is a collection which is unordered,
changeable and indexed.
In Python dictionaries are written with curly
brackets, and they have keys and values.
Example - Create and print a dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
Output : {'brand': 'Ford', 'model': 'Mustang', 'year': 68
1964}
Accessing Items
You can access the items of a dictionary by
referring to its key name, inside square brackets:
Example - Get the value of the "model" key:
x = thisdict["model"]
Output :’Mustang’
o There is also a method called get() that will give
you the same result:
x = thisdict.get("model")
69
Change Values
You can change the value of a specific item by
referring to its key name:
Example - Change the "year" to 2018:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["year"] = 2018
70
Check if Key Exists
To determine if a specified key is present in a
dictionary use the in keyword:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
if "model" in thisdict:
print("Yes, 'model' is one of the keys in the
thisdict dictionary")
71
Loop Through a Dictionary
1. Example - Print all key names in the dictionary, one by one:
for x in thisdict:
print(x)
Output : brand model year
2. Print all values in the dictionary, one by one:
for x in thisdict:
print(thisdict[x])
Output: Ford Mustang 1964
3. You can also use the values() function to return values of a dictionary:
for x in thisdict.values():
print(x)
Output: Ford Mustang 1964
4. Loop through both keys and values, by using the items() function:
for x, y in thisdict.items():
print(x, y)
Output:
brand Ford
model Mustang
year 1964
72
Dictionary Length - To determine how many items
(key-value pairs) a dictionary has, use
the len() method.
print(len(thisdict))
Adding Items - Adding an item to the dictionary is
done by using a new index key and assigning a
value to it:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["color"] = "red"
print(thisdict) 73
Removing Items
There are several methods to remove items from
a dictionary:
pop() method removes the item with the
specified key name:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.pop("model")
print(thisdict)
74
The popitem() method removes the last inserted
item (in versions before 3.7, a random item is
removed instead):
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.popitem()
print(thisdict)
75
Example - The del keyword removes the item with
the specified key name:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict["model"]
print(thisdict)
76
Example - The clear() keyword empties the
dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.clear()
print(thisdict)
77
Copy a Dictionary
You cannot copy a dictionary simply by
typing dict2 = dict1, because: dict2 will only be
a reference to dict1, and changes made
in dict1 will automatically also be made in dict2.
There are ways to make a copy, one way is to use
the built-in Dictionary method copy().
Make a copy of a dictionary with
the copy() method:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = thisdict.copy() 78
print(mydict)
Make a copy of a dictionary with
the dict() method:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = dict(thisdict)
print(mydict)
79
Nested Dictionaries
create a dictionary that contain three dictionaries:
myfamily = {
"child1" : {
"name" : "Emil",
"year" : 2004
},
"child2" : {
"name" : "Tobias",
"year" : 2007
},
"child3" : {
"name" : "Linus",
"year" : 2011
} 80
}
Or, if you want to nest three dictionaries that already exists as
dictionaries:
Example - Create three dictionaries, than create one dictionary
that will contain the other three dictionaries:
child1 = {
"name" : "Emil",
"year" : 2004
}
child2 = {
"name" : "Tobias",
"year" : 2007
}
child3 = {
"name" : "Linus",
"year" : 2011
}
myfamily = {
"child1" : child1,
"child2" : child2, 81
"child3" : child3
}
The dict() Constructor
It is also possible to use the dict() constructor to
make a new dictionary:
Example
thisdict = dict(brand="Ford", model="Mustang",
year=1964)
# note that keywords are not string literals
# note the use of equals rather than colon for the
assignment
print(thisdict)
82
Dictionary Methods
Method Description
clear() Removes all the elements from the dictionary
copy() Returns a copy of the dictionary
fromkeys() Returns a dictionary with the specified keys and values
get() Returns the value of the specified key
items() Returns a list containing a tuple for each key value pair
keys() Returns a list containing the dictionary's keys
pop() Removes the element with the specified key
popitem() Removes the last inserted key-value pair
setdefault() Returns the value of the specified key. If the key does not
exist: insert the key, with the specified value
update() Updates the dictionary with the specified key-value pairs
values() Returns a list of all the values in the dictionary
83
Python Sets
set is a collection which is unordered and
unindexed. In Python sets are written with curly
brackets.
thisset = {"apple", "banana", "cherry"}
print(thisset)
Output: {“apple”,’banana”,”cherry”}
Note: Sets are unordered, so you cannot be sure in
which order the items will appear.
84
Access Items
You cannot access items in a set by referring to
an index, since sets are unordered the items has
no index.
But you can loop through the set items using
a for loop, or ask if a specified value is present in
a set, by using the in keyword.
thisset = {"apple", "banana", "cherry"}
for x in thisset:
print(x)
Example : Check if "banana" is present in the set:
thisset = {"apple", "banana", "cherry"} 85
print("banana" in thisset)
Change Items
Once a set is created, you cannot change its
items, but you can add new items.
Add items:
To add one item to a set use the add() method.
To add more than one item to a set use
the update() method.
Example -Add an item to a set, using
the add() method:
thisset = {"apple", "banana", "cherry"}
thisset.add("orange")
print(thisset)
86
Example -Add multiple items to a set, using
the update() method:
thisset = {"apple", "banana", "cherry"}
thisset.update(["orange", "mango", "grapes"])
print(thisset)
87
Get the Length of a Set
To determine how many items a set has, use
the len() method.
Example - Get the number of items in a set:
thisset = {"apple", "banana", "cherry"}
print(len(thisset))
Remove Item - To remove an item in a set, use
the remove(), or the discard() method.
thisset = {"apple", "banana", "cherry"}
thisset.remove("banana")
print(thisset)
88
Example - Remove "banana" by using
the discard() method:
thisset = {"apple", "banana", "cherry"}
thisset.discard("banana")
print(thisset)
Note:
If the item to remove does not exist,
remove() will raise an error.
If the item to remove does not
exist, discard() will NOT raise an error.
89
You can also use the pop(), method to remove an
item, but this method will remove the last item.
Remember that sets are unordered, so you will
not know what item that gets removed.
The return value of the pop() method is the
removed item.
Remove the last item by using the pop() method:
thisset = {"apple", "banana", "cherry"}
x = thisset.pop()
print(x)
print(thisset)
Note: Sets are unordered, so when using
the pop() method, you will not know which item
that gets removed. 90
The clear() method empties the set:
thisset = {"apple", "banana", "cherry"}
thisset.clear()
print(thisset)
Example - The del keyword will delete the set
completely:
thisset = {"apple", "banana", "cherry"}
del thisset
print(thisset)
91
Join Two Sets
There are several ways to join two or more sets in
Python.
You can use the union() method that returns a
new set containing all items from both sets, or
the update() method that inserts all the items
from one set into another:
Example - The union() method returns a new set
with all items from both sets:
set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}
set3 = set1.union(set2)
print(set3)
92
Example - The update() method inserts the items
in set2 into set1:
set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}
set1.update(set2)
print(set1)
Note: Both union() and update() will exclude any
duplicate items.
The set() Constructor- It is also possible to use
the set() constructor to make a set. Using the
set() constructor to make a set:
thisset = set(("apple", "banana", "cherry")) # note
the double round-brackets
print(thisset) 93
Set Methods
Method Description
add() Adds an element to the set
clear() Removes all the elements from the set
copy() Returns a copy of the set
difference() Returns a set containing the difference between two or more sets
difference_update() Removes the items in this set that are also included in another, specified set
discard() Remove the specified item
intersection() Returns a set, that is the intersection of two other sets
intersection_update() Removes the items in this set that are not present in other, specified set(s)
isdisjoint() Returns whether two sets have a intersection or not
issubset() Returns whether another set contains this set or not
issuperset() Returns whether this set contains another set or not
pop() Removes an element from the set
remove() Removes the specified element
symmetric_difference() Returns a set with the symmetric differences of two sets
symmetric_difference_update() inserts the symmetric differences from this set and another
union() Return a set containing the union of sets
94
update() Update the set with the union of this set and others
Python Strings - immutable
String literals in python are surrounded by either
single quotation marks, or double quotation marks.
'hello' is the same as "hello".
Example
print("Hello")
print('Hello')
95
Multiline Strings
You can assign a multiline string to a variable by using three quotes:
You can use three double quotes:
Example:
a = """ My name is kruti
I am professor of Computer Engg Dept.
I am working in Shri s’ad vidya mandal institute of technology """
print(a)
OR
You can use threee single quotes
a = ''' My name is kruti
I am professor of Computer Engg Dept.
I am working in Shri s’ad vidya mandal institute of technology '''
print(a)
96
Strings are arrays:
Python does not have a character data type, a single
character is simply a string with a length of 1.
Square brackets can be used to access elements of
the string.
Example - Get the character at position 1 (remember
that the first character has the position 0):
a = "Hello, World!"
print(a[1])
97
How String slicing in Python works
Python slicing can be done in two ways:
Using a slice() method
Using array slicing [ : : ] method
Index tracker for positive and negative index: .
Method 1: Using slice() method
The slice() constructor creates a slice object
representing the set of indices specified by
range(start, stop, step).
Syntax:
slice(stop)
slice(start, stop, step)
Parameters:
start: Starting index where the slicing of object starts.
stop: Ending index where the slicing of object stops.
step: It is an optional argument that determines the
increment between each index for slicing. Return
Type: Returns a sliced object containing elements in
the given range only.
P
Python program to demonstrate
# string slicing
String = 'ASTRING'
# Using slice constructor
s1 = slice(3)
s2 = slice(1, 5, 2) Output:
s3 = slice(-1, -12, -2) String slicing
AST
print(“String slicing “) SR
print(String[s1]) GITA
print(String[s2])
print(String[s3])
Method 2: Using List/array slicing [ : : ] method
In Python, indexing syntax can be used as a substitute
for the slice object.. A start, end, and step have the same
mechanism as the slice() constructor.
Syntax
arr[start:stop] # items start through stop-1
arr[start:] # items start through the rest of the array
arr[:stop] # items from the beginning through stop-1
arr[:] # a copy of the whole array
arr[start:stop:step] # start through not past stop, by step
Example-# Python program to demonstrate
# string slicing
# String slicing
String = 'GEEKSFORGEEKS' Output:
GEE
# Using indexing sequence EK
print(String[:3]) SEGOSE
# Using indexing sequence
print(String[1:5:2])
# Using indexing sequence
print(String[-1:-12:-2])
Program : reverse of string
# Python program to demonstrate
# string slicing Output:
SKEEGROFSKEEG
# String slicing
String = 'GEEKSFORGEEKS'
# Prints string in reverse
print(String[::-1])
String length
To get the length of a string, use len() function.
Example - The len() function returns the length of
a string:
a = "Hello, World!"
print(len(a))
Output :13
10
4
Looping Through a String
Since strings are arrays, we can loop through the
characters in a string, with a for loop.
Loop through the letters in the word
" SVMIT ":
for x in “SVMIT":
print(x)
10
5
Check String
check if a certain phrase or character is present in
a string, we can use the keyword in.
Example
Check if "free" is present in the following text:
txt = "The best things in life are free!"
print("free" in txt)
o Use it in an if statement:
Example
Print only if "free" is present:
txt = "The best things in life are free!"
if "free" in txt:
print("Yes, 'free' is present.") 10
6
Check if NOT
To check if a certain phrase or character is NOT
present in a string, we can use the keyword not
in.
Example
Check if "expensive" is NOT present in the
following text:
txt = "The best things in life are free!"
print("expensive" not in txt)
Use it in an if statement:
print only if "expensive" is NOT present:
txt = "The best things in life are free!"
if "expensive" not in txt:
print("Yes, 'expensive' is NOT 10
present.") 7
Python string methods
Method Description
capitalize() Converts the first character to upper
case
casefold() Converts string into lower case
center() Returns a centered string
count() Returns the number of times a specified
value occurs in a string
encode() Returns an encoded version of the
string
endswith() Returns true if the string ends with the
specified value
10
8
expandtabs() Sets the tab size of the string
find() Searches the string for a specified
value and returns the position of where
it was found
format() Formats specified values in a string
format_map() Formats specified values in a string
index() Searches the string for a specified
value and returns the position of where
it was found
isalnum() Returns True if all characters in the
string are alphanumeric
10
9
isalpha() Returns True if all characters in the string are in the alphabet
isdecimal() Returns True if all characters in the string are decimals
isdigit() Returns True if all characters in the string are digits
isidentifier() Returns True if the string is an identifier
islower() Returns True if all characters in the string are lower case
isnumeric() Returns True if all characters in the string are numeric
isprintable() Returns True if all characters in the string are printable
isspace() Returns True if all characters in the string are whitespaces
11
0
istitle() Returns True if the string follows the
rules of a title
isupper() Returns True if all characters in the
string are upper case
join() Joins the elements of an iterable to the
end of the string
ljust() Returns a left justified version of the
string
lower() Converts a string into lower case
lstrip() Returns a left trim version of the string
maketrans() Returns a translation table to be used in
translations
partition() Returns a tuple where the string is
parted into three parts
11
1
replace() Returns a string where a specified value is replaced with a specified value
rfind() Searches the string for a specified value and returns the last position of where it was found
rindex() Searches the string for a specified value and returns the last position of where it was found
rjust() Returns a right justified version of the string
rpartition() Returns a tuple where the string is parted into three parts
rsplit() Splits the string at the specified separator, and returns a list
rstrip() Returns a right trim version of the string
split() Splits the string at the specified separator, and returns a list
splitlines() Splits the string at line breaks and returns a list
11
2
startswith() Returns true if the string starts with the
specified value
strip() Returns a trimmed version of the string
swapcase() Swaps cases, lower case becomes
upper case and vice versa
title() Converts the first character of each
word to upper case
translate() Returns a translated string
upper() Converts a string into upper case
zfill() Fills the string with a specified number
of 0 values at the beginning
11
3
Get a list as input from user
# creating an empty list
L1 = []
# number of elements as input
n = int(input("Enter number of elements : "))
# iterating till the range
for i in range(0, n):
ele = int(input())
L1.append(ele) # adding the element
print(L1)
Python Built in Functions
Function Description
abs() Returns the absolute value of a number
all() Returns True if all items in an iterable object are true
any() Returns True if any item in an iterable object is true
ascii() Returns a readable version of an object. Replaces none-ascii
characters with escape character
bin() Returns the binary version of a number
bool() Returns the boolean value of the specified object
bytearray() Returns an array of bytes
bytes() Returns a bytes object
callable() Returns True if the specified object is callable, otherwise False
chr() Returns a character from the specified Unicode code.
classmetho Converts a method into a class method
d()
Python Built in Functions
Function Description
compile() Returns the specified source as an object, ready to be executed
complex() Returns a complex number
delattr() Deletes the specified attribute (property or method) from the
specified object
dict() Returns a dictionary (Array)
dir() Returns a list of the specified object's properties and methods
divmod() Returns the quotient and the remainder when argument1 is divided
by argument2
enumerate() Takes a collection (e.g. a tuple) and returns it as an enumerate
object
eval() Evaluates and executes an expression
exec() Executes the specified code (or object)
filter() Use a filter function to exclude items in an iterable object
float() Returns a floating point number
Python Built in Functions
Function Description
format() Formats a specified value
frozenset() Returns a frozenset object
getattr() Returns the value of the specified attribute (property or method)
globals() Returns the current global symbol table as a dictionary
hasattr() Returns True if the specified object has the specified attribute
(property/method)
hash() Returns the hash value of a specified object
help() Executes the built-in help system
hex() Converts a number into a hexadecimal value
id() Returns the id of an object
input() Allowing user input
Python Built in Functions
Function Description
isinstance() Returns True if a specified object is an instance of a specified
object
issubclass() Returns True if a specified class is a subclass of a specified object
iter() Returns an iterator object
len() Returns the length of an object
list() Returns a list
locals() Returns an updated dictionary of the current local symbol table
map() Returns the specified iterator with the specified function applied to
each item
max() Returns the largest item in an iterable
memoryview() Returns a memory view object
min() Returns the smallest item in an iterable
next() Returns the next item in an iterable
Python Built in Functions
Function Description
object() Returns a new object
oct() Converts a number into an octal
open() Opens a file and returns a file object
ord() Convert an integer representing the Unicode of the specified
character
pow() Returns the value of x to the power of y
print() Prints to the standard output device
property() Gets, sets, deletes a property
range() Returns a sequence of numbers, starting from 0 and increments by
1 (by default)
repr() Returns a readable version of an object
reversed() Returns a reversed iterator
round() Rounds a numbers
Python Built in Functions
Function Description
set() Returns a new set object
setattr() Sets an attribute (property/method) of an object
slice() Returns a slice object
sorted() Returns a sorted list
staticmethod() Converts a method into a static method
str() Returns a string object
sum() Sums the items of an iterator
super() Returns an object that represents the parent class
tuple() Returns a tuple
type() Returns the type of an object
vars() Returns the __dict__ property of an object
Difference Between List and Tuple in Python
Sr. Key List Tuple
No.
1 Type List is mutable. Tuple is immutable.
Iteration List iteration is Tuple iteration is faster.
2 slower and is time
consuming.
Appropriate List is useful for Tuple is useful for readonly
3 for insertion and operations like accessing
deletion operations. elements.
Memory List consumes more Tuples consumes less
4
Consumption memory. memory.
Methods List provides many Tuples have less in-built
5
in-built methods. methods.
Error prone List operations are Tuples operations are safe.
6
more error prone.
Mutable/immutable class
Class Explanation Immutable or not
Bool Boolean value Immutable
Int Integer value (magnitude can be arbitrary) Immutable
Float Floating point number Immutable
List Sequence of objects of mutable nature Mutable
Tuple Sequence of objects of immutable nature Immutable
Str Character /string Immutable
set of distinct objects that are of
Set Mutable
Unordered nature
Frozenset Set class of immutable nature Immutable
Dict Dictionary or associative mapping Mutable
FUNCTIONS
• Function name should be descriptive of the task
carried out by the function
– Often includes a verb
• Function definition: specifies what function does
def function_name():
statement
statement
Example : write a code to find out maximum no between two
using function.
def max(x, y):
if x > y:
return x
else:
return y
Execute at promt:
>>> max(3,4)
>>>4
# Factorial of a number using recursion
def recur_factorial(n):
if n == 1:
return n
else:
return n*recur_factorial(n-1)
num = 7
# check if the number is negative
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
print("The factorial of", num, "is", recur_factorial(num))
Coding Styles of Python Programming
Language
Different coding styles can be chosen for different
problems. There are four different coding styles
offered by python.
• Functional
• Imperative
• Object-oriented
• Procedural
Functional coding
In the functional type of coding, every statement is treated as a
Mathematical equation and mutable (able to change) data can be
avoided. Most of the programmers prefer this type of coding for
recursion and lambda calculus. The merit of this functional coding is it
works well for parallel processing, as there is no state to consider. This
style of coding is mostly preferred by academics and Data scientists .
Python Code:
my_list = [1, 5, 4, 6, 8, 11, 3, 12]
new_list = list(map(lambda x: x * 2 , my_list))
print(new_list)
Output:
[2, 10, 8, 12, 16, 22, 6, 24]
Imperative coding
When there is a change in the program, computation occurs.
Imperative style of coding is adopted, if we have to manipulate
the data structures. This style establishes the program in a
simple manner. It is mostly used by Data scientists because of
its easy demonstration.
Python Code:
sum = 0
for x in my_list:
sum += x
print(sum)
Output:
50
Object-oriented coding
This type of coding relies on the data fields, which are treated
as objects. These can be manipulated only through prescribed
methods. Python doesn’t support this paradigm completely, due
to some features like encapsulation cannot be implemented.
This type of coding also supports code reuse.
.
Python Code:
class word:
def test(self):
print("Python")
string = word()
string.test()
Output:
Python
Procedural coding
Usually, most of the people begin learning a language through
procedural code, where the tasks proceed a step at a time. It is the
simplest form of coding. It is mostly used by non-programmers as it is a
simple way to accomplish simpler and experimental tasks. It is used for
iteration, sequencing, selection, and modularization.
Python Code:
def add(list):
sum = 0
for x in list:
sum += x
return sum
print(add(my_list))
Output:
50