0% found this document useful (0 votes)
2 views37 pages

PPS NOTES Unit-2 (2024 Pattern)

The document provides notes on advanced data types and decision control statements in Python, focusing on selection statements like if, if-else, if-elif-else, and nested if statements. It also covers basic loop structures, including while and for loops, along with their syntax, flowcharts, and examples. Additionally, it discusses the use of else statements with loops and the concept of nested loops.

Uploaded by

itsmedon09
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views37 pages

PPS NOTES Unit-2 (2024 Pattern)

The document provides notes on advanced data types and decision control statements in Python, focusing on selection statements like if, if-else, if-elif-else, and nested if statements. It also covers basic loop structures, including while and for loops, along with their syntax, flowcharts, and examples. Additionally, it discusses the use of else statements with loops and the concept of nested loops.

Uploaded by

itsmedon09
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

PPSUnit-II SKNSITS

SKN SINHGAD INSTITUTES OF TECHNOLOGY & SCIENCE,LONAVALA


Department of First Year Engineering
Programming and Problem Solving
Unit- 2 Notes
-----------------------------------------------------------------------------------

UnitII: Advance Data Types and Decision Control

Statements

2.1Selection/conditional Statements:
Q. Explain selection/conditional statements with flowchart

• The selection control statements usually jump from one part of code to another
depending on whether a particular condition is satisfied or not.
• It allow us to execute statements selectively(branchwise)based on certain decisions.
• Python language supports different types of selection/conditional/branching
statements.
1. If statements
2. If.... else statements
3. If…elif….else statements
4. Nested if

2.1.1if
1. If statements:
• If statement is a simplest form of decision control statements that is frequently
used in decision making.
• If statements may include one statement or N statements enclosed within the if
block
• If the expression is true the statements of if block get executed, otherwise these
statements will be skipped and the execution will be jump to statement just outside
if block.

1
• Syntax:
if (expression/condition):
Block of statements
Statements outside if

• Flowchart:

✓ Example:

i = 10
# Checking if i is greater than 15
if (i > 15):
print("10 is less than 15")
print("I am Not in if")

Output

I am Not in if

1
PPSUnit-II SKNSITS

2.1.2if-else
• In simple if statement, test expression is evaluated and if it is true the statements
in if block get executed, But if we want a separate statements to be get executed if
it returns false in this case we have to use if..else control statement.
• If else statement has two blocks of codes, each for if and else.
• The block of code inside if statement is executed if the expression in if statement
is TRUE, else the block of code inside else is executed.
• Syntax:
if (expression/condition):
Block of statements
else:
Block of statements

2
PPSUnit-II SKNSITS

• Flowchart:

✓ Example:
x=5
if (x<10):
print(“Condition is TRUE”)
else:
print(“Condition is FALSE”)

output:
Condition is TRUE'

Output
Condition is TRUE

i = 20
# Checking if i is greater than 0
if (i > 0):
print("i is positive")
else:
print("i is 0 or Negative")

Output
i is positive

3
2.1.3if-elif-else
• Python supports if..elif..else to test additional conditions apart from the initial test
expression.
• It work just like a if…else statement.
• The programmer can have as many elif statements/branches as he wants depending
on the expressions that have to be tested.
• A series of if..elif statements can have a final else block, which is called if none of
the if or elif expression is true.

• Syntax:
if (expression/condition):
Block of statements

4
PPSUnit-II SKNSITS

elif(expression/condition):
Block of statements
elif(expression/condition):
Block of statements
else:
Block of statements

• Flowchart:

Example:
x=5
if(x == 2):
print(“x is equal to2”)
elif(x<2):
print(“x is less than2”)
else:
print(“x is greater than2”)

Output:
X is greater than 2

5
i = 25
if (i == 10):
print("i is 10")
elif (i == 15):
print("i is 15")
elif (i == 20):
print("i is 20")
else:
print("i is not present")

Output:
i is not present

6
PPSUnit-II SKNSITS

