You are on page 1of 129

MODULE 2:

INTRODUCTION
TO PYTHON
PROGRAMMING

DR. NIDHI AHUJA 1


• Python is a:
• high-level,
• interpreted and
PYTHON • general-purpose dynamic
programming language that
focuses on code readability.

• The syntax in Python helps the


programmers to do coding in fewer
steps as compared to Java or C++.
DR. NIDHI AHUJA 2
• A popular scripting language for
PYTHON connecting to database.

• To write lengthy programs,


• use Script mode in which we
can create and edit programs.

DR. NIDHI AHUJA 3


• The python ecosystem is very rich and
provides easy to use tools for data
science.
PYTHON
• Popular packages are:
• Numpy
• Pandas
• Matplotlib
• Scipy

DR. NIDHI AHUJA 4


• All Python programs can work on
PYTHON any of these platforms without
requiring any changes.

• Python supports relational


database systems.

DR. NIDHI AHUJA 5


• Notebooks are very popular in the
field of data science because they
allows creation & sharing of
• code,
PYTHON • equations,
• visualizations and
• explanatory texts.

• A notebook interface is a virtual


notebook environment used for
programming.
DR. NIDHI AHUJA 6
• In this course, we’ll be using Jupyter
notebooks.

• Jupyter notebook (a web based


PYTHON editor) is an open source web
application that allows you to create
and share documents that contain
• live code,
• equations,
• visualizations and
• narrative texts.
DR. NIDHI AHUJA 7
• Notebook support for over 40
programming languages including
• Python,
ADVANTAGES • Julia,
OF JUPYTER • Scala and
• R.
NOTEBOOK
• Notebooks can be shared with other by
• emails,
• Dropbox,
• Github and
• Jupyter notebook viewer.
DR. NIDHI AHUJA 8
• You can leverage big
• Your code can data tools such as
ADVANTAGES produce
• Apache,
• rich interactive
OF JUPYTER output HTML,
• Spark from
Python,
NOTEBOOK • images, • R and
• videos, • Scala and
• Latex and • explore that same
• customized data with Pandas,
types. scikit learn,
ggplot2 and
DR. NIDHI AHUJA
Tensor flow. 9
1. PYTHON • STATEMENT: • ARGUMENT:
When you run a print
BASICS A statement or
statement, Python will
expressions is an simply display the value
instruction the in the parentheses. The
computer will run or value in the parentheses
execute. is called Argument.

DR. NIDHI AHUJA 10


To Run a
statement:
1. PYTHON Cell: • If you select this
BASICS • In Jupyter cell with your
notebook, a mouse then click
small rectangle the run cell
with a statement button (or shift +
is called a cell. enter). The
statement will
execute.
DR. NIDHI AHUJA 11
• This tells other people what your
To comment code does. Simply put “#”
your code symbol preceding your comment.

• For example,
#Hello

DR. NIDHI AHUJA 12


• To print in two different lines , use
“\n”:
To print in 2 E.g.
different lines Print (“Hello \n World”)

• This gives you:


Hello
World

DR. NIDHI AHUJA 13


• A type is how Python represents
different types of data.
2. Types
• Different types in Python are:
• Integers (Int)
• Real Numbers (Float)
• Words / Strings etc. (Str)

DR. NIDHI AHUJA 14


• To check the type of any data, use:

2. Types type ( ) in python

• For example,
type (1) gives you int
type (‘Hello’) gives you str

DR. NIDHI AHUJA 15


• In Python, you can change the type of
expression. This is called Type casting.

2. Types • For example,


• float (2) gives you 2.0;
• int (1.1) gives you 1.

• Note: But if you convert float to


integer then there is some loss of
info.

DR. NIDHI AHUJA 16


• These types can be expressed as
different data types.

2. Types
• E.g. Int - 11 , 62

• Float – 21.236

• Str – “Hello Python”

DR. NIDHI AHUJA 17


• Also, if a string contains an integer
value you can convert it to “int”.
2. Types • For example, int (“1”) gives you 1

• But if you convert a string that


contains a non-integer value, we
get an error.
• For example, int (“A”) gives you error.

DR. NIDHI AHUJA 18


• Note: You can convert an “int” to
2. Types “str” or a float to a “str”.

