Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
48 views

AR20 Python Unit-II

The document discusses various concepts in Python programming including decision making statements like if, if-else and elif. It also covers loops like for and while loops. Some key points discussed include the syntax and usage of if-else, elif, nested if, for loop with range function, while loop, break, continue and pass statements. The document also provides an introduction to data structures in Python mentioning lists, tuples, sets, dictionaries and comprehensions.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
48 views

AR20 Python Unit-II

The document discusses various concepts in Python programming including decision making statements like if, if-else and elif. It also covers loops like for and while loops. Some key points discussed include the syntax and usage of if-else, elif, nested if, for loop with range function, while loop, break, continue and pass statements. The document also provides an introduction to data structures in Python mentioning lists, tuples, sets, dictionaries and comprehensions.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 128

RAGHU ENGINEERING COLLEGE

Python Programming
Unit-II

Python Programming Raghu Engineering College 1


Decision Making
• if
• if else
• elif
• Nested if
• loops

Python Programming Raghu Engineering College 2


if - statement

if statement syntax:
if test expression:
statement(s)

In Python, the body of the if statement is indicated by the indentation. Body starts with an
indentation and the first un indented line marks the end.
Example:
num = 3
if num > 0:
print(num, "is a positive number.")
print("This is always printed.")
Python Programming Raghu Engineering College 3
if else
Syntax of if...else:
if test expression:
Body of if
else:
Body of else

body of if only when test condition is True. If the condition is False, body of else is
executed. Indentation is used to separate the blocks.

Example:
if num >= 0:
print("Positive or Zero")
else:
print("Negative number")

Python Programming Raghu Engineering College 4


elif
Syntax of if...elif...else:
if test expression:
Body of if
elif test expression:
Body of elif
else:
Body of else
• The elif is short form for else if. It allows us to check for multiple expressions.
• If the condition for if is False, it checks the condition of the next elif block and so on.
• If all the conditions are False, body of else is executed.
• Only one block among the several if...elif...else blocks is executed according to the
condition.

Python Programming Raghu Engineering College 5


Multiple elif blocks

• The if block can have only one else block. But it can have
multiple elif blocks.
Example:
if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")

Python Programming Raghu Engineering College 6


Nested if

• We can have a if...elif...else statement inside


another if...elif...else statement. This is called nesting in computer
programming.

• Any number of these statements can be nested inside one another.


Indentation is the only way to figure out the level of nesting.

Python Programming Raghu Engineering College 7


Loops

Loops are often used when we have a piece of code that we need to repeat for
(i) N number of times or (ii) until a condition becomes true or false

Concepts in loops:
• For loop
• While loop
• Nested loops
• Break
• Continue

Python Programming Raghu Engineering College 8


for loop
for, is often used when we have a piece of code which we want to repeat "n" number
of times.
Syntax:
for variable in range(start,end[,step]):
body of the for loop
Example:
for i in range(1,5):
print(i)
Output:
1
2
3
4

Range function iterates i value starting from 1st argument up to but not including 2nd
argument. So i value is iterated only up to 4, but not 5
Python Programming Raghu Engineering College 9
for loop
The third argument in range function indicates the difference between each
number in the sequence:

Example:
for i in range(1,10,2):
print(i)
Output:
1
3
5
7
9

Python Programming Raghu Engineering College 10


for loop
Difference can also have a negative value
Example:
for i in range(0,-10,-2):
print(i)

Output:
0
-2
-4
-6
-8
Python Programming Raghu Engineering College 11
while loop
A while loop statement in Python programming language repeatedly executes a target
statement as long as a given condition is true.
Syntax:
while test_expression:
body
Example:
n = 10
i=1
while i <=n:
if(i%2!=0):
print(i,end=" ")
i=i+1
Output:
13579

Python Programming Raghu Engineering College 12


Nested loops
Python programming language allows to use one loop inside another loop.

Syntax for nested for loop:


for iterating_var in sequence:
for iterating_var in sequence:
statements(s)
statements(s)

syntax for a nested while loop:


while expression:
while expression:
statement(s)
statement(s)

Python Programming Raghu Engineering College 13


Nested loops
Example :
n=5
for row in range(1,n+1):
for col in range(1,row+1):
print(row,end=" ")
print()

Output:
1
22
333
4444
55555
Python Programming Raghu Engineering College 14
Break statement
The break statement terminates the loop containing it. Control of the program
flows to the statement immediately after the body of the loop.

Example:
for val in "string":
if val == "i":
break
print(val)
Output:
s
t
r
• If break statement is inside a nested loop (loop inside another loop), break will
terminate the innermost loop.

Python Programming Raghu Engineering College 15


Continue Statement
The continue statement is used to skip the rest of the code inside a loop for the
current iteration only. Loop does not terminate but continues on with the next
iteration.

Example:
for val in "string":
if val == "i":
continue
print(val)
Output:
s
t
r
n
g

Python Programming RAGHU ENGINEERING COLLEGE 16


pass
• The pass statement is a null operation; nothing happens when it executes.

• The pass statement in Python is used when a statement is required syntactically but you
do not want any command or code to execute.