2.1.4nestedif
• A statement that contains other statements is called nested/compound statements.
• In nested if else statements, if statement is nested inside an if statements. So, the nested
if statements will be executed only if the expression of main if statement returns
TRUE.

• Syntax:
if (expression/condition):
if(expression/condition):
statements
else:
statements
else:

statements
• Flowchart

• Example

x=5
if (x<=10):
if(x==10):
print(“Number is Ten”)
else:
print(“Number is less than Ten”)
else:
print(“Number is greater than Ten”)

7
x = 41
if x > 10:
print("Above ten,")
if x > 20:
print("and also above 20!")
else:
print("but not above 20.")

OUTPUT:

Above ten,
and also above 20!

8
PPSUnit-II SKNSITS

2.2Basic loop Structures/Iterative statements:


Q. Explain looping statements with flowchart.

• Iterative statements are decision control statements that are used to repeat
the execution of a list of statements.
• Python language supports two types of statements while loop and for loop.

2.2.1 while loop


• The while loop provides a mechanism to repeat one or more statements while a
particular condition is True.
• Syntax:
while condition:
Statement block
Statement y

• As shown in the syntax above, in the while loop condition is first tested.
• If the condition is True, only then the statement block will be executed.
• Otherwise, if the condition is False the control will jump to statement y, that is the
immediate statement outside the while loop block.
• Flowchart:

9
PPSUnit-II SKNSITS

• Example:
Program to print numbers from 1 to 10.

print('Numbers from 1 to 10:')


n=1
while n <= 10:
print(n, end=' ')
n = n+1

Output:
Numbers from 1 to 10:
1 2 3 4 5 6 7 8 9 10

2.2.2 for loop


• The for loop provide a mechanism to repeat a task until a particular condition is
True.
• The for loop is usually known as a determinate or definite loop because the
programmer knows exactly how many times the loop will repeat.
• The for loop in python is used to iterate through each item in a sequence.
• Here, by sequence we mean just an ordered collection of items.
• The sequence of for loop is tested; if it is satisfied then body of for loop is executed.
• When the last item in sequence is reached, then for loop exits.

• Syntax:
For loop_control_var in sequence:
statement block1
Statement x

• The range()function: (Optional)


o The range()function is inbuilt function in python that is used to iterate over a
sequence of numbers.
o The syntax of range() is
range(beginning,end, [step])

10
PPSUnit-II SKNSITS

The range( ) function produces a sequence of numbers starting with


beginning(inclusive) and ending with one less than the number end. The
step argument is optional

• Flowchart:

• Example:.

fori in range(1, 5): fori inrange(1, 10, 2):


print(i,end=” “) print(i,end=” “)

Output: Output:
1234 13 579

The range() function is commonly used with for loops to generate a sequence of numbers. It can
take one, two, or three arguments:
• range(stop): Generates numbers from 0 to stop-1.
• range(start, stop): Generates numbers from start to stop-1.
• range(start, stop, step): Generates numbers from start to stop-1, incrementing by step.

for i in range(0, 10, 2):


print(i)

Output:
11
0
2
4
6
8

Continue with For Loop

Python continue Statement returns the control to the beginning of the loop.

# Prints all letters except 'e' and 's'

for i in 'geeksforgeeks':

if i == 'e' or i == 's':

continue

print(i)

Output:

Break with For Loop


Python break statement brings control out of the loop.

for i in 'geeksforgeeks':

12
# break the loop as soon it sees 'e'

# or 's'

if i == 'e' or i == 's':

break

print(i)

Output:
E

Pass Statement with For Loop


The pass statement to write empty loops. Pass is also used for empty control statements,
functions, and classes.

# An empty loop
for i in 'geeksforgeeks':
pass
print(i)

Output
s

Else Statement with For Loops


Python also allows us to use the else condition for loops. The else block just after
for/while is executed only when the loop is NOT terminated by a break statement.

for i in range(1, 4):

print(i)

else: # Executed because no break in for

print("No Break\n")

Output

2
13
3

No Break

2.2.3 Selecting appropriate loop:

• Loops can be of different types such as entry controlled (also known as pre-
test),exit controlled (also known as post-test), counter controlled and condition
controlled (or sentinel-controlled) loops.

Pre-test and Post-test loops:


• While in an entry controlled loop, condition is tested before the loop starts, an
exit- controlled loop, tests the condition after the loop is executed.

14
PPSUnit-II SKNSITS

• If condition is not met in entry-controlled loop, then the loop will never execute.
• However, in case of post-test, the body of the loop is executed unconditionally for
the first time.
• If the requirement is to have a pre-test loop, then choose a for loop or a while loop.
• The table below shows comparison between Pre-test loop and post-test loop.
Feature Pre-test Loop Post-test Loop
Initialization 1 2
Number of tests N+1 N
Statements executed N N
Loop control variable update N N
Minimum Iterations 0 1

Condition-controlled and Counter-controlled loops:


• When we know in advance the number of times the loop should be executed, we
use a counter controlled loop.
• The counter is a variable that must be initialized, tested and updated for performing
the loop operations.
• Suchacountercontrolledloopinwhichthecounterisassignedaconstantora value is
known as a definite repetition loop.
• When we do not know in advance the number of times the loop will be executed,
we use a condition-controlled (or sentinel-controlled or indefinite loop) loop.
• In such a loop, a special value called a sentinel value is used to change the loop
control expression from true to false.
• For example, when data is read from user, the user may be notified that when they
want the execution to stop, they may enter -1. This value is called sentinel value.
• If your requirement is to have a counter-controlled loop, then choose for loop, else,
if you need to have a sentinel controlled loop then go for a while loop.

15
PPSUnit-II SKNSITS

Comparison between condition-controlled and counter controlled loop:


Attitude Counter-controlled loop Condition Controlled loop
Number of execution Used when number of times Used when number of times
the loop has to be executed is the loops has to be executed
known in advance. is not known in advance.
Condition Variable In counter-controlled loops, In condition-controlled
we have a counter variable. loops, we use a sentinel
variable.
Value and limitation of The value of the counter The value of the counter
variable variable and the condition for variable and the condition for
loop execution, both are loop execution,both are
strict. strict.
Example i=0 i=1
while (i<=10): while(i>0):
print(i,end="") i+=1 print(i,end="") i+=1
if (i==10):
break

2.3Nested loops
• Python allows its users to have a nested loop, that is,loops can be placed inside
another loop.
• This feature works with while as well as for loop.
• Nested loops are commonly used with for loop because it is easiest to control.
• Loops can be nested at any desired level.
• Loopsshouldbeproperlyindentedtoidentifywhichstatementsarecontainedwithin which
loop.
• Example:
x = [1, 2]
y = [4, 5]
for i in x:
for j in y:
print(i, j)
16
Output
1 4
1 5
2 4
2 5

Printing multiplication table using Python nested for loops

# Running outer loop from 2 to 3


for i in range(2, 4):

# Printing inside the outer loop


# Running inner loop from 1 to 10
for j in range(1, 11):

# Printing inside the inner loop


print(i, "*", j, "=", i*j)
# Printing inside the outer loop
print()

Output
2*1=2
2*2=4
2*3=6
2*4=8
2 * 5 = 10
2 * 6 = 12
2 * 7 = 14
2 * 8 = 16
2 * 9 = 18
2 * 10 = 20

3*1=3
3*2=6
17
3*3=9
3 * 4 = 12
3 * 5 = 15
3 * 6 = 18
3 * 7 = 21
3 * 8 = 24
3 * 9 = 27
3 * 10 = 30

for i in range(0, 5):


for j in range(0, i+1):

print("*",end="")
print("\r")

Output
*
**
***
****
*****

18
PPSUnit-II SKNSITS

Example2:
last Number=6
for row in range(1, last Number):
for column in range(1,row+1):
print(column,end='')
print("")

Output
1
12
123
1234
12345

2.4 else statement used with loops


• In for loop, the else keyword is used to specify a block of code to be executed after
completion of loop.
• If the else statement is used with a for loop, the else statement is executed when the
loop has completed iterating.
• But when used with the while loop, the else statement is executed when the
condition becomes false.