• For example,
• str (1) gives ‘1’.
• str (4.5) gives ‘4.5’

DR. NIDHI AHUJA 19


• Boolean is another important type
in Python.
2. Types
• A Boolean can take only two values:
• True
• False

DR. NIDHI AHUJA 20


• Using the “type” command on a
Boolean value, we obtain the term
2. Types “bool” which is a short form of
Boolean.

• i.e. type (True) gives you "bool”

DR. NIDHI AHUJA 21


• If we cast a Boolean “true” to an
integer or float we’ll get a 1 i.e
• int (True) = 1;
2. Types float (True) = 1.0

• If we cast a Boolean “false” to an


integer or float we’ll get a 0.
• i.e. int (False) = 0;
float (False) = 0.0

DR. NIDHI AHUJA 22


• If we cast a 1 to a Boolean you get
“true”.
2. Types
• If we cast a 0 to a Boolean you get
“false”.
• i.e. bool (0) = False
bool (1) = True

DR. NIDHI AHUJA 23


• Expressions describe a type of
operation that computers perform.
3. Expressions
& Variables • For example, Basic arithmetic
operators like adding numbers:
43 + 60 + 16 + 41 in which
numbers are operands and
“+” is operator

DR. NIDHI AHUJA 24


1. To the power i.e. 52 can be written
3. Expressions as 5 * * 2
2. Subtraction sign: “-”
& Variables
3. Multiply Sign: “*”
4. Division sign: “/”
5. For getting remainder use “%”. E.g.
17 % 3 gives 2

DR. NIDHI AHUJA 25


Python divides the operators in the
following groups:
• Arithmetic operators
3. Expressions
• Assignment operators
& Variables • Comparison operators
• Logical operators
• Identity operators
• Membership operators
• Bitwise operators
DR. NIDHI AHUJA 26
Python
Arithmetic
Operators

DR. NIDHI AHUJA 27


Python
Comparison
Operators

DR. NIDHI AHUJA 28


Python Identity
Operators

DR. NIDHI AHUJA 29


Python
Membership
Operators

DR. NIDHI AHUJA 30


Python Bitwise
Operators

DR. NIDHI AHUJA 31


• Note: When we divide the numbers,
the result will always be in float.
3. Expressions
& Variables • We can use the double slash for
integer division where the result is
rounded.
• For example: 25 // 5 gives 5;
• 25 // 6 gives 4

DR. NIDHI AHUJA 32


3. Expressions
• Note: Python follows mathematical
& Variables conventions when performing
mathematical expressions. i.e.
follows BODMAS

DR. NIDHI AHUJA 33


VARIABLES:
• We can use variables to store values.
3. Expressions
& Variables • For example, if we write x = 1 then
value 1 gets stored in x.

• Note: If we assign a new value to x


using assignment operator (=) then
the old value of the variable is not
independent and it will show the
latest value.
DR. NIDHI AHUJA 34
• We can also store the results of
expressions as:
x = 43 + 60 + 16 + 41
3. Expressions i.e. x = 160.
& Variables Now x has stored value 160.

• We can also perform operations on


“x” and save the result to a new
variable ‘y’.
For example, y = x/10 gives you 16.0

DR. NIDHI AHUJA 35


• Note: We can use the type command
in variables as well.

3. Expressions • For example,


& Variables • type (x) gives int; while
• type (y) gives float.

• Note: Its common to use underscore


to represent the start of a new word;
you can also use a capital letter. For
example, total_cost OR TotalCost
DR. NIDHI AHUJA 36
1. If you have made a
mistake in writing a code.
Points to Always check what the
Remember: error message tells you:
• Where error occurred
• What kind of error it was

DR. NIDHI AHUJA 37


2. Python is called an interpreted
language.
• Compiled languages examine your
Points to entire program at compile time
and are able to warn you about a
Remember: whole class of errors prior to
execution.
• In contrast, python interprets your
script line by line as it executes it.
• Python will stop executing the
entire program when it encounters
an error.
DR. NIDHI AHUJA 38
Points to 3. Floats represents real numbers.
Remember: There are some limitations when it
comes to machines representing real
numbers; but floating numbers are a
good representation in most cases.

DR. NIDHI AHUJA 39