• Sometimes there may be situations so that we do not want to execute any statement when
a particular condition is true or false.

• Example: Consider the code shown in next slide.

Python Programming Raghu Engineering College 17


pass - Example

x=5
y=10
if(x==y):
else:
print("not equal")

Here we do not want to execute any statement when the if condition becomes true,
but when this code is executed, we get an error saying “expected and indented block”.

Python Programming Raghu Engineering College 18


pass - Example
In such cases we can use pass keyword:

x=5
y=10
if(x==y):
pass
else:
print("not equal")

pass keyword can be used in all the control flow statements like if, elif, else, for ,while.

Python Programming Raghu Engineering College 19


Data Structures
• A data structure is a data organization and storage format that enables efficient access
and modification.
• A data structure is a group of data elements that are put together under one name.
• Data structure defines a particular way of storing and organizing data in a computer
so that it can be used efficiently.
• More precisely, a data structure is a collection of data values, the relationships among
them, and the functions or operations that can be applied to the data.
• Sequence is the most basic data structure in Python. In sequence, each element has a specific
index. This index value starts from zero and is automatically incremented for the next element.
In Python, sequence is the generic term for an ordered set.

Python Programming Raghu Engineering College Slide 20


Data Structures in Python

• List

• Tuple

• Set

• Dictionary

• Comprehension

Python Programming Raghu Engineering College Slide 21


List
• A list is a data structure in Python that is a mutable, or changeable, ordered sequence of
elements. Each element or value that is inside of a list is called an item.

• It is a sequence in which elements are written as a list of comma-separated values


(items) between square brackets.

• The key feature of a list is that it can have elements that belong to different data types.

• Syntax to create a list,


list_name=[item1,item2,item3,item4,….]

Python Programming Raghu Engineering College Slide 22


List

Program: Program:
l=[10,16,1000,98] l=[10,16.53,"hello"]
print(l) print(l)

Sample output: Sample output:


[10, 16, 1000, 98] [10, 16.53, 'hello']

Python Programming Raghu Engineering College 23


List

•Each item in a list corresponds to an index number, which is an


integer value, starting with the index number 0.

• Python allows negative indexing for its sequences.

•The index of -1 refers to the last item, -2 to the second last item
and so on.

•We can access the list item by its index as below,


list_name[index_value]

Python Programming Raghu Engineering College Slide 24


List

list1 = ['tiger','lion','dog','cat','horse']

For this list:


• list1[0] is ‘tiger’
• list1[1] is ‘lion’
• list1[-1] is ‘horse’
• list1[-2] is ‘cat’

Python Programming Raghu Engineering College


List : using slice operator

• Similar to strings, lists can also be sliced and concatenated.

• To access values in lists, square brackets are used to slice along with
the index or indices to get value stored at that index.

• The syntax for the slice operation is given as, seq =


List[start:stop:step]

Python Programming Raghu Engineering College


List : using slice operator

Python Programming Raghu Engineering College


List : using slice operator

>>> a=[5,10,15,20,25] Using + and * on lists:

>>> a[:3] >>>a=[1,2,3]


>>> b=[4,5]
[5, 10, 15]
>>> a+b
>>> a[2:]
[1, 2, 3, 4, 5]
[15, 20, 25]
>>> b*3
>>> a[:]
[4, 5, 4, 5, 4, 5]
[5, 10, 15, 20, 25]
Python Programming Raghu Engineering College
List

We can reverse a list, just by providing -1 for step:


>>> x=[12,10,6,19,13]
>>> x[::-1]
[13, 19, 6, 10, 12]

A List can contain another list as member:


>>> list1=[1,2]
>>> list2=[1.5,3,list1]
>>> list2
[1.5, 3, [1, 2]]
Python Programming Raghu Engineering College
List

Presence of a item in a list can be


tested using in operator:
Syntax: item in list_name >>> x=[5,'6',7,'8']
>>> x=[1,2,3,4]
>>> 6 in x
>>> 2 in x
True False
>>> 10 in x
>>> '6' in x
False
True
Python Programming Raghu Engineering College
Traversing a List

• The most common way to traverse the elements of a list is with


a for loop.
• This works well if you only need to read the elements of the list.
• But if you want to write or update the elements, you need the indices.
• Syntax:

for variable in list_name: for variable in range(0,len(list_name):


#statements #statements

Python Programming Raghu Engineering College


Traversing a List: Example

Program: Program:
x=[5,10,15,20,25] x=[5,10,15,20,25]
for i in x: for i in range(0,len(x)):
print(i,end=" ") print(x[i],end=" ")

Sample Output: Sample Output:


5 10 15 20 25 5 10 15 20 25

Python Programming Raghu Engineering College


Traversing a List: Example

Program:
cities=["vizag","hyderabad","delhi","mumbai"]
for city in cities:
print(city,end=" ")

Sample Output:
vizag hyderabad delhi mumbai

Python Programming Raghu Engineering College


Reading a List at run time
• To read a list of values separated by space at run time:
• Syntax: list_name=list(input().split())
l = list(input().split())

• split() function assumes the default argument as space. Instead of space, any
other symbol can also be used as a separator between values as shown
below:
l = list(input().split(“,”))
Here user needs to enter list of values separated by comma.

Python Programming Raghu Engineering College


Reading a List at run time: Examples

Program: Program:
l = list(input().split()) l = list(input().split(","))
print(l) print(l)

Sample Input: Sample Input:


abc xyz hello pqr abc,xyz,hello,pqr

Sample Output: Sample Output:


['abc', 'xyz', 'hello', 'pqr'] ['abc', 'xyz', 'hello', 'pqr']
Python Programming Raghu Engineering College
Reading a List at run time: Examples

Converting to int while reading: Converting to float while reading:


Program: Program:
il=list(map(int,input().split())) il=list(map(float,input().split(",")))
print(il) print(il)

Sample Input: Sample Input:


10 20 30 40 50 10,20,30,40,50
Sample Output: Sample Output:
[10, 20, 30, 40, 50] [10.0, 20.0, 30.0, 40.0, 50.0]
Python Programming Raghu Engineering College
Modifying items in Lists

• Once created, one or more elements of a list can be easily updated by


using the index on the left-hand side of the assignment operator.

• You can also append new values in the list and remove existing value(s)
from the list using the append() method and del statement respectively.

Python Programming Raghu Engineering College


Modifying items in Lists

Python Programming Raghu Engineering College


Modifying items in Lists

using insert() using pop()


Syntax: Syntax: list_name.pop(index)
list_name.insert(index,item) Program:
Program: l=[5,10,15,20,25]
l=[5,10,15,20,25] l.pop(2)
l.insert(2,30) print(l)
print(l) Sample Output:
Sample Output: [5, 10, 20, 25]
[5, 10, 30, 15, 20, 25]

Python Programming Raghu Engineering College


List Methods

Python Programming Raghu Engineering College


List Methods

Python Programming Raghu Engineering College


List Methods

Python Programming Raghu Engineering College


List Methods
• len(list): Gives the total length of the list.

• max(list) : Returns item from the list with max value.

• min(list): Returns item from the list with min value.

• list(seq): Converts a sequence into list.

• sum(list): Returns the arithmetic total of all items in list,


items must be numeric

Python Programming Raghu Engineering College


List Methods: Examples

Program: Program:
s="hello" list1=[1,2,3,4]
print(s) print(sum(list1))
l=list(s)
print(l) Sample Output:
Sample Output: 10
hello
['h', 'e', 'l', 'l', 'o']

Python Programming Raghu Engineering College


List: Example on looping in list

Python Programming Raghu Engineering College


Nested Lists

Nested list is a list within another list.

Python Programming Raghu Engineering College


Nested Lists: Traversing

Program: Program:
l=[[1,2,3],[4,5,6]] l=[[1,2,3],['abc','xyz'],[4,5,6]]
print(l[0][2]) print(l[1][1])
print(l[1][0]) print(l[1][1][2])
print(l[1][1]) print(l[2])
Sample Output: Sample Output:
3 xyz
4 z
5 [4, 5, 6]
Python Programming Raghu Engineering College
Nested Lists: Traversing

Program:
a=[[1,2,3,4],[5,6],[7,8,9]]
for i in range(len(a)):
for j in range(len(a[i])):
print(a[i][j],end=" ")
print()
Sample Output:
1234
56
789

Python Programming Raghu Engineering College


Nested Lists: Traversing

Program:
a=[[1,2,3,4],[5,6],[7,8,9]]
for row in a:
for ele in row:
print(ele,end=" ")
print()
Sample Output:
1234
56
789

Python Programming Raghu Engineering College


Reading a Nested List at run time

Program:
r=int(input()) # r represents number of rows(or number of lines)
list2d=[] # list2d represents variable name of a 2d list
for i in range(r): # repeating for r times
list1d=list(map(int,input().split())) # reading each line into 1d list
list2d.append(list1d) # appending 1d list into a 2d list
print(list2d)

Python Programming Raghu Engineering College


Nested List: Output for program in last slide

Sample input2:
Sample input1: 4
3 12
1234 3456
9
5678
3614721
2341
Sample output2:
Sample output1: [[1, 2], [3, 4, 5, 6], [9], [3, 6, 1, 4, 7,
[[1, 2, 3, 4], [5, 6, 7, 8], [2, 3, 4, 1]] 2, 1]]
Python Programming Raghu Engineering College
Cloning Lists
• If we try to copy one list into the other by using assignment operator, now both the lists will
be allocated same addresses.

• Only a reference is created, not another copy of list.

• This means that both the lists will be treated as same objects.

• So if a change is made in one list, it will be reflected to the other list also.
list1=[10,20,30,40,50]
list2=list1 #copying using assignment operator

Python Programming Raghu Engineering College


Cloning Lists

• If we want to modify a list and also keep a copy of the original list, then we
should create a separate copy of the list (not just the reference).
• This process is called cloning. In this cloning process the new list called as
Shallow copy
• The slice operation or copy() function is used to clone a list.

list2=list1[:] #copying using slice operator


or
list2=list1.copy()
Python Programming Raghu Engineering College
Cloning Lists

Program: Program:
list1=[10,20,30,40,50] list1=[10,20,30,40,50]
list2=list1 list2=list1[:] #copying using slice
list2[1]=25 #both lists are modified list2[1]=25 #only list2 is modified
print(list1) print(list1)
print(list2) print(list2)
Sample Output: Sample Output:
[10, 25, 30, 40, 50] [10, 20, 30, 40, 50]
[10, 25, 30, 40, 50] [10, 25, 30, 40, 50]
Python Programming Raghu Engineering College
List Comprehensions
• Python also supports computed lists called list comprehensions having
the following syntax.

• List = [expression for variable in sequence]


• Where, the expression is evaluated once, for every item in the sequence.

• This is mainly beneficial to make new lists where each element is


obtained by applying some operations to each member of another
sequence or iterable.

Python Programming Raghu Engineering College


List Comprehensions

Program: Program:
squares=[] squares=[i**2 for in range(11)]
for i in range(11): print(squares)
squares.append(i**2)
print(squares) Sample Output:
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81,
Sample Output: 100]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81,
100]