19
PPSUnit-II SKNSITS

• Example1(For‘ for loop’):Print numbers from 0 to10 and print a message when
the loop is ended.

for x in range(11):
print(x)
else:
print(“Loop is finished”)

• Example2(For‘while loop”):
i=1
while(i<0)
print(i)
i=i-1
else:
print(i,“is not negative so loop did not execute”)

Output:

1is not negative so loop did not execute.

2.5 Branching Statements:

Q.Write a note on Break, pass and continue.


2.5.1 break
• The break statement is used to terminate the execution of the nearest enclosing loop
in which it appears.
• The break is widely used with for and while loop.
• When the break statement is encountered inside a loop, the loop is immediately
terminated and program control is passed to next statement following the loop.
• The syntax of break is as shown below:
• Syntax:
break
• The break statement is used to exit a loop from any point with in its body ,by
passing its normal termination expression.
• Example:
for i in "welcome":

20
PPSUnit-II SKNSITS

if(i=="c"):
break
print(i)
Output:
w
el
2.5.2 continue
• Continue statement can appear only in the body of loop.
• When the continue statement encounters, then the rest of the statements in the loop
are skipped
• The control is transferred to the loop-continuation portion of the nearest enclosing
loop.
• Its syntax is simple just type keyword continue as shown below

continue

• Example:
for I in" welcome":
if(i=="c"):
continue
print(i)
Output:
w
e
l
o
m
e

• We can say continue statement forces the next iteration of the loop to take place,
skipping the remaining code below continue statement.

13
PPSUnit-II SKNSITS

while(…): for(…):
… …
if condition: if condition:
continue continue
…. …
……. …

❖ DifferentiateBetweenbreak& continue:
Break Continue
Task It terminates the execution of It terminates only the current iteration
Remaining iteration of the loop. Of the loop.
Control after When ‘break’ statement appears When ‘continue’ statement appears the
statement The control goes out of the loop. Control goes at the beginning of the loop.

Causes It causes early termination of It causes early execution of the next


loop. iteration.
Continuation Break stops the continuation of Continue donot stop the continuation of
loop. loop.
Syntax break Continue
Example for I in ‘welcome’: for I in ‘welcome’:
if (i==’c’) if (i==’c’)
break continue
print(i) print(i)
Output: Output:
w w
e e
l l
o
m
e

2.5.3 pass
• It is used when a statement is required syntactically but you do not want any command
or code to execute.
• The pass statement is a null operation.
• No thing happens when it executes.

14
PPSUnit-II SKNSIST

• It is used as placeholder.
• In a program where for some conditions you don’t want to execute any action or what
action to be taken is not yet decided, but we may wish to write some code in future, In
such cases pass can be used.
• Syntax:
Pass

• Example:
for i in “welcome”:
if(i == 'c'):
pass
print (i)

Output:

w
e

l
c
o
m
e

2.6 Other data types

2.6.1 Tuples
Q. What is tuple? Explain how to access, add and remove elements in a tuple
• Tuple is a data structure supported by python.
• A tuple is a sequence of immutable objects. That means you cannot change the
values in a tuple.
• Tuples use parentheses to define its elements.

Accessing elements in a Tuple:

• Indices in a tuple start at 0.


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

15
PPSUnit-II SKNSITS

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

Tup1=(1,2,3,4,5,6,7,8,9,10)

print(“Tup[3:6]=”,Tup1[3:6])

print(“Tup[:8]=”,Tup1[:4])

print(“Tup[4:]=”,Tup1[4:])

output:

Tup[3:6]=(4,5,6)

Tup[:8]=(1,2,3,4)

Tup[4:]=(5,6,7,8,9,10)

Using square brackets we can get the values from tuples in Python.

t = (10, 5, 20)

print("Value in t[0] = ", t[0])


print("Value in t[1] = ", t[1])
print("Value in t[2] = ", t[2])

Output
Value in t[0] = 10
Value in t[1] = 5
Value in t[2] = 20