Points to
Remember: 4. Strings can be represented with
single quotes (‘1.2’) or double quotes
(“1.2”) or triple quotes (‘’’1.2’’’)

DR. NIDHI AHUJA 40


A simple • To enter a number:
a = input (“Enter a Number”)
program:
b = int (a)
c = b**2 (#square of b)
print(c)

DR. NIDHI AHUJA 41


• In Python, a string is a sequence of
characters.
4. String
Operations • A string is contained within double
quotes. E.g. “Michael Jackson”

• You could also use single quotes


‘Michael Jackson’ or ‘’’Michael
Jackson’’’.

DR. NIDHI AHUJA 42


• A string can be spaces or digits.

4. String • A string can also be special characters


e.g. “1 2 3 4 5 6” OR
Operations
‘@ # $ 2 _ ! % ^’

• We can bind or assign a string to


another variable
e.g. Name = “Michael Jackson”
DR. NIDHI AHUJA 43
• It is helpful to think of a string as an
4. String ordered sequence. Each element in
the sequence can be accessed using
Operations an index represented by the array of
numbers.

M I C H A E L J A C K S O N
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14

DR. NIDHI AHUJA 44


• The first index can be accessed as
4. String follows:
Operations Name[0] = M

• We can access index 6 as


Name [6] = L

DR. NIDHI AHUJA 45


4. String
Operations • We can also use negative indexing
with strings:

M I C H A E L J A C K S O N
- - - - - - -9 -8 -7 -6 -5 -4 -3 -2 -1
15 14 13 12 11 10

DR. NIDHI AHUJA 46


• We can bind a string to another
variable.

4. String • It is helpful to think of string as a list


or tuple. You can treat the string as a
Operations sequence and perform operation.

• For example, a = “There was …..with


notes”
b = a.endswith (“notes”) gives True
b = a.endswith (“abc”) gives False
DR. NIDHI AHUJA 47
M I C H A E L J A C K S O N
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14

4. String • Name [0:4] = MICH


Operations • Name [8:12] = JACK

• We can also input a stride values as


follows:
Name[::2] = “MCALJCSN”
• 2 indicates we select every second
variable.
DR. NIDHI AHUJA 48
M I C H A E L J A C K S O N
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14

4. String • We can also incorporate slicing.


Operations
• In this case, we return every 2nd value
upto index 5.

Name [0:5:2] = “MCA”

DR. NIDHI AHUJA 49


• We can use “len” command to obtain
the length of the string.
len (“Michael Jackson”) = 15
4. String
Operations • We can concatenate or combine
strings using addition symbol.

• For example, Name = “Michael


Jackson”
Statement = Name + “is the best”
Output is: Statement = “Michael
Jackson is the best”
DR. NIDHI AHUJA 50
• We can also replicate values of a
string.
• For example, 3 * “Michael Jackson”
4. String gives
Operations “Michael Jackson Michael Jackson
Michael Jackson”
OR print(‘Michael Jackson \n‘ *3)
OR
for i in range(3):
print(“Michael Jackson’)
DR. NIDHI AHUJA 51
• If a = “There was ……. With notes”.
• b = a.count (“r”) gives the number of
4. String ‘r’ present in a.
Operations
• a.capitalize () capitalizes the 1st letter
of the word.

• a.count(1) gives you how many times


‘1’ occurs in tuple.

DR. NIDHI AHUJA 52


4. String • Strings are immutable i.e.
unable to change.
Operations
• Backslashes represents the
beginning of escape sequences.

DR. NIDHI AHUJA 53


• For example, print(“Michael Jackson
\n is the best”).

4. String • Output is:


Operations Michael Jackson
is the best
• Note:
1. \n represents a new line
2. \t represents a tab

DR. NIDHI AHUJA 54


• For example, print(“Michael Jackson
4. String \t is the best”).
Operations
• Output is:
Michael Jackson is the best

DR. NIDHI AHUJA 55


Let’s discuss string methods.

• Strings are sequences and as such


4. String have apply methods that work on
Operations lists and tuples.

• Strings also have a second set of


methods.
1. Sequence Methods
2. String Methods
DR. NIDHI AHUJA 56
• To make in an upper case ()

4. String • For example, Let A = “Thriller is the


Operations sixth studio album”

If we write B = A.upper ()
O/P is:
THRILLER IS THE SIXTH STUDIO ALBUM

DR. NIDHI AHUJA 57


• To make in a lower case ()

4. String • For example, Let A = “THRILLER IS


Operations THE SIXTH STUDIO ALBUM”

If we write C = A.lower ()
O/P is:
thriller is the sixth studio album

DR. NIDHI AHUJA 58


• The method replaces () a segment of
the string.
4. String
Operations • For example,
A = Michael Jackson is the best
B = A. replace (‘Michael’, ‘Janet’)

O/P: Janet Jackson is the best

DR. NIDHI AHUJA 59


• The method find () finds sub-strings.
The argument is the sub-string you
would like to find.
4. String
• For example, Name = ‘Michael
Operations Jackson’
Name.find(‘el’) = 5
Name.find(‘Jack’) = 8

Note: The output is the first index of


the sequence.
DR. NIDHI AHUJA 60
• If the sub-string which you want to
find is not in the string then the
output is -1.
Points to For example, Name.find (‘&’) = -1
Remember
• While using slicing e.g. Name[0:4] =
Mich; The first number ‘0’ means the
index (i.e. start at 0) and the second
number ‘4’ means the length from the
index to the last element you want.
DR. NIDHI AHUJA 61
Points to
• If A = “1” and B = “2” then
Remember
• A+ B = 12

DR. NIDHI AHUJA 62


,

• Letter ="Dear <|Name|>, You are selected!


on <|Date|>"

Program • Name = input ("Enter your name")


• Date = input ("Enter the Date")

• Letter = Letter.replace ("<|Name|>", Name)


• Letter = Letter.replace ("<|Date|>", Date)
• print (Letter)

DR. NIDHI AHUJA 63


Data Structures
1. Lists and • Lists and Tuples are called compound
Tuples data types and are one of the key
types of data structures in Python.

DR. NIDHI AHUJA 64


• These are an ordered sequence.

Tuples • Tuples are expressed as comma


separated elements within
parentheses.

• For example, Ratings = (10, 9, 6, 5, 10,


8, 9, 6, 2)

DR. NIDHI AHUJA 65


• In Python, there were different types:
• Strings
Tuples • Integer
• Float

• They can all be contained in a tuple


but the type of variable is tuple.

DR. NIDHI AHUJA 66


• For example,
Tuples Tuple 1 = (‘disco’, 10, 1.2)
Tuple 1 [1:] gives you (10, 1.2)

• Type (Tuple 1) = tuple

DR. NIDHI AHUJA 67


• Each element of a tuple can be
accessed via an index.
Tuples
• For example,
tuple 1[0] = ‘disco’ = tuple 1[-3]
tuple 1[2] = 1.2 = tuple [-1]

DR. NIDHI AHUJA 68


• We can also concatenate tuples by
adding them.
Tuples
• For example, tuple 1 + (“hard
rock”, 10) gives

(“disco”, 10, 1.2, “hard rock”, 10)

DR. NIDHI AHUJA 69


• We can give two commands
Tuples together in Python.

• For example, print


(type(tuple1[1]))

DR. NIDHI AHUJA 70


• Tuple 2 [0:3] = (‘disco’, 10, 1.2)

Tuples: Slicing Length:


Len (tuple 2) = 5

• Tuples are immutable i.e. we cant


change them.

DR. NIDHI AHUJA 71


• Note: If you would like to
manipulate a tuple we must create
Tuples: Slicing a new tuple instead.

• For example, If we would like to


sort a tuple we use the function
sorted.

DR. NIDHI AHUJA 72


• Ratings = (10, 9, 6, 5, 10, 8, 9, 6, 2)
Tuples: Slicing
• RatingsSorted = sorted (Ratings)

• O/P is:
[2, 5, 6, 6, 8, 9, 9, 10, 10]

DR. NIDHI AHUJA 73


• Note: A tuple can contain other
tuples as well as other complex
data types.
Tuples: Slicing
• NT = (1, 2, (“pop”, “rock”), (3, 4),
(“disco”, (1,2)))

• This is called nesting.

DR. NIDHI AHUJA 74


• We can access these elements
using the standard indexing
methods.

Tuples: Slicing • For example,


NT[2] = (“pop”, “rock”)[1]
= “rock”
OR
NT[2][1] = “rock”

DR. NIDHI AHUJA 75


• We can visualize this nesting as
tree.
• We can also access the different
characters in the string or various
Tuples: Slicing elements in the 2nd tuple
contained in the first.
• For example,
NT[2][1] = “rock”
NT[2][1][0] = r
NT[2][1][1]=0 etc.
DR. NIDHI AHUJA 76
Tuples: Slicing
• We can also call to print like:
print(“Element 0 of NT:”, NT[1])

DR. NIDHI AHUJA 77


• Tuples cannot use function sort but
Tuples: Slicing lists can.

• For example, Name.sort () is not


allowed.

DR. NIDHI AHUJA 78


• Lists are also a popular data
structure in Python.

Lists • Lists are also an ordered sequence


and can be created with different
data types.

• A list is represented with square


brackets.
DR. NIDHI AHUJA 79
• For example, L = [“Michael
Jackson”, 10.1, 1982]
Lists
• In many respects lists are like
tuples.

• One key difference is they are


mutable i.e. lists can be edited.

DR. NIDHI AHUJA 80


• Lists can contain strings, floats,
integers. We can nest other lists.
Lists
• For example, L = [“Michael
Jackson”, 10.1, 1982, [1, 2], (‘A’, 1)]

• We can nest tuples and other data


structures.

DR. NIDHI AHUJA 81


• Like tuples, each element of a list
can be accessed via an index like
L[0] = “Michael Jackson”
Lists
• L1 = [6, 1, 11, 2, 50]
L1.sort () gives you [1, 2, 6, 11, 50]
This will sort the original variable (In
this case L1)

DR. NIDHI AHUJA 82


• We can also perform slicing in lists.

Lists • For example, L[3:5] = [[1,2], (‘A’,1)]

• Note: The index conventions for


lists and tuples are identical.

DR. NIDHI AHUJA 83


• We can also concatenate or
combine lists by adding them.

Lists • For example, L = [“Michael


Jackson”, 10.1, 1982]

• L1 = L + [“pop”, 10]

• O/P: L1 = [“Michael Jackson”, 10.1,


1982, “pop”, 10]
DR. NIDHI AHUJA 84
• Note: Lists are mutable so we can
change them.
Lists
• Like L = [1, 2, 3]
• If L[0] = 6 then L becomes [6, 2, 3]

• For example, L = [“Michael


Jackson”, 10.1, 1982]

DR. NIDHI AHUJA 85


Extend function
• L.extend ([“pop”, 10])

Lists O/P is L = [“Michael Jackson”, 10.1,


1982, “pop”, 10]

• To find the index of “Michael


Jackson” in tuple
• L. index (“Michael Jackson”)
DR. NIDHI AHUJA 86
Another similar method is append.
If we apply append method instead
of extended, we add one element to
the list.
Lists
For example, L = [“Michael Jackson”,
10.1, 1982]
L.append([“pop”, 10])

O/P: L = [“Michael Jackson”, 10.1,


1982, [“pop”, 10]]
DR. NIDHI AHUJA 87
• Every time we apply a method the
list changes. If we apply extend, we
add two new elements to the list. If
we append the string A, we further
Lists change the list, adding the string A.
L.append (“A”) – this adds the value
at the end of the list.

• L = [“Michael Jackson”, 10.1, 1982,


“pop”, 10, “A”]

DR. NIDHI AHUJA 88


• As lists are mutable, we can change
them.

Lists • For example, we can change the


first element as:
A = [“disco”, 10, 1.2]
A[0] = “hard rock”

O/P is A = [“hard rock”, 10, 1.2]


DR. NIDHI AHUJA 89
• L1. reverse () gives you list in
reverse order.
Lists
• L1. pop (2) removes the value
which is at 2nd index.

• We can delete the element of a list


using del command.

DR. NIDHI AHUJA 90


• A = [“hard rock”, 10, 1.2]
Lists • del(A[0])

• Output is
A = [10, 1.2]

DR. NIDHI AHUJA 91


• We can convert a string to a list
using split.
Lists
• For example, “hard rock”.split ()

• O/P is [“hard”, “rock”]

DR. NIDHI AHUJA 92


• L1.insert (3, 50) adds ‘50’ value at
Lists 3rd place.

• For example, L1 = [1, 2, 3, 5]


• L1.insert (3, 50) gives [1, 2, 3, 50, 5]

DR. NIDHI AHUJA 93


• When we set one variable B = A,
both A and B are referencing the
same list.
Lists: Aliasing
• Multiple names referring to the
same object is known as aliasing.

• i.e. A = B = [“hard rock”, 10, 1.2]

DR. NIDHI AHUJA 94


• Thus, if we change the 1st element
in A to “banana”.
Lists: Aliasing
• i.e. if A[0] = “banana”

• Then the value of B will also change


as a consequence.

DR. NIDHI AHUJA 95


• A and B are referencing the same
Lists: Aliasing list, thus, if we change A, list B also
changes. For this, we need to
create clone of the lists as:
B = A[:]

DR. NIDHI AHUJA 96


• Now if you change A, B will not
Lists: Aliasing change,
A[0] = “banana”
Thus, A = [“banana”, 10, 1.2] but
B = [“hard rock”, 10, 1.2]

DR. NIDHI AHUJA 97


• Sets are a type of collection.

• This means that like lists and


2. Sets tuples, you can input different
Python Types.

• Note: Unlike lists and tuples, they


are unordered. This means sets do
not record element position.
DR. NIDHI AHUJA 98
• Sets only have unique elements.

Sets • This means there is only one of the


particular element in a set.

• To define a set, you use curly


brackets.

DR. NIDHI AHUJA 99


• Set 1 = {“pop”, “rock”, “soul”, “hard
rock”, “rock”, “disco”}

Sets • Since there are duplicate items in


Set1. When the actual set is
created, duplicate items will not be
present.

• Set 1: {“pop”, “rock”, “soul”, “hard


rock”, “disco”}
DR. NIDHI AHUJA 100
Sets • b=set() is an empty set.

• Thus, b.add(4) gives b = {4}

DR. NIDHI AHUJA 101


• Note: You can’t add list within a set
but we can add tuple. Also, can’t
Sets add dictionary too because these
are mutable.

• You can convert a list to a set by


using function ‘set’. This is called
type casting.

DR. NIDHI AHUJA 102


• For example,
album_list = [“Michael Jackson”,
“Thriller”, 1982, “Thriller”]
Sets
Album_set = set(album_list)

O/P is: Album_set:{‘Michael


Jackson’, ‘Thriller’, 1982}

DR. NIDHI AHUJA 103


• Let A = {“Thriller”, “Back in Black”,
“AC/DC”}

• These can be shown as Venn


Set Operations Diagrams.

1. We can add an item to a set


using ‘add’ method.
A.add(‘NSYNC’)
Note: add () only takes exactly one
argument.
DR. NIDHI AHUJA 104
• O/P is A: {“Thriller”, “Back in
Set Operations Black”, “NSYNC”, AC/DC”}

• Note: If we add some item twice,


nothing will happen as there can
be no duplicates in a set.

DR. NIDHI AHUJA 105


• 2. To remove an item from a set
using
A.remove (“Thriller”)
Set Operations
O/P is A:{“Back in Black”, “NSYNC”,
“AC/DC”}

• Now, set A does not contain the


item “Thriller”
DR. NIDHI AHUJA 106
• 3. To verify if an item is in the set
using “in” command.

Set Operations • For example, “AC/DC” in A

• O/P is True

• If the item is in the set, it returns


true and if not then returns false.
DR. NIDHI AHUJA 107
Note: Sets are
• Unordered i.e. order doesn’t
Set Operations matter
• Can’t contain duplicate items
• Unindexed means can’t access by
index
• Can’t change items in sets

DR. NIDHI AHUJA 108


Mathematical
Operations
• Album_set1 = {“A”, “B”, “C”, “D”}
1. Intersection • Album_set2 = {“B”, “E”, “D”, “F”}
(&)
Album_set1.intersection (
album_set2)

DR. NIDHI AHUJA 109


Mathematical
Operations O/P is album_set3 : {“B”, “D”}

1. Intersection • b.pop() removes any value from


set.
(&)
• b.clear () empties the set

DR. NIDHI AHUJA 110


Mathematical
Operations
• In sets, S = {20, 20.0, “20”} has
length = 2 since 20 is same as 20.0.
1. Intersection
(&)

DR. NIDHI AHUJA 111


Mathematical
Operations
• Album_set1.union(album_set2)

2. Union
• {“A”, “B”, “C”, “D”, “E”, “F”}

DR. NIDHI AHUJA 112


• Consider album_set1 and
Mathematical album_set3 (as in intersection
Operations heading)

3. Subset • To check subset,


Album_set3.issubset(album_set1)

O/P returns True or False

DR. NIDHI AHUJA 113


Mathematical
Operations • album_set1.difference(album_set
2)

4. Difference
• gives you the element of A which
are not in B.

DR. NIDHI AHUJA 114


Mathematical
Operations
• album_set1.issuperset(album_set
5. Superset 2)

DR. NIDHI AHUJA 115


• Dictionaries are a type of
collection of key-value in Python.

3. Dictionaries • If we recall, a list has integer


indexes. These are like addresses.
A list also has elements.
Index Elements
0 1
1 2
2 3
… …
DR. NIDHI AHUJA 116
Dictionaries are:
3. Dictionaries
• Mutable
• Indexed
• Cannot contain duplicate key

DR. NIDHI AHUJA 117


• The key is analogous to the index
they are like addresses but they
3. Dictionaries don’t have to be integers.

• They are usually characters, the


values are similar to the elements
in a list & contain info.

DR. NIDHI AHUJA 118


Dictionaries are:

Key Values /
Elements
3. Dictionaries Key 1 Value 1
Key 2 Value 2
Key 3 Value 3
… …

DR. NIDHI AHUJA 119


• To create a dictionary, we use curly
brackets.

3. Dictionaries • The keys are the first elements,


they must be immutable and
unique.

• Each key is followed by a value


separated by a colon.
DR. NIDHI AHUJA 120
• The values can be immutable,
mutable and duplicates.

3. Dictionaries • Each key and value pair is


separated by a comma.

• For example: {“key1”:1, “key2”:2,


“key3”:[3,3,3], “key4”: (4,4,4),
(‘key5’):5}
DR. NIDHI AHUJA 121
• Consider the following example of
dictionary
A={‘Thriller’:1982, “Back in
3. Dictionaries Black”:1980, “The Dark side of the
moon”:1973, “The
Bodyguard”:1992}

• Here the album title is key and the


value is the released date.

DR. NIDHI AHUJA 122


• Thus, we can see this as:
3. Dictionaries Key Values
“Thriller” 1982
“Back in Black” 1980
“The Dark Side of 1973
Moon”
“The Bodyguard” 1992

DR. NIDHI AHUJA 123


• We can also assign the dictionary to
a variable. The Key is used to look
up the value.
3. Dictionaries
• For example, A [“Thriller”] gives
you 1980

• We can add a new entry to the


dictionary as follows:
A[‘Graduation’] = ‘2007’
DR. NIDHI AHUJA 124
• We can also delete an entry as:
del (A[‘Thriller’])
3. Dictionaries
• We can verify if an element is in the
dictionary using
‘The Bodyguard’ in DICT
• If they are in dictionary, we get true
otherwise false.

DR. NIDHI AHUJA 125


• In order to see all the keys in a
dictionary, we can use the method
keys to get the keys.
3. Dictionaries
A.keys()

O/P: [‘Thriller’, “Back in Black”, “The


Dark side of the moon”, “The
Bodyguard”]

DR. NIDHI AHUJA 126


• In the same way, we can obtain the
3. Dictionaries values as:
A.values()

O/P: [“1982”, “1980”, “1973”, “1992”]

DR. NIDHI AHUJA 127


• A.items () gives you all the items
present in a dictionary.

• A.update ({“Graduation”:”abc”})
3. Dictionaries will add to dictionary.

• A.get (“Thriller”) gives you 1982

• Note: If any key is not present in


dictionary, get function gives you
none but in simple case like
DICT[“Thriller”] gives you error.
DR. NIDHI AHUJA 128
Thank you

DR. NIDHI AHUJA 129

You might also like