Python Programming Raghu Engineering College


List Comprehensions

Program: Program:
odds=[] l=range(1,11)
for i in range(1,11): odd=[x for x in l if x%2==1]
if i%2!=0: print(odd)
odds.append(i)
print(odds) Sample Output:
Sample Output: [1, 3, 5, 7, 9]
[1, 3, 5, 7, 9]

Python Programming Raghu Engineering College


Task on List Comprehension

• Write a program to generate a list of prime numbers


between 1 to 100 using list comprehension
• L=[i for i in range(2,101) if 0 not in[i%j for j in
range(2,i//2+1)]]

Python Programming Raghu Engineering College


Using sorted() and sort() functions

• The sorted() method sorts the elements of a given iterable in a specific


order - Ascending or Descending.

• A list also has sort() method which performs the same way as sorted().

• Only difference being, sort() method doesn't return any value and
changes the original list itself where as sorted() method only returns
sorted list but it does not change the original list.

Python Programming Raghu Engineering College


Using sorted() and sort() functions

Program: Program:
l=[50,20,40,10,30] l=[50,20,40,10,30]
print(sorted(l)) l.sort()
print(l) #original list not sorted print(l) #original list sorted

Sample Output: Sample Output:


[10, 20, 30, 40, 50] [10, 20, 30, 40, 50]
[50, 20, 40, 10, 30]

Python Programming Raghu Engineering College


Using sorted() and sort() functions

Program: Program:
l=['mech','eee','ece','civil','cse'] l=['mech','eee','ece','civil','cse']
l.sort()#strings sorted alphabetically print(sorted(l))
print(l) print(l)

Sample Output: Sample Output:


['civil', 'cse', 'ece', 'eee', 'mech'] ['civil', 'cse', 'ece', 'eee', 'mech']
['mech', 'eee', 'ece', 'civil', 'cse']

Python Programming Raghu Engineering College


Using sorted() and sort() functions

Program: Program:
l=['mech','eee','ece','civil','cse'] l=[50,20,10,40,30]
l.sort(reverse=True) #descending print(sorted(l,reverse=True))
print(l) print(l)

Sample Output: Sample Output:


['mech', 'eee', 'ece', 'cse', 'civil'] [50, 40, 30, 20, 10]
[50, 20, 10, 40, 30]

Python Programming Raghu Engineering College


enumerate() function
enumerate() function is used when we want to print both index as well as
an item in the list.

Python Programming Raghu Engineering College


enumerate() function
Program:
fruits=['apple','banana','gauva','papaya','kiwi','lime','orange','melon','raspberry','strawberry']
fr=enumerate(fruits)
print(list(fr))
fr=enumerate(fruits,5)
print(list(fr))
Sample Output:
[(0, 'apple'), (1, 'banana'), (2, 'gauva'), (3, 'papaya'), (4, 'kiwi'), (5, 'lime'), (6, 'orange'), (7, 'melon'),
(8, 'raspberry'), (9, 'strawberry')]
[(5, 'apple'), (6, 'banana'), (7, 'gauva'), (8, 'papaya'), (9, 'kiwi'), (10, 'lime'), (11, 'orange'), (12,
'melon'), (13, 'raspberry'), (14, 'strawberry')]

Python Programming Raghu Engineering College


Tuple
• Like lists, tuple is another data structure supported by Python. It is very
similar to lists but differs in two things.

• First, a tuple is a sequence of immutable objects.

• This means that while you can change the value of one or more items in
a list, you cannot change the values in a tuple.

• Second, tuples use parentheses to define its elements whereas lists use
square brackets.

Python Programming Raghu Engineering College


Creating Tuple
• Creating a tuple is very simple and almost similar to creating a list.

• For creating a tuple, generally we need to just put the different comma-
separated values within a parentheses as shown below:

t = (val1, val2,….. )

Example: t=(10,20,30,40,50)

• t[2]=55 is not possible because tuple is mutable.

Python Programming Raghu Engineering College


Accessing Values in a Tuple
• Like other sequences (strings and lists) covered so far, indices in a tuple
also starts at 0.

• We can even perform operations like slice, concatenate, etc. on a tuple

• For example, to access values in tuple, slice operation is used along with
the index or indices to obtain value stored at that index

Python Programming Raghu Engineering College


Accessing Values in a Tuple

Program:
t=(10,20,30,40,50,60,70,80) Sample Output:
print(t[2:4]) (30, 40)
print(t[1:]) (20, 30, 40, 50, 60, 70, 80)
print(t[:5]) (10, 20, 30, 40, 50)
print(t[-2]) 70

Python Programming Raghu Engineering College


Updating a Tuple
Tuples are immutable which means you cannot update or change the values
of tuple elements but two tuples can be concatenated as shown:

Program:
t1=(10,20,30,40,50)
t2=("abc","xyz")
t3=t1+t2
print(t3)
Sample Output:
(10, 20, 30, 40, 50, 'abc', 'xyz')

Python Programming Raghu Engineering College


Deleting a Tuple
Since tuple is an immutable data structure, you cannot delete value(s) from
it, but an entire tuple can be removed.

t1=(10,20,30,40,50)
del t1[2] or t1.remove(30) will not work

instead, del t1 can be used which deletes the entire tuple.

Python Programming Raghu Engineering College


Tuple Operations

Python Programming Raghu Engineering College


Tuple Assignment

Python Programming Raghu Engineering College


Tuples : index() and count()
• index() and count() methods can be used just like lists.
• The index of an element in the tuple can be obtained by using the index()
method.
• Syntax: tuple.index(obj) where obj is the object to be found out.

• count() method can be used to find out the number of occurences of an


element within a sequence.
• Syntax: tuple.count(obj) where obj is the object to count.

Python Programming Raghu Engineering College


The zip() function
• The zip() is a built-in function that takes two or more sequences and
"zips" them into a list of tuples.

• The tuple thus, formed has one element from each sequence.

• The * operator can be used in conjunction with zip() to unzip the list.

zip(*zippedList)
Python Programming Raghu Engineering College
The zip() function

Python Programming Raghu Engineering College


unzipping sequences

The * operator can be used in conjunction


with zip() to unzip the list.
Program: Sample Output:
coordinate = ['x', 'y', 'z']
[('x', 3), ('y', 4), ('z', 5)]
value = [3, 4, 5]
result = zip(coordinate, value) c = ('x', 'y', 'z')
resultList = list(result) v = (3, 4, 5)
print(resultList)
c, v = zip(*resultList)
print('c =', c)
print('v =', v)
Python Programming Raghu Engineering College
Sets
• Sets is another data structure supported by Python. Basically, sets are
same as lists but with a difference that sets are lists with no duplicate
entries.

• Technically, a set is a mutable. This means that we can easily add or


remove items from it.

• A set is created by placing all the elements inside curly brackets {},
separated by comma or by using the built-in function set().

Python Programming Raghu Engineering College Slide 77


Sets
• Syntax for creating a set:

• Example: To create a set:

Python Programming Raghu Engineering College Slide 78


Sets
• A set is an unordered collection of elements, which means the order of
items within a set need not be preserved.

• Example:
• st = {1,2,3,4,5}
• When we print st, {1,2,3,4,5} may not be printed in order, but all the
values will be printed definitely without any duplicates.

• Set items cannot be accessed using indices.

Python Programming Raghu Engineering College Slide 79


Sets

Program: Program:
st={1,2,'cse','ece',2,3,'cse'} t=(1,2,'cse','ece',2,3,'cse')
print(st) st=set(t) #converts tuple to set
print(t)
Sample output: print(st)
{1, 2, 3, 'cse', 'ece'} Sample output:
(1, 2, 'cse', 'ece', 2, 3, 'cse')
{1, 2, 3, 'ece', 'cse'}

Python Programming Raghu Engineering College 80


Sets
Program:
Similarly a list can also be l=[1,2,'cse','ece',2,3,'cse']
converted into a set: st=set(l) #converting list to set
print(l)
Syntax: print(st)
set_variable = set(list variable)
or Sample output:
set_variable = set([list values]) [1, 2, 'cse', 'ece', 2, 3, 'cse']
{1, 2, 3, 'ece', 'cse'}

Python Programming Raghu Engineering College 81


Set functions: update()
Program:
Update(): s1={1,2,3,4,5}
Adds elements of one set into s2={6,7,8}
the other set. s1.update(s2)
print(s1)
Syntax: print(s2)
set1.update(set2)
Sample output:
Adds elements of set2 into set1 {1, 2, 3, 4, 5, 6, 7, 8}
{8, 6, 7}
Python Programming Raghu Engineering College 82
Set functions: add()
Program:
add(): s1={1,2,3,4,5}
Adds one element to a set. s1.add(7)
print(s1)
Syntax:
set.add(element) Sample output:
{1, 2, 3, 4, 5, 7}

Python Programming Raghu Engineering College 83


Set functions: remove()

remove(): Program:
syntax: s1={1,2,3,4,5}
s.remove(x) s1.remove(3)
print(s1)
removes element x from set s.
Returns keyerror if x is not Sample output:
present. {1, 2, 4, 5}

Python Programming Raghu Engineering College 84


Set functions: discard()

discard(): Program:
s1={1,2,4,5}
syntax: s1.discard(3)
s.discard(x) print(s1)

same as remove() but does not Sample output:


return an error if x is not {1, 2, 4, 5}
present.

Python Programming Raghu Engineering College 85


Set functions: pop()

pop(): Program:
s1={1,2,3,4,5}
syntax: print(s1.pop())
s.pop() print(s1)

removes and returns any Sample output:


arbitrary element from s. 1
keyerror is raised if s is empty. {2, 3, 4, 5}

Python Programming Raghu Engineering College 86


Set functions: clear()
Program:
clear(): s={1,2,3,4,5}
s.clear()
syntax: print(s)
s.clear() s.add(2)
print(s)
Removes all elements from the
set. Sample output:
Only elements are deleted, not set()
entire set. {2}
Python Programming Raghu Engineering College 87
Set functions: len()

len(): Program:
s={1,2,3,4,5}
syntax: print(len(s))
len(s)
Sample output:
Returns the length of a set s. 5

Python Programming Raghu Engineering College 88


Set operations: in

in: Program:
s={1,2,3,4,5}
syntax: print(7 in s)
x in s
Sample output:
Returns True if x is present in s, False
False otherwise

Python Programming Raghu Engineering College 89


Set operations: not in

not in: Program:


s={1,2,3,4,5}
syntax: print(7 not in s)
x not in s
Sample output:
Returns True if x is not present in True
s,
False otherwise

Python Programming Raghu Engineering College 90


Set functions: issubset()

issubset(): Program:
s={1,2,3,4,5}
syntax: t={1,2,3}
s.issubset(t) print(s.issubset(t))
or
s<=t Sample output:
False
Returns True if s is subset of t,
False otherwise
Python Programming Raghu Engineering College 91
Set functions: issuperset()

issuperset(): Program:
s={1,2,3,4}
syntax: t={1,2,3}
s.issuperset(t) print(s>=t)
or
s>=t Sample output:
True
Returns True if s is superset of t,
False otherwise
Python Programming Raghu Engineering College 92
Set functions: union()

union(): Program:
syntax: s={1,2,3,4,'abc','def'}
s. union(t) t={1,2,3,6,'abc',9}
or print(s.union(t))
s|t
Sample output:
Returns a new set that has {1, 2, 3, 'abc', 4, 'def', 6, 9}
elements from both sets s and t

Python Programming Raghu Engineering College 93


Set functions: intersection()

intersection(): Program:
syntax: s={1,2,3,4,'abc','def'}
s.intersection(t) t={1,2,3,6,'abc',9}
or print(s&t)
s&t
Sample output:
Returns a new set that has {1, 2, 3, 'abc'}
elements which are common to
both sets s and t.
Python Programming Raghu Engineering College 94
Set functions: intersection_update()

intersection_update(): Program:
s={1,2,3,4,'abc','def'}
syntax: t={1,2,3,6,'abc',9}
s. intersection_update(t) s.intersection_update(t)
print(s)
Returns a set s that has elements
which are common to both sets s Sample output:
and t. {1, 2, 3, 'abc'}
s is updated with new values.
Python Programming Raghu Engineering College 95
Set functions: difference()

difference(): Program:
s={1,2,3,4,5,6}
syntax: t={2,5,10,15}
s. difference(t) z=s-t
or print(z)
s-t
Sample output:
Returns a new set that has {1, 3, 4, 6}
elements in s but not in t.
Python Programming Raghu Engineering College 96
Set functions: difference_update()

difference_update(): Program:
s={1,2,3,4,5,6}
syntax: t={2,5,10,15}
s. difference_update(t) s.difference_update(t)
print(s)
Returns a set s that has elements
in s but not in t. And update s Sample output:
with new values. {1, 3, 4, 6}

Python Programming Raghu Engineering College 97


Set functions: symmetric_difference()

symmetric_difference(): Program:
s={1,2,3,4,5,6}
syntax: t={2,5,10,15}
s. symmetric_difference(t) z=s.symmetric_difference(t)
or print(z)
s^t
Sample output:
Returns a new set with elements {1, 3, 4, 6, 10, 15}
in either s or t but not both.
Python Programming Raghu Engineering College 98
Set functions: symmetric_difference_update()

symmetric_difference_udpate(): Program:
s={1,2,3,4,5,6}
syntax: t={2,5,10,15}
s. s.symmetric_difference_update(
symmetric_difference_update(t) t)
print(s)
Returns a set s with elements in Sample output:
either s or t but not both. {1, 3, 4, 6, 10, 15}

Python Programming Raghu Engineering College 99


Set functions: copy()
Program:
copy(): s1={1,2,3,4,5,6}
s2=s1.copy()
syntax: s2.add(7)
s.copy() print(s1)
print(s2)
Returns a copy of set s.
Sample output:
{1, 2, 3, 4, 5, 6}
{1, 2, 3, 4, 5, 6, 7}
Python Programming Raghu Engineering College 100
Set functions: isdisjoint()
Program:
isdisjoint(): s={1,2,3,4,5,6}
t={2,7,8}
syntax: print(s.isdisjoint(t))
s.isdisjoint(t)
Sample output:
Returns True if there are no False
common values in both the sets,
False otherwise

Python Programming Raghu Engineering College 101


Set functions: all()
Program1:
all(): s={True,'2',True,True,6}
print(all(s))
syntax: Sample output1:
all(s) True
Program2:
Returns True if all elements in s={True,0,True,True,6}
the set are True, print(all(s))
False otherwise. Sample output2:
Returns True if the set is empty. False
Python Programming Raghu Engineering College 102
Set functions: any()
Program1:
any(): s={1,0,2,0}
print(any(s))
syntax: Sample output1:
any(s) True
Program2:
Returns True if any of the s={0,0,0,0}
elements in the set are True, print(any(s))
False otherwise. Sample output2:
Returns False if the set is empty. False
Python Programming Raghu Engineering College 103
Set functions: enumerate()

enumerate(): Program:
s={'a','b','c','d'}
syntax: for i in enumerate(s):
enumerate(s) print(i,end=" ")

Returns enumerate object which Sample output:


contains index as well as value of (0, 'd') (1, 'c') (2, 'b') (3, 'a')
all the items of set as pairs.

Python Programming Raghu Engineering College 104


Set functions

• max(s): Returns the maximum value in a set.

• min(s): Returns the minimum value in a set.

• sum(s): Returns the sum of elements in a set.

Python Programming Raghu Engineering College Slide 105


Set functions: sorted()
Program:
sorted(): s={40,20,60,10}
l=sorted(s)
syntax: r=sorted(s,reverse=True)
sorted(s) print(l)
print(r)
Returns a new sorted list, but does print(s)
not sort the set as set is unordered. Sample output:
[10, 20, 40, 60]
[60, 40, 20, 10]
{40, 10, 20, 60}

Python Programming Raghu Engineering College 106


Set operations: == and !=
Program1:
==: s={40,20,60,10}
syntax: t={40,20,60,10}
s==t print(s==t)
Returns True if both lists are equal, Sample output1:
False otherwise True
Program2:
!=: s={40,20,60,10}
syntax: t={40,20,60,10}
Returns True if both lists are not print(s!=t)
equal, Sample output2:
False otherwise. False

Python Programming Raghu Engineering College 107


Dictionaries

• Dictionary is a data structure in which we store items as a pair of key and


value.

• Each key is separated from its value by a colon (:), and consecutive items
are separated by commas.

• The entire items in a dictionary are enclosed in curly brackets{}.

Python Programming Raghu Engineering College Slide 108


Dictionaries
The syntax for defining a dictionary is:
dictionary_name = {key_1: value_1, key_2: value_2, key_3: value_3,…}
Example:
d={'rollno':101,'name':'ram','percent':75.4}
print(d)
Output:
{'rollno': 101, 'name': 'ram', 'percent': 75.4}

Python Programming Raghu Engineering College Slide 109


Dictionaries: Accessing Values
Program:
d={'rollno':101,'name':'ram','percent':75.4}
print(d['rollno'])
print(d['name'])
print(d['percent'])

Sample output:
101
ram
75.4

Python Programming Raghu Engineering College Slide 110


Dictionary: Adding items
items to a dictionary can be added directly by using key, value pair:
syntax:
dictionary_name[key] = value
Program:
d={'rollno':101,'name':'ram','percent':75.4}
d['dept']='cse‘ #adding key, value pair
print(d)
Sample output:
{'rollno': 101, 'name': 'ram', 'percent': 75.4, 'dept': 'cse'}

Python Programming Raghu Engineering College Slide 111


Dictionary: Modifying values
value in a dictionary can be modified directly by using its key.
syntax:
dictionary_name[key] = value
Program:
d={'rollno':101,'name':'ram','percent':75.4}
d['percent']='85.9'
print(d)
Sample output:
{'rollno': 101, 'name': 'ram', 'percent': '85.9'}

Python Programming Raghu Engineering College Slide 112


Dictionary: Deleting items using del
del:
Program:
Syntax: d={'rollno':101,'name':'ram','percent':75.4}
del dictionary_variable[key] del d['name']
print(d)
Deletes the item which is
containing the specified key. Sample output:
{'rollno': 101, 'percent': 75.4}

Python Programming Raghu Engineering College 113


Dictionary: Deleting items using clear()
clear():
Program:
Syntax: d={'rollno':101,'name':'ram','percent':75.4}
dictionary_variable.clear() d.clear()
print(d)
• Deletes all the items from
the list, but empty Sample output:
dictionary still exists. {}
• Dictionary is not removed
from memory.
Python Programming Raghu Engineering College 114
Dictionary: Deleting all items using del
del:
Program:
Syntax: d={'rollno':101,'name':'ram','percent':75.4}
del dictionary_variable del d
print(d)
• del() can also be used for
deleting the entire Sample output:
dictionary. NameError: name 'd' is not defined
• Dictionary is completely
removed from memory.
Python Programming Raghu Engineering College 115
Dictionary: accessing values
values():
Program:
Syntax: d={'rollno':101,'name':'ram','percent':75.4}
dictionary_variable.values() for val in d.values():
print(val,end=" ")
Returns a list of values from
the dictionary. Sample output:
101 ram 75.4

Python Programming Raghu Engineering College 116


Dictionary: accessing keys
keys():
Program:
Syntax: d={'rollno':101,'name':'ram','percent':75.4}
dictionary_variable.keys() for k in d.keys():
print(k,end=" ")
Returns a list of keys from
the dictionary. Sample output:
rollno name percent

Python Programming Raghu Engineering College 117


Dictionary: accessing items
items(): Program:
d={'rollno':101,'name':'ram','percent':75.4}
Syntax: for i in d.items():
dictionary_variable.items() print(i,end=" ")

Returns a list of tuples from Sample output:


dictionary with each tuple ('rollno', 101) ('name', 'ram') ('percent',
containing a key value pair. 75.4)

try for k,v in d.items() in the above code.


Python Programming Raghu Engineering College 118
Dictionaries: functions()
len(dict):

Returns the length of dictionary, that is the number of key value pairs.

in and not in:


Checks whether a given key is present in dictionary or not.

dictionary.get(key):

Returns the value for the key passed as argument. If key is not present, returns None

Python Programming Raghu Engineering College Slide 119


Dictionary functions: str()
str(): Program:
d={'rollno':101,'name':'ram','percent':75.4}
Syntax: e=str(d)
str(dictionary) print(e)
print(e[0])
Returns a string
representation of the Sample output:
dictionary. {'rollno': 101, 'name': 'ram', 'percent': 75.4}
{

Python Programming Raghu Engineering College 120


Dictionary functions: fromkeys()
fromkeys():
Program:
Syntax: students=['st1','st2','st3']
dict.fromkeys(seq[,val]) marks = dict.fromkeys(students,60)
print(marks)
• Creates a new dictionary with
keys from seq and values set to Sample output:
val. {'st1': 60, 'st2': 60, 'st3': 60}
• If no value is specified, None is
assigned as default value.
Python Programming Raghu Engineering College 121
Dictionary functions: update()
update():
Program:
Syntax: d1={'rollno':101,'name':'ram','percent':75.4}
dict1.update(dict2) d2={'branch':'cse','marks':378}
d1.update(d2)
Adds the key value pairs of print(d1)
dict2 to key value pairs of
dict1. Sample output:
{'rollno': 101, 'name': 'ram', 'percent': 75.4,
'branch': 'cse', 'marks': 378}
Python Programming Raghu Engineering College 123
Reading a Dictionary at run time

• First step in reading a dictionary is to read all the elements into a list.
• Now to create a dictionary from this list:
– starting from first element every alternative element should be a key.
– starting from second element every alternative element should be a value.
• This can be done by using the loop:
for i in range(0,len(list),2):
dict[key] = value

Python Programming Raghu Engineering College Slide 124


Reading a Dictionary at run time
consider, list = [rollno,101,name,ram,marks,76]

From this list to create a dictionary, we need to assign key value pairs as
shown below:
dict[‘rollno’] = 101 or dict[list[0]] = list[1]
dict[‘name’] = ‘ram’ or dict[list[2]] = list[3]
dict[‘marks’] = 76 or dict[list[4]] = list[5]
which is nothing but dict[list[i]] = list[i+1], where i is every alternative
index from starting to ending of list.

Python Programming Raghu Engineering College Slide 125


Reading a Dictionary at run time
Program:
l=list(input().split(","))
d={}
for i in range(0,len(l),2):
d[l[i]]=l[i+1]
print(d)

Output:
rollno,101,name,ram,marks,76
{'rollno': '101', 'name': 'ram', 'marks': '76'}

Python Programming Raghu Engineering College Slide 126


list vs Dictionary
• First, a list is an ordered set of items. But, a dictionary is a data structure
that is used for matching one item(key) with another (value).

• Second, in lists, you can use indexing to access a particular item. But,
these indexes should be a number. In dictionaries, you can use any type
(immutable) of value as an index. For example, when we write
Dict['Name'], Name acts as an index but it is not a number but a string.

Python Programming Raghu Engineering College Slide 127


list vs Dictionary
• Third, lists are used to look up a value whereas a dictionary is used to
take one value and look up another value. For this reason, dictionary is
also known as a lookup table.

• Fourth, the key-value pair may not be displayed in the order in which it
was specified while defining the dictionary. This is because Python uses
complex algorithms (called hashing) to provide fast access to the items
stored in the dictionary. This also makes dictionary preferable to use over
a list of tuples.
Python Programming Raghu Engineering College Slide 128
When to use which Data Structure
• Use lists to store a collection of data that does not need random access.

• Use lists if the data has to be modified frequently.

• Use a set if you want to ensure that every element in the data structure
must be unique.

• Use tuples when you want that your data should not be altered.

Python Programming Raghu Engineering College Slide 129

You might also like