Adding Elements in a Tuple:

• Tuples are immutable means we cannot add new element into it.
• Also it is not possible to change the value of tuple.

16
Program:
tup1=(“Kunal”,”Ishita”,”Shree”,”Pari”,“Rahul”)
tup1[5]=”Raj”
print(tup1)

Output:
It will raise an error because new element can not be added.

t = (1, 2, 3, 4, 5)
# tuples are indexed
print(t[1])
print(t[4])
# tuples contain duplicate elements
t = (1, 2, 3, 4, 2, 3)
print(t)
# updating an element
t[1] = 100
print(t)

Output :
2
5
(1, 2, 3, 4, 2, 3)
ERROR!
Traceback (most recent call last):
File "<main.py>", line 9, in <module>
TypeError: 'tuple' object does not support item assignment

17
Removing /Deleting elements in Tuple:

• Since tuple is an immutable data structure,you cannot delete value(s)from it.

Program:

Tup1=(1,2,3,4,5)

delTup1[3]

print(Tup1)

output: It will raise error as ‘tuple’ object doesn’t support item deletion.

# Code for deleting a tuple


t = ( 0, 1)

del t
print(t)

Output:

ERROR!
Traceback (most recent call last):
File "<main.py>", line 4, in <module>
NameError: name 't' is not defined

18
PPSUnit-II SKNSITS

• How ever ,we can delete the entire tuple by using the “del” statement.

Example:

Tup1=(1,2,3,4,5)

delTup1

Operations on Tuple
Q.Explain various operations on Tuple.
• Tuple behave like similar way as string when operators like concatenation
(+),and repetition (*) are used and returns new list rather a string.
• Tuple supports various operations as listed below:

Operation Description Example Output


Concatenation(+) -It joins two list and
X=(10,11,12) (10,11,12,13,1
returns new list. Y=(13,14,“pune”) 4, “pune”)
Z=X+Y
print(Z)
Repetition(*) -It repeats elements X=(10,11,12) (10,11,12,10,1
from the list. Z=X*2 1,12)
print(Z)
Slice[] - It will give you Example: PPS
element from a List2 =
specified index. ('John','PPS',94)
print(List2[1])
Range slice[:] -It will give you X=(10,11,12,13,14, (10,11,12)
elements from 15)
specified range slice. Z=X[0:3]
-Range slice contains print(z)
inclusive and
Exclusive slices

19
PPSUnit-II SKNSITS

Memebership (in) -It will check whether X=(10,11,12,13,14, TRUE


given value present in 15)
list or not.– print(11 in X)
accordingly it will
Return Boolean value
Length– len() -It will return length of
X=(10,11,12,13,14, 6
given list 15)
print(len(X))
Maximum– -It will return X=(10,11,12,13,14, 15
max() maximum value from 15)
list print(max(X))
Minimum()- -It will return minimum X=(10,11,12,13,14, 10
min() value from list 15)
print(min(X))

2.6.2 Lists
Q.What is list? Explain how elements are accessed, added and removed from list.
• List is a data type in python.
• List is a collection of values(items/ elements).
• The items in the list can be of different data types.
• The elements of the list are separated by comma(,)and written between square
brackets [].
• List is mutable which means the value of its elements can be changed.
• Syntax:
List=[value1,value2, …]
• Example1:
List1=[1,2,3,4]
print(List1)

Output:
[1, 2,3, 4]
• Example2:
List2 =['John','PPS',94]
print(List2)
20
PPSUnit-II SKNSITS

Output:
['John','PPS',94]

➢ Accessing Values in List:


• Elements in the list can be accessed by their index.
• Starting index of list is 0(zero).
• To access values in list, square brackets []are used to slice and index is written
inside it.
• Example:
List2 =['John','PPS',94]
print(List2[1])
print(List2[0:2])
Output:
PPS
['John','PPS']

➢ Adding elements/ Updating Values in List


