Ict Python Solved Lab Manual by Herry
Ict Python Solved Lab Manual by Herry
(DI02032011)
LAB MANUAL
Lab Manual
Certificate
In ................................................................................................................. …………………………………….of
Place:………………..
Date: …………………..
Sr
Practical Outcome/Title of Date TS WQ CO IN TOTAL SIGN
No.
experiment (5) (5) (5) (5) (20)
Prepare flowchart and algorithm for a given
1. problem.(Following are the sample programs.
Faculty can select any other similar programs for
the practice of the students.)
i.Find the sum of two given numbers.
ii.Find a maximum out of two given numbers.
iii.Find whether a given number is odd or even.
iv.Find a maximum out of three given numbers.
TS : TECHNICAL SKILL
WQ: WORK QUALITY
CO: COLLABORATION
IN: INITIATIVE
Practical-1
Prepare flowchart and algorithm for a given problem.
Theory:-
An introduction to Algorithm
What is Algorithm?
The Algorithm designed are language-independent, i.e. they are just plain instructions
that can be implemented in any language, and yet the output will be the same, as expected.
Step 1. START
What is a Flowchart?
6. Flow lines: Flow lines indicate the exact sequence in which instructions are
executed. Arrows represent the direction of flow of control and relationship
among different symbols of flowchart.
8. Page Break:
When flowchart does not fit into single page then page break and page continue
symbols are used.
Page Break symbol indicate break in current page.
Example : Draw a flowchart to input two numbers from user and display the largest of
two numbers
Exercise
Ex-1- Draw flowchart and write algorithm to Find the sum of two given numbers.
Ex-2- Draw flowchart and write algorithm to Find a maximum out of two given
numbers.
Ex-3- Draw flowchart and write algorithm to Find whether a given number is odd or
even.
Ex-4- Draw flowchart and write algorithm to Find a maximum out of three given
numbers.
Algorithm:
Step 1:Start
Step 3:Sum=num1+num2
Step 5:End
Ex-2-Draw flowchart and write algorithm to Find maximum out of two given
numbers
Flowchart:
Input a,b
If a>b
Print a Print b
is max is max
Step 6:Stop
Ex-3- Draw flowchart and write algorithm to Find whether a given number is
odd or even
Flowchart:
Algorithm:
Step 1:Start
Step 6:End
Algorithm:
Step 1:Start
Theory:-
The print() function is used whenever you want to print text to the screen. Try the following
example in your Python shell:
Hello World!
Now that you know how to use the print() function, you can begin to work with the different
types of ‗ and ― (quotes) .
However, when you want to work with a contraction, such as don ’ t , or if you want to quote
someone quoting something, observe what happens:
When you press Enter to execute the function, you will get the error message: SyntaxError:
invalid
There is a simple solution to this, known as an escape. Retry the preceding code, adding an
escape character to this string:
I said, “Don‟t do it
Triple quote allows you to write some text on multiple lines, without being processed
until you close it with another triple quote. This technique is useful if you have a large
amount of data that you do not wish to print on one line, or if you want to create line breaks
within your code.
Here, in the next example, you write a poem using this method:
> > > print(“””Roses are red
Violets are blue
I just printed multiples lines
And you did too!”””)
Roses are red
Violets are blue
I just printed multiple lines
And you did too!
There is another way to print text on multiple lines using the newline ( \n ) escape character,
which is the most common of all the escape characters. I ‘ ll show it to you here briefly, and
come back to discuss it in more depth in a later chapter. Try this code out:
The print function will automatically advance to the next line. For instance, the following
will print on two lines:
print('On the first line')
print('On the second line')
On the first line
On the second line
There is an optional argument called end that you can use to keep the print function from
advancing to the next line. Here is an example:
If you wanted to suppress the separator completely, you‘d have to pass an empty string ('')
instead:
>>>
>>> print('hello', 'world', sep='\n')
hello
world
A more useful example of the sep parameter would be printing something like file paths:
>>>
>>> print('home', 'user', 'documents', sep='/')
home/user/documents
Second method:
name="ABC"
mobile_no="9122222222"
dob="22-01-2003"
print("Name=",name)
print("Mobile No.=",mobile_no)
print("Date of birth=",dob)
Output:
Name= ABC
Mobile No.= 9122222222
Date of birth= 22-01-2003
Data Types
Every value belongs to a specific data type in Python. Data type identifies the type of data
values a variable can hold and the operations that can be performed on that data.
● Number
Number data type stores numerical values only. It is further classified into three different
types: int, float and complex.
Boolean data type (bool) is a subtype of integer. It is a unique data type, consisting of two
constants, True and False. Boolean True value is non-zero, non-null and non-empty. Boolean
False is the value zero.
We can try to execute few statements in interactive mode to determine the data type of the
variable using built-in function type().
Example
>>> num1 = 10
>>> type(num1)
<class 'int'>
>>> num2 = -1210
>>> type(num2)
● Sequence
A Python sequence is an ordered collection of items, where each item is indexed by an integer.
The three types of sequence data types available in Python are Strings, Lists and Tuples. We
will learn about each of them in detail in later chapters. A brief introduction to
these data types is as follows:
(A) String
String is a group of characters. These characters may be alphabets, digits or special haracters
including spaces. String values are enclosed either in single quotation marks (e.g., ‗Hello‘) or
in double quotation marks (e.g., ―Hello‖). The quotes are not a part of the string, they are
used to mark the beginning and end of the string for the interpreter. For example,
>>> str1 = 'Hello Friend'
>>> str2 = "452"
We cannot perform numerical operations on strings, even when the string contains a numeric
value, as in str2.
(B) List
List is a sequence of items separated by commas and the items are enclosed in square
brackets [ ].
Example
#To create a list
>>> list1 = [5, 3.4, "New Delhi", "20C", 45]
● Set
Set is an unordered collection of items separated by commas and the items are enclosed in
curly brackets { }. A set is similar to list, except that it cannot have duplicate entries. Once
created, elements of a set cannot be changed.
Example
#create a set
>>> set1 = {10,20,3.14,"New Delhi"}
>>> print(type(set1))
<class 'set'>
>>> print(set1)
{10, 20, 3.14, "New Delhi"}
#duplicate elements are not included in set
>>> set2 = {1,2,1,3}
>>> print(set2)
{1, 2, 3}
● None
None is a special data type with a single value. It is used to signify the absence of value in a
situation. None supports no special operations, and it is neither False nor 0 (zero).
Example
● Mapping
Mapping is an unordered data type in Python. Currently, there is only one standard mapping
data type in Python called dictionary.
(A) Dictionary
Dictionary in Python holds data items in key-value pairs. Items in a dictionary are enclosed in
curly brackets { }. Dictionaries permit faster access to data. Every key is separated from its
value using a colon (:) sign. The key : value pairs of a dictionary can be accessed using the
key. The keys are usually strings and their values can be any data type. In order to access any
value in the dictionary, we have to specify its key in square brackets
[ ].
Example
#create a dictionary
>>> dict1 = {'Fruit':'Apple',
'Climate':'Cold', 'Price(kg)':120}
>>> print(dict1)
{'Fruit': 'Apple', 'Climate': 'Cold',
'Price(kg)': 120}
>>> print(dict1['Price(kg)'])
120
num1=int(input("Enter a number:"))
num2=int(input("Enter a number:"))
num3=int(input("Enter a number:"))
average=(num1+num2+num3)/3
print("Average of",num1,num2,num3,"is:",average)
Output:
Enter a number:10
Enter a number:20
Enter a number:30
Average of 10 20 30 is: 20.0
Formulae:
Simple Interest,
SI = P × (R/100) × T
Where P= Principal amount
R=Rate of interest
T=No. of years
Compound Interest,
CI = P( 1 + R/100)T – P
Where P=Principal amount
R= Rate of interest
T=No. of years
Program:
p=int(input("Enter principal amount="))
r=int(input("Enter rate of interest="))
t=int(input("Enter number of years="))
si=p*(r/100)*t
ci=p*(1+(r/100))**t-p
print("Simple interest=",si)
print("Compound interest=",ci)
Output:
Enter principal amount=1000
Enter rate of interest=5
Enter number of years=2
Simple interest= 100.0
Compound interest= 102.5
Program:
c=(f-32)/1.8
Output:
Enter temperature in Fahrenheit:23
Temperatur in Celcious=-5.00
Theory:
If..else statement :
In programming, concept of decision making or selection is implemented
with the help of if..else statement.
The syntax of if statement is:
if condition:
statement(s)
If the condition is true, then the indented statement(s) are executed. The
indentation implies that its execution is dependent on the condition. There is
no limit on the number of statements that can appear as a block under the if
statement.
Example
age = int(input("Enter your age "))
if age >= 18:
print("Eligible to vote")
Let us now modify the example on voting with the condition that if the age entered
by the user is greater than 18, then to display that the user is eligible to vote.
Otherwise display that the user is not eligible to vote.
age = int(input("Enter your age: "))
if age >= 18:
print("Eligible to vote")
else:
print("Not eligible to vote")
if n%2==0:
print(n,"is an even number")
else:
print(n,"is an odd number")
Output:
Enter an integer number:24
24 is an even number
Theory:
if..elif statement
Many a times there are situations that require multiple conditions to be checked
and it may lead to many alternatives. In such cases we can chain the conditions
using if..elif (elif means else..if).
The syntax for a selection structure using elif is as shown below.
if condition:
statement(s)
elif condition:
statement(s)
elif condition:
statement(s)
else:
statement(s)
n1=int(input("Enter a number:"))
n2=int(input("Enter a number:"))
n3=int(input("Enter a number:"))
if(n1>n2)and (n1>n3):
print(n1,"is largest number")
elif (n2>n1) and (n2>n3):
print(n2,"is largest number")
else:
print(n3,"is largest number")
Output:
Enter a number:10
Enter a number:20
Enter a number:30
30 is largest number
Program:
a=float(input("Enter a number:"))
b=float(input("Enter a number:"))
print("Enter 1 for addition,2 for subtraction,3 for multiplication and 4 for
division:")
c=int(input("Choice:"))
if c==1:
print("Addition of a and b=",a+b)
elif c==2:
print("Subtraction of b from a=",a-b)
elif c==3:
print("Multiplication of a and b is=",a*b)
elif c==4:
print("a divided by b=",a/b)
else:
print("Invalid choice")
Output:
Enter a number:10
Enter a number:2
Enter 1 for addition,2 for subtraction,3 for multiplication and 4 for division:
Choice:3
Multiplication of a and b= 20.0
Theory:
Python programming language provides following types of loops to handle
looping requirements. Python provides three ways for executing the loops. While
all the ways provide similar basic functionality, they differ in their syntax and
condition checking time.
While Loop:
In python, while loop is used to execute a block of statements repeatedly until a
given a condition is satisfied. And when the condition becomes false, the line
immediately after the loop in program is executed.
while expression:
statement(s)
All the statements indented by the same number of character spaces after a
programming construct are considered to be part of a single block of code. Python
uses indentation as its method of grouping statements.
Output:
for Loop
1
2
3
4
5
6
7
8
9
10
While Loop
1
2
3
4
5
6
7
8
9
10
Program:
n=int(input("Enter a number:"))
flag=0
for i in range(2,int(n/2)):
if(n%i==0):
flag=1
if (flag==0):
print(n,"is prime number")
else:
print(n,"is not a prime number")
Output:
Enter a number:117
117 is not a prime number
Program:
(i)
1
12
123
1234
12345
n=int(input("Enter a number:"))
for i in range(1,n+1):
for j in range(1,i+1):
print(j,end=" ")
print("")
(ii)
*****
****
***
**
*
n=int(input("Enter a number:"))
for i in range(n,0,-1):
for j in range(1,i+1):
print("*",end=" ")
print("")
Theory:
Introduction to function:
In programming, the use of function is one of the means to achieve modularity
and reusability. Function can be defined as a named group of instructions that
accomplish a specific task when it is invoked. Once defined, a function can be
called repeatedly from different places of the program without writing all the
codes of that function every time, or it can be called from inside another function,
by simply writing the name of the function and passing the required parameters,
if any.
The Advantages of Function
Following are the advantages of using functions in a program:
• Increases readability, particularly for longer code as by using functions, the
program is better organised and easy to understand.
• Reduces code length as same code is not required to be written at multiple places
in a program. This als o makes debugging easier.
• Increases reusability, as function can be called from another function or another
program. Thus, we can reuse or build upon already defined functions and avoid
repetitions of writing the same piece of code.
• Work can be easily divided among team members and completed in parallel.
• The items enclosed in "[ ]" are called parameters and they are optional. Hence,
a function may or may not have parameters. Also, a function may or may not
return a value.
• Function header always ends with a colon (:).
• Function name should be unique. Rules for naming identifiers also applies for
function naming.
• The statements outside the function indentation are not considered as part of
the function.
Example: Write a user defined function to add 2 numbers and display their sum.
#function definition
def addnum():
fnum = int(input("Enter first number: "))
snum = int(input("Enter second number: "))
sum = fnum + snum
print("The sum of ",fnum,"and ",snum,"is ",sum)
#function call
addnum()
Output:
Enter first number: 5
Enter second number: 6
The sum of 5 and 6 is 11
#function header
def sumSquares(n): #n is the parameter
sum = 0
for i in range(1,n+1):
sum = sum + i
print("The sum of first",n,"natural numbers is:
",sum)
num = int(input("Enter the value for n: "))
#num is an argument referring to the value input by
the user
sumSquares(num) #function call
def fibo(n):
f1=0
f2=1
print(f1)
print(f2)
for i in range(2,n):
f3=f1+f2
f1=f2
f2=f3
Output:
Enter a number:12
0
1
1
2
3
5
8
13
21
34
55
89
Theory:
Functions Returning Value
A function may or may not return a value when called. The return statement
returns the values from the function. In the examples given so far, the function
performs calculations and display result(s).They do not return any value. Such
functions are called void functions. But a situation may arise, wherein we need to
send value(s) from the function to its calling function.
This is done using return statement.
The return statement does the following:
• returns the control to the calling function.
• return value(s) or None.
Program:
def calcFact(num):
fact = 1
for i in range(num,0,-1):
fact = fact * i
return fact
num = int(input("Enter the number: "))
factorial=calcFact(num)
print(num,"!=",factorial,sep='')
Output:
Enter the number: 5
5!=120
Program:
def reverse(n):
reversed_num = 0
while n!= 0:
digit = n%10
reversed_num = reversed_num * 10 + digit
n=n//10
return reversed_num
num=int(input("Enter a number:"))
ans=reverse(num)
print("Reversed number is=",ans)
Output:
Enter a number:96705
Reversed number is= 50769
Ex: 15451, for example: If we take 131 and reverse it then after reversing the
number remains the same.
Program:
def armstrong(n):
sum=0
number=n
while n!= 0:
digit = n%10
sum=sum+digit**3
n=n//10
if(sum==number):
print(number, "is an Armstrong number")
else:
print(number, "is not an Armstrong number")
def palindrome(n):
rev_num=0
number=n
num=int(input("Enter a number:"))
armstrong(num)
palindrome(num)
Output:
Enter a number:171
171 is not an Armstrong number
171 is a Palindrome number
Theory:
Strings
String is a sequence which is made up of one or more UNICODE characters.
Here the character can be a letter, digit, whitespace or any other symbol. A
string can be created by enclosing one or more characters in single, double or
triple quote.
Example 8.1
>>> str1 = 'Hello World!'
>>> str2 = "Hello World!"
>>> str3 = """Hello World!"""
>>> str4 = '''Hello World!''
Accessing Characters in a String
Each individual character in a string can be accessed using a technique called
indexing. The index specifies the character to be accessed in the string and is
written in square brackets ([ ]). The index of the first character (from left) in the
string is 0 and the last character is n-1 where n is the length of the string. If we
give index value out of this range then we get an IndexError. The index must be
an integer (positive, zero or negative).
#initializes a string str1
>>> str1 = 'Hello World!'
#gives the first character of str1
>>> str1[0]
'H'
#gives seventh character of str1
>>> str1[6]
'W'
#gives error as index is out of range
>>> str1[15]
IndexError: string index out of range
Traversing a String:
We can access each character of a string or traverse a string using for loop
and while loop.
(A) String Traversal Using for Loop:
str1 = 'Hello World!'
for ch in str1:
print(ch,end = '')
Output:
Hello World! #output of for loop
In the above code, the loop starts from the first character of the string str1
and automatically ends when the last character is accessed.
(B) String Traversal Using while Loop:
str1 = 'Hello World!'
index = 0
#len(): a function to get length of string
Output:
length of string is 12
Theory:
String methods
Strings come with a ton of methods, functions that return information about
the string or return a new string that is a modified version of the original. Here
are some of the most useful ones:
Method Description
capitalize() Converts the first character to upper case
casefold() Converts string into lower case
center() Returns a centered string
Returns the number of times a specified value occurs in a string
count()
encode() Returns an encoded version of the string
endswith() Returns true if the string ends with the specified value
expandtabs() Sets the tab size of the string
Searches the string for a specified value and returns the position of where it
find() was found
format() Formats specified values in a string
format_map() Formats specified values in a string
Searches the string for a specified value and returns the position of where it
index() was found
Returns True if all characters in the string are alphanumeric
isalnum()
Returns True if all characters in the string are in the alphabet
isalpha()
Returns True if all characters in the string are ascii characters
isascii()
isdecimal() Returns True if all characters in the string are decimals
isdigit() Returns True if all characters in the string are digits
isidentifier() Returns True if the string is an identifier
islower() Returns True if all characters in the string are lower case
isnumeric() Returns True if all characters in the string are numeric
isprintable() Returns True if all characters in the string are printable
Output:
Enter a stringpython is easy
easy is python
Theory:
Membership:
Python has two membership operators 'in' and 'not in'. The 'in' operator takes
two strings and returns True if the first string appears as a substring in the
second string, otherwise it returns False.
>>> str1 = 'Hello World!'
>>> 'W' in str1
True
>>> 'Wor' in str1
True
>>> 'My' in str1
False
The 'not in' operator also takes two strings and returns True if the first string
does not appear as a substring in the second string, otherwise returns False.
>>> str1 = 'Hello World!'
>>> 'My' not in str1
True
>>> 'Hello' not in str1
False
Built in function find(str,start,end):
Returns the first occurrence of index of substring str occurring in the given
string. If we do not give start and end then searching starts from index 0 and
ends at length of the string. If the substring is not present in the given string,
then the function returns -1
>>> str1 = 'Hello World! Hello Hello'
>>> str1.find('Hello',10,20)
13
>>> str1.find('Hello',15,25)
19
Output:
Enter string:python
Enter word:o
Substring in string!
Program:
st=input("Enter a string:")
v=0
c=0
u=0
l=0
for i in range(0,len(st)):
if st[i].isspace() or not(st[i].isalpha()) :
continue
else:
if st[i]=='a' or st[i]=='e' or st[i]=='i' or st[i]=='o' or st[i]=='u':
v=v+1
else:
c=c+1
print(st[i])
if st[i].islower():
l=l+1
else:
u=u+1
print("uppercase=",u)
print("lowercase=",l)
print("vowels=",v)
print("consonants=",c)
Output: Enter a string:encyclopedia
n
c
y
c
l
p
d
uppercase= 0
lowercase= 12
vowels= 5
consonants= 7
SSGP SURAT INFORMATION & COMMUNICATION TECHNOLOGY PYTHON POGRAMMING
Practical-12
Develop programs to perform the following list
operations.
a) To swap given two elements in a list.
b) To find the sum of elements in a list.
Theory:
Introduction to List:
The data type list is an ordered sequence which is mutable and made up of
one or more elements. Unlike a string which consists of only characters, a list
can have elements of different data types, such as integer, float, string, tuple
or even another list. A list is very useful to group together elements of mixed
data types. Elements of a list are enclosed in square brackets and are separated
by comma. Like string indices, list indices also start from 0.
Example
#list1 is the list of six even numbers
>>> list1 = [2,4,6,8,10,12]
>>> print(list1)
[2, 4, 6, 8, 10, 12]
#list2 is the list of vowels
>>> list2 = ['a','e','i','o','u']
>>> print(list2)
['a', 'e', 'i', 'o', 'u']
#list3 is the list of mixed data types
>>> list3 = [100,23.5,'Hello']
>>> print(list3)
[100, 23.5, 'Hello']
#list4 is the list of lists called nested
#list
>>> list4 =[['Physics',101],['Chemistry',202],
Traversing a List:
We can access each element of the list or traverse a list using a for loop or a
while loop.
(A) List Traversal Using for Loop:
>>> list1 = ['Red','Green','Blue','Yellow',
'Black']
>>> for item in list1:
print(item)
Output:
Red
Green
Blue
Yellow
Black
Another way of accessing the elements of the list is using range() and len()
functions:
>>> for i in range(len(list1)):
print(list1[i])
Output:
Red
Green
Blue
Yellow
Black
x=int(x)
y=int(y)
t=list[x]
list[x]=list[y]
list[y]=t
print("list after swap:",list)
Output:
Original list: [1, 5, 2, 10, 21, 7]
Enter positions of elements you want to swap x: 2
Enter positions of elements you want to swap y: 4
list after swap: [1, 5, 21, 10, 2, 7]
for i in range(0,len(list)):
sum=sum+list[i]
Output:
Sum of elements in list: 46
Theory:
List comprehensions:
List comprehensions are a powerful way to create lists. Here is a simple
example:
L = [i for i in range(5)]
This creates the list [0,1,2,3,4]
Here are a couple more examples of list comprehensions. For these examples,
assume the following:
string = 'Hello'
L = [1,14,5,9,12]
M = ['one', 'two', 'three', 'four', 'five', 'six']
Multiple fors You can use more than one for in a list comprehension:
L = [[i,j] for i in range(2) for j in range(2)]
[[0, 0], [0, 1], [1, 0], [1, 1]]
Example 3 Count how many items in a list L are greater than 50.
len([i for i in L if i>50])
Programs:
a) Given a list saved in variable: a = [1, 4, 9, 16, 25, 36,
49, 64, 81, 100]. Write one line of Python that takes
this list and makes a new list that has only the even
elements of this list in it.
b) Create a list containing the square of all odd numbers from range 1 to
10.
b = [i for i in range(1,11) if i % 2 == 1]
Print(b)
Output:
[1, 3, 5, 7, 9]
A Set in Python is a collection of unique elements which are unordered and mutable. Python provides
various functions to work with Set.
Create set:
A set can be created in two ways. First, you can define a set with the built-in set() function:x = set(<iter>)
In this case, the argument <iter> is an iterable—again, for the moment, think list or tuple—that generates the
list of objects to be included in the set.
Example:
Strings are also iterable, so a string can be passed to set() as well. You have already seen that list(s)
generates a list of the characters in the string s. Similarly, set(s) generates a set of the characters in s:
Example:
>>> s = 'quux'
>>> list(s)
['q', 'u', 'u', 'x']
>>> set(s)
{'x', 'u', 'q'}
Thus, the sets shown above can also be defined like this:
A set can be empty. However, recall that Python interprets empty curly braces ({}) as anempty
dictionary, so the only way to define an empty set is with the set() function:
>>> x = set()
>>> type(x)
<class 'set'>
>>> x
set()
>>> x = {}
>>> type(x)
<class 'dict'>
>>> x = set()
>>> bool(x)False
Don‘t forget that set elements must be immutable. For example, a tuple may be included in aset:
>>>
>>> x = {42, 'foo', (1, 2, 3), 3.14159}
>>> x
{42, 'foo', 3.14159, (1, 2, 3)}
But lists and dictionaries are mutable, so they can‘t be set elements:
>>>
>>> a = [1, 2, 3]
>>> {a}
Traceback (most recent call last):
File "<pyshell#70>", line 1, in <module>
{a}
TypeError: unhashable type: 'list'
>>> d = {'a': 1, 'b': 2}
>>> {d}
Traceback (most recent call last):
File "<pyshell#72>", line 1, in <module>
{d}
Modifying Sets:
Python supports several methods that modify sets.
x.add(<elem>)
Adds an element to a set.
x.add(<elem>) adds <elem>, which must be a single immutable object, to x:
>>>
>>> x = {'foo', 'bar', 'baz'}
>>> x.add('qux')
>>> x
{'bar', 'baz', 'foo', 'qux'}
x.remove(<elem>)
Removes an element from a set.
x.remove(<elem>) removes <elem> from x. Python raises an exception if <elem> isnot in x:
>>>
>>> x = {'foo', 'bar', 'baz'}
>>> x.remove('baz')
>>> x
{'bar', 'foo'}
>>> x.remove('qux')
Traceback (most recent call last):
File "<pyshell#58>", line 1, in <module>
x.remove('qux')
KeyError: 'qux'
x.discard(<elem>)
Removes an element from a set.
x.discard(<elem>) also removes <elem> from x. However, if <elem> is not in x, thismethod quietly
does nothing instead of raising an exception:
>>> x = {'foo', 'bar', 'baz'}
>>> x.discard('baz')
>>> x
{'bar', 'foo'}
>>> x.discard('qux')
>>> x
{'bar', 'foo'}
x.clear()
Clears a set.
x.clear() removes all elements from x:
>>>
>>> x = {'foo', 'bar', 'baz'}
>>> x
{'foo', 'bar', 'baz'}
>>>
>>> x.clear()
>>> x
set()
Set operations :
Below is a list of the set operations available in Python. Some are performed by operator, some by method,
and some by both. The principle outlined above generally applies: where a set is expected, methods will
typically accept any iterable as an argument, but operators require actual sets as operands.
Union operation:
x1.union(x2[, x3 ...])
x1 | x2 [| x3 ...]
Intersection Operation:
x1.intersection(x2) and x1 & x2 return the set of elements common to both x1 and
x2:
>>>
>>> x1 = {'foo', 'bar', 'baz'}
>>> x2 = {'baz', 'qux', 'quux'}
>>> x1.intersection(x2)
{'baz'}
>>> x1 & x2
{'baz'}
You can specify multiple sets with the intersection method and operator, just like you can with set union:
>>>
>>> a = {1, 2, 3, 4}
>>> b = {2, 3, 4, 5}
>>> c = {3, 4, 5, 6}
>>> d = {4, 5, 6, 7}
>>> a.intersection(b, c, d)
{4}
>>> a & b & c & d
{4}
x1.difference(x2[, x3 ...])
x1 - x2 [- x3 ...]
Compute the difference between two or more sets.
x1.difference(x2) and x1 - x2 return the set of all elements that are in x1 but not in x2:
x1.symmetric_difference(x2)
x1 ^ x2 [^ x3 ...]
Compute the symmetric difference between sets.
>>> x1.symmetric_difference(x2)
{'foo', 'qux', 'quux', 'bar'}
>>> x1 ^ x2
{'foo', 'qux', 'quux', 'bar'}
Disjoint or not:
x1.isdisjoint(x2)
Determines whether or not two sets have any elements in common.
x1.isdisjoint(x2) returns True if x1 and x2 have no elements in common:
>>>
>>> x1 = {'foo', 'bar', 'baz'}
>>> x2 = {'baz', 'qux', 'quux'}
>>> x1.isdisjoint(x2)False
>>> x2 - {'baz'}
{'quux', 'qux'}
>>> x1.isdisjoint(x2 - {'baz'})True
If x1.isdisjoint(x2) is True, then x1 & x2 is the empty set:
>>>
>>> x1 = {1, 3, 5}
>>> x2 = {2, 4, 6}
>>> x1.isdisjoint(x2)True
>>> x1 & x2
set()
Note: There is no operator that corresponds to the .isdisjoint() method.
Subset or not:
x1.issubset(x2)
x1 <= x2
Determine whether one set is a subset of the other.
In set theory, a set x1 is considered a subset of another set x2 if every element of x1 is in x2.
x1.issubset(x2) and x1 <= x2 return True if x1 is a subset of x2:
>>>
>>> x1 = {'foo', 'bar', 'baz'}
>>> x1.issubset({'foo', 'bar', 'baz', 'qux', 'quux'})
True
It seems strange, perhaps. But it fits the definition—every element of x is in x.x1 < x2
Determines whether one set is a proper subset of the other.
A proper subset is the same as a subset, except that the sets can‘t be identical. A set x1 is considered a
proper subset of another set x2 if every element of x1 is in x2, and x1 and x2are not equal.
x1 < x2 returns True if x1 is a proper subset of x2:
>>>
>>> x1 = {'foo', 'bar'}
>>> x2 = {'foo', 'bar', 'baz'}
>>> x1 < x2
True
>>> x1 = {'foo', 'bar', 'baz'}
>>> x2 = {'foo', 'bar', 'baz'}
>>> x1 < x2
False
While a set is considered a subset of itself, it is not a proper subset of itself:
>>>
>>> x = {1, 2, 3, 4, 5}
>>> x <= x
True
>>> x < xFalse
Note: The < operator is the only way to test whether a set is a proper subset. There is no
corresponding method.
Superset or not:
x1.issuperset(x2)x1 >= x2
Determine whether one set is a superset of the other.
A superset is the reverse of a subset. A set x1 is considered a superset of another set x2 if
x1 contains every element of x2.
x1.issuperset(x2) and x1 >= x2 return True if x1 is a superset of x2:
>>>
>>> x1 = {'foo', 'bar', 'baz'}
>>> x1.issuperset({'foo', 'bar'})True
>>> x2 = {'baz', 'qux', 'quux'}
>>> x1 >= x2
False
>>> x = {1, 2, 3, 4, 5}
>>> x.issuperset(x)True
SSGP SURAT INFORMATION & COMMUNICATION TECHNOLOGY PYTHON POGRAMMING
>>> x >= x
True
x1 > x2
Determines whether one set is a proper superset of the other.
A proper superset is the same as a superset, except that the sets can‘t be identical. A set x1 isconsidered a
proper superset of another set x2 if x1 contains every element of x2, and x1 and x2 are not equal.
x1 > x2 returns True if x1 is a proper superset of x2:
>>>
>>> x1 = {'foo', 'bar', 'baz'}
>>> x2 = {'foo', 'bar'}
>>> x1 > x2
True
>>> x1 = {'foo', 'bar', 'baz'}
>>> x2 = {'foo', 'bar', 'baz'}
>>> x1 > x2
False
A set is not a proper superset of itself:
>>>
>>> x = {1, 2, 3, 4, 5}
>>> x > xFalse
Exercise
# Clearing a set
set1.clear()
print("set1 after clearing: ", set1)
Output:
set1: {1, 2, 3, 4, 5}
set2: {4, 5, 6, 7, 8}
Union of set1 and set2: {1, 2, 3, 4, 5, 6, 7, 8}
Intersection of set1 and set2: {4, 5}
Difference between set1 and set2: {1, 2, 3}
Symmetric difference between set1 and set2: {1, 2, 3, 6, 7, 8}
Is set1 a subset of set2? False
Is set1 a superset of set2? False
set1 after adding 6: {1, 2, 3, 4, 5, 6}
set2 after removing 8: {4, 5, 6, 7}
set1 after clearing: set()