• One or more elements can be updated in the list by giving slice on the left
hand side of assignment operator.
• New values can be appended in the list using append().
• New element is given as parameter to append function.
• Example:
List2 =['John','PPS',94]
List2.append('FE')
print(List2)
List2[0]="Sam"
print(List2)
Output:
['John','PPS', 94, 'FE']
['Sam','PPS', 94, 'FE']

➢ Removing /Deleting elements from List


• Element can be removed from list using del statement or remove().

21
PPSUnit-II SKNSITS

• Here, index of element or name of element is provided as a argument to remove().


• Example:
List2=['John', 'PPS', 94,'FE']
print(List2)
del List2[1]
print(List2)
List2.remove(List2[0])
print(List2)
List2.remove(94)
print(List2)

Output:

['John', 'PPS', 94, 'FE']


['John', 94, 'FE']
[94, 'FE']
['FE']

Operations on list
Q.Explain various operations on list.
• List behave like similar way as string when operators like concatenation (+), and
repetition (*) are used and returns new list rather a string.
• List supports various operations as listed below:

Operation Description Example Output


Concatenation(+) -It joins two list and
X=[10,11,12] [10,11,12,13,1
returns new list. Y=[13,14,“pune”] 4, “pune”]
Z=X+Y
print(Z)
Repetition(*) -It repeats elements X=[10,11,12] [10,11,12,10,1
from the list. Z=X*2 1,12]
print(Z)
Slice[] - It will give you Example: PPS
element from a List2 =
specified index. ['John','PPS',94]
print(List2[1])

22
PPSUnit-II SKNSITS

Range slice[:] -It will give you X=[10,11,12,13,14, [10,11,12]


elements from 15]
specified range slice. Z=X[0:3]
-Range slice contains print(Z)
inclusive and
exclusive slices
Memebership(in) -It will check whether X=[10,11,12,13,14, TRUE
given value present in 15]
list or not.– print(11 in X)
accordingly it will
Return Boolean value
Length– len() -It will return length of
X=[10,11,12,13,14, 6
given list 15]
print(len(X))
Maximum– -It will return X=[10,11,12,13,14, 15
max() maximum value from 15]
list print(max(X))
Minimum()- -It will return minimum X=[10,11,12,13,14, 10
min() value from list 15]
print(min(X))

2.6.3 Dictionary
Q.What is dictionary? Explain how to create dictionary, access, add and remove
elements from dictionary.

• Dictionary is a data structure which stores elements as key: value pairs.


• Each key is separated from its value by a colon (:).
• Consecutive key: value pairs are separated by commas (,).
• The entire items in a dictionary are enclosed in curly brackets {}.
• Syntax:
Dict= {key1: value1,key2: value2, key3: value3}
• If there are many key: value pairs in dictionary, then we can write just one
key: value pair on one line to make code easier to read and understand.

Dict={key1:value1, key2: value2,key3:value3 ................... key N:value N.}

23
PPSUnit-II SKNSITS

• Keys can be of any data type.


• The keys in dictionary must be unique.
• Dictionary keys are case sensitive.

➢ Creating Dictionary
• The syntax to create an empty dictionary can be given as:
Dict = { }
• The syntax to create a dictionary with key value pair
is: Dict = {key1: value1, key2: value2, key3:
value3}
• Example1:
Dict = { }
Print(Dict)
Output:
{}
• Example2:
Dict = {1: "PPS", 2: "PHY"}
print(Dict)
Output:
{1:'PPS',2: 'PHY'}

➢ Accessing values from Dictionary


• To access values in dictionary, square brackets are used along with the key to
obtain its value.
• Example:
Dict = {1: "PPS", 2: "PHY"}
print(Dict[1])
Output:
PPS
• Note that if you try to access an item with a key, which is not specified
in dictionary, a Key Error is generated.

22
PPSUnit-II SKNSITS

➢ Adding and Modifying(Updating)an item in Dictionary


• Following syntax is used to add a new key: value pair in a dictionary.
• Syntax
Dict[key]= value
• Example
Dict={1:"PPS",2:"PHY"}
Dict [3]= "M-I"
print(Dict)
Output
{1:'PPS', 2:'PHY', 3: 'M-I'}

To modify an entry, just overwrite existing value as shown below:


• Example
Dict={1:"PPS",2:"PHY"}
Dict[2]= "SME"
print(Dict)
Output
{1:'PPS',2: 'SME'}

➢ Deleting items from Dictionary


• One or more items of dictionary can be deleted using del keyword.
• To remove all items in dictionary in just one line, clear()is used.
• To remove entire dictionary from memory, del statement can be used as del Dict.
• Example:
Dict={1:"PPS", 2:"PHY",3: "SME"}
del Dict[2]
print(Dict)
Dict.clear()
print(Dict)
del Dict
Output
PPSUnit-II SKNSITS

{1:'PPS',3: 'SME'}
{}

Operations on Dictionary:

Method Description

clear() Remove all items form the dictionary.

copy() Return a shallow copy of the dictionary.

items() Return a new view of the dictionary's items(key,value).

keys() Return a new view of the dictionary's keys.

values() Return a new view of the dictionary's values

2.6.4 Sets

Q. Write a note on ‘Sets’.

• Set is an unordered collection of unique and immutable elements.


• Although it is unchangeable collection, we can add or delete the items to the set.
• sets are written with curly braces { }.
• Set items are unordered, unchangeable, and do not allow duplicate values.

• Example:
set1 = {1, 2, 3, 4, 5}
print(set1)
set2= set([3, 4, 5, 6, 7])
print(set2)

Q. Explain following operations in sets.

1) Set Union: The union operation is for combining the elements from both the sets. While combining
the elements it removes the duplicate elements. The | or union( ) is used to perform the union
operation of the set.
Python Program
set1= {1,2,3,4,5}
set2 = {3,4,5,6,7}
result1 = set1 | set2 #using operator |
result2 = set1.union(set2) #using union( ) method
print("result1: ",result1)
print("result2: ",result2)

Output:
result1: {1, 2, 3, 4, 5, 6, 7}
result2: {1, 2, 3, 4, 5, 6, 7}

2) Set Intersection: This operation returns the common element from both the sets. The & operator or the
intersection( ) function is used to find the intersection of two sets.

Python Program
set1= {1, 2, 3,4,5}
set2 = {3,4,5,6,7}
result1 = set1 & set2 #using operator &
result2 = set1.intersection(set2) #using intersection( )
print("result1: ",result1)
print("result2: ",result2)

Output:
result1: {3, 4, 5}
result2: {3, 4, 5}

3) Set Difference: This operation returns the element which is present in one set but not present in another set.
The operator - or function difference( ) is used to find the difference of two sets.

Python Program
set1 = {1,2,3,4,5}
set2 = {3,4,5,6,7}
result1 = set1- set2 #using operator -
result2= set1.difference(set2) #using intersection() method
print("result1: ",result1)
print("result2: ",result2)

Output:
result1: {1, 2}
result2: {1, 2}

4) Symmetric Difference: Symmetric difference: The symmetric difference of two sets is the set of elements
that are in either set, but not in both In Python we can find the symmetric set using the operator ^ or the
method symmetric_difference( ).
Python Program
set1={1,2,3,4,5}
set2= {3,4,5,6,7}
result1 = set1 ^ set2 #using operator ^
result2 = set1.symmetric_difference(set2)
#using symmetric_difference( ) method
print("result1 ",result1)
print("result2 ",result2)

Output:
result1 {1, 2, 6, 7}
result2 {1, 2, 6, 7}

5) Adding and removing element:


➢ We can add or remove the element from the set using the function add() or remove() function.
➢ In Python, the discard() function removes a specified element from a Set. The remove() in python also
removes an element from a set. However, When the specified element does not exist in the given set, the
remove() function raises an error whereas the discard() function does not raise any error.
➢ Following Python code illustrates these operations.
set1 = {1, 2, 3, 4, 5}
print(set1)
print("Adding the element 100")
set1.add(100)
print(set1)
print("Removing the element 4")
set1.remove(4)
print(set1)
print("Using Discard function to remove element 99")
set1.discard(99)
print(set1)

You might also like