0% found this document useful (0 votes)
21 views

PFSD stringFuncLIST

Uploaded by

gtabackup005
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

PFSD stringFuncLIST

Uploaded by

gtabackup005
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 105

Java Enterprise Programming

UNIT-4
Hibernate
String datatype
What is String?
Any sequence of characters within either single quotes or double quotes is
considered as a
String.
Syntax:
s = ‘red'
s = “line"
How to define multi-line String Literals?
We can define multi-line String literals by using triple single or double quotes.
Eg:
>>> s = '‘gojo
Is
dead'''
We can also use triple quotes to use single quotes or double quotes as symbol
inside
String literal.
How to Access Characters of a String?

We can access characters of a string by using the following ways.


1) By using index
2) By using slice operator
1)Accessing Characters By using Index:
 Python supports both +ve and -ve Index.
 +ve Index means Left to Right (Forward Direction)
 -ve Index means Right to Left (Backward Direction)
Eg: s = ‘baki'
1) >>> s=‘baki'
2) >>> s[0]
3) ‘b'
6) >>> s[-1]
7) ‘i'
8) >>> s[10]
9) IndexError: string index out of range
Accessing Characters by using Slice Operator:

Syntax: s[beginindex:endindex:step]

Begin Index: From where we have to consider slice (substring)


End Index: We have to terminate the slice (substring) at endindex-1
Step: Incremented Value

Note:  If we are not specifying bEgin index then it will consider from bEginning
of the string.
 If we are not specifying end index then it will consider up to end of the string.
 The default value for step is 1
Behaviour of Slice Operator:

1) s[bEgin:end:step]
2) Step value can be either +ve or –ve
3) If +ve then it should be forward direction(left to right) and we have to consider
bEgin
to end-1
4) If -ve then it should be backward direction (right to left) and we have to consider
bEgin
to end+1.
***Note:
 In the backward direction if end value is -1 then result is always empty.
 In the forward direction if end value is 0 then result is always empty.
In Forward Direction:
default value for bEgin: 0
default value for end: length of string
default value for step: +1
In Backward Direction:
default value for bEgin: -1
default value for end: -(length of string+1)
Note: Either forward or backward direction, we can take both +ve and -ve values
for
bEgin and end index.
Mathematical Operators for String:

We can apply the following mathematical operators for Strings.


1) + operator for concatenation
2) * operator for repetition
 print(“red"+“line")  redline
 print(“moye"*2) moyemoye

Note: 1) To use + operator for Strings, compulsory both arguments should be str
type. 2) To use * operator for Strings, compulsory one argument should be str
and other argument should be int.
len() in-built Function:
We can use len() function to find the number of characters present in the string.
Eg:
s = 'durga'
print(len(s)) – 5
Checking Membership:
We can check whether the character or string is the member of another string or
not by
using in and not in operators
s = 'durga'
print('d' in s)  True
print('z' in s)  False
Comparison of Strings:
 We can use comparison operators (<, <=, >, >=) and equality operators (==, !
=) for
strings.
 Comparison will be performed based on alphabetical order
Removing Spaces from the String:
We can use the following 3 methods
1) rstrip()  To remove spaces at right hand side
2) lstrip() To remove spaces at left hand side
3) strip()  To remove spaces both sides
Finding Substrings:

We can use the following 4 methods


For forward direction:
1) find()
2) index()
For backward direction:
1) rfind()
2) rindex()
find():
s.find(substring)
Returns index of first occurrence of the given substring. If it is not available then we will
get -1.
1) s="Learning Python is very easy"
2) print(s.find("Python")) #9
3) print(s.find("Java")) # -1
4) print(s.find("r"))#3
index():
index() method is exactly same as find() method except that if the specified substring is
not available then we will get ValueError.

1) s=input("Enter main string:")


2) subs=input("Enter sub string:")
3) try:
4) n=s.index(subs)
5) except ValueError:
6) print("substring not found")
7) else:
8) print("substring found")
Counting substring in the given String:

We can find the number of occurrences of substring present in the given string by
using
count() method.
1) s.count(substring)  It will search through out the string.
2) s.count(substring, bEgin, end)  It will search from bEgin index to end-1

1) s="abcabcabcabcadda"
2) print(s.count('a'))
3) print(s.count('ab'))
4) print(s.count('a',3,7))x
Replacing a String with another String:

s.replace(oldstring, newstring)
inside s, every occurrence of old String will be replaced with new String.
Eg 1:
s = "Learning Python is very difficult"
s1 = s.replace("difficult","easy")
print(s1)
Output: Learning Python Is very easy

Q) String Objects are Immutable then how we can change the Content by
using replace() Method
Splitting of Strings:

 We can split the given string according to specified seperator by using split()
method.
 l = s.split(seperator)
 The default seperator is space. The return type of split() method is List.
1) s=“nothing changes if nothing changes"
2) l=s.split()
3) for x in l:
4) print(x)
Ask students
Joining of Strings:

We can join a Group of Strings (List OR Tuple) wrt the given Seperator.
s = seperator.join(group of strings)
Eg 1:
t = ('sunny', 'bunny', 'chinny')
s = '-'.join(t)
print(s)
Output: sunny-bunny-chinny
Changing Case of a String:

We can change case of a string by using the following 4 methods.


1) upper()  To convert all characters to upper case
2) lower()  To convert all characters to lower case
3) swapcase()  Converts all lower case characters to upper case and all upper case
characters to lower case
4) title()  To convert all character to title case. i.e first character in every word should
be upper case and all remaining characters should be in lower case.
5) capitalize()  Only first character will be converted to upper case and all remaining
characters can be converted to lower case
To Check Type of Characters Present in a String:

Python contains the following methods for this purpose.


1) isalnum(): Returns True if all characters are alphanumeric( a to z , A to Z ,0 to9
)
2) isalpha(): Returns True if all characters are only alphabet symbols(a to z,A to
Z)
3) isdigit(): Returns True if all characters are digits only( 0 to 9)
4) islower(): Returns True if all characters are lower case alphabet symbols
5) isupper(): Returns True if all characters are upper case aplhabet symbols
6) istitle(): Returns True if string is in title case
7) isspace(): Returns True if string contains only spaces
Formatting the Strings:

We can format the strings with variable values by using replacement operator {}
and
format() method.
1) name = ‘ben'
2) salary = 10000
3) age = 48
4) print("{} 's salary is {} and his age is {}".format(name,salary,age))
5) print("{0} 's salary is {1} and his age is {2}".format(name,salary,age))
6) print("{x} 's salary is {y} and his age is {z}".format(z=age,y=salary,x=name))
List datatype
If we want to represent a group of individual objects as a single entity where insertion
order preserved and duplicates are allowed, then we should go for List.
֍ insertion order preserved.
֍ duplicate objects are allowed.
֍ heterogeneous objects are allowed.
֍ List is dynamic because based on our requirement we can increase the size and
decrease the size.
֍ In List the elements will be placed within square brackets and with comma seperator.
֍ We can differentiate duplicate elements by using index and we can preserve insertion
order by using index. Hence index will play very important role.
֍ Python supports both positive and negative indexes. +ve index means from left to
right where as negative index means right to left.
[10,"A","B",20, 30, 10]
Creation of List Objects:

1) We can create empty list object as follows...


1) list=[]
2) print(list)
3) print(type(list))
4)
5) []
6) <class 'list'>
2) If we know elements already then we can create list as follows list = [10, 20,
30, 40]
3) With Dynamic Input:

1)# creating an empty list


2)lst = [ ]
3)# number of elements as input
4)n = int(input("Enter number of elements : "))
5)# iterating till the range
6)for i in range(0, n):
7) ele = int(input())
8) # adding the element
9) lst.append(ele)
10) print(lst)
4) With list() Function:
1) l=list(range(0,10,2))
2) print(l)
3) print(type(l))
D:\Python_classes>py test.py
[0, 2, 4, 6, 8]

1) s=“unaagii"
2) l=list(s)
3) print(l)
['u', 'n', 'a', 'a', 'g', 'i', 'i']
4)With split()
1) s="Learning Python is very very easy !!!"
2) l=s.split()
3) print(l)
4) print(type(l))
['Learning', 'Python', 'is', 'very', 'very', 'easy', '!!!‘]

1) lst2 = [item for item in input("Enter \


2) the list items : ").split()]
3) print(lst2)

Input: nothing changes if nothing changes


Output: ['nothing', 'changes', 'if', 'nothng', 'changes‘]
Accessing Elements of List:

We can access elements of the list either by using index or by using slice
operator(:)
1)By using Index:
֍ List follows zero based index. ie index of first element is zero.
֍ List supports both +ve and -ve indexes.
֍ +ve index meant for Left to Right
֍ -ve index meant for Right to Left
֍ list = [10, 20, 30, 40]
2)By using Slice Operator:
Syntax: list2 = list1[start:stop:step]
Start - It indicates the Index where slice has to Start
Default Value is 0
Stop - It indicates the Index where slice has to End
Default Value is max allowed Index of List ie Length of the List
Step - increment value
Default Value is 1
1) n=[1,2,3,4,5,6,7,8,9,10]
2) print(n[2:7:2])
3) print(n[4::2])
4) print(n[3:7])
5) print(n[8:2:-2])
6) print(n[4:100])

Output
[3, 5, 7]
[5, 7, 9]
[4, 5, 6, 7]
[9, 7, 5]
[5, 6, 7, 8, 9, 10]
List vs Mutability:

Once we creates a List object, we can modify its content. Hence List objects are
mutable.
1) n=[10,20,30,40]
2) print(n)
3) n[1]=777
4) print(n)
D:\Python_classes>py test.py
[10, 20, 30, 40]
[10, 777, 30, 40]
Traversing the Elements of List:
1)By using while Loop:

1) nl = [0,1,2,3,4,5]
2) i = 0
3) while i < len(nl):
4) print(nl[i])
5) i=i+1
Output:
0
1
2
3
4
5
1)By using for Loop:
1) nl = [0,1,2,3,4,5]
2) for i in nl:
3) print (i)
Important Functions of List:

1) len():
Returns the number of elements present in the list
Eg: n = [10, 20, 30, 40]
print(len(n) - 4

2) count():
It returns the number of occurrences of specified item in the list
1) n=[1,2,2,2,2,3,3]
2) print(n.count(1))
3) print(n.count(2))
4) print(n.count(3))
5) print(n.count(4))
D:\Python_classes>py test.py
1
4
2
0
3) index():
Returns the index of first occurrence of the specified item.
1) n = [1, 2, 2, 2, 2, 3, 3]
2) print(n.index(1))  0
3) print(n.index(2))  1
4) print(n.index(3))  5
5) print(n.index(4))  ValueError: 4 is not in list
Note: If the specified element not present in the list then we will get ValueError.Hence
before index() method we have to check whether item present in the list or not by using
in operator.
print( 4 in n) - False
II. Manipulating Elements of List:

1) append() Function:
We can use append() function to add item at the end of the list.
1) list=[]
2) list.append("A")
3) list.append("B")
4) list.append("C")
5) print(list)
D:\Python_classes>py test.py
['A', 'B', 'C']
2) insert() Function:
To insert item at specified index position
1) n=[1,2,3,4,5]
2) n.insert(1,888)
3) print(n)
[1, 888, 2, 3, 4, 5]

1) n=[1,2,3,4,5]
2) n.insert(10,777)
3) n.insert(-10,999)
4) print(n)
[999, 1, 2, 3, 4, 5, 777]
3) extend() Function:
To add all items of one list to another list
l1.extend(l2)
all items present in l2 will be added to l1
1) order1=["Chicken","Mutton","Fish"]
2) order2=["RC","KF","FO"]
3) order1.extend(order2)
4) print(order1)
['Chicken', 'Mutton', 'Fish', 'RC', 'KF', 'FO']

1) order = ["Chicken","Mutton","Fish"]
2) order.extend("Mushroom")
3) print(order)
['Chicken', 'Mutton', 'Fish', 'M', 'u', 's', 'h', 'r', 'o', 'o', 'm']
4) remove() Function:
We can use this function to remove specified item from the list.If the item present
multiple times then only first occurrence will be removed.
1) n=[10,20,10,30]
2) n.remove(10)
3) print(n)
D:\Python_classes>py test.py
[20, 10, 30]
If the specified item not present in list then we will get ValueError
5) pop() Function:
 It removes and returns the last element of the list.
 This is only function which manipulates list and returns some element.
1) n=[10,20,30,40]
2) print(n.pop())
3) print(n.pop())
4) print(n)
40
30
[10, 20]
If the list is empty then pop() function raises IndexError
Note:
1) pop() is the only function which manipulates the list and returns some value
2) In general we can use append() and pop() functions to implement stack
datastructure
by using list,which follows LIFO(Last In First Out) order.
In general we can use pop() function to remove last element of the list. But we
can use to
remove elements based on index.
n.pop(index)  To remove and return element present at specified index.
n.pop()  To remove and return last element of the list
Note: List Objects are dynamic. i.e based on our requirement we can increase
and decrease the size.
append(), insert(), extend() -for increasing the size/growable nature
remove(), pop() - for decreasing the size /shrinking nature
III) Ordering Elements of List:
1) reverse():
We can use to reverse() order of elements of list.
1) n=[10,20,30,40]
2) n.reverse()
3) print(n)
D:\Python_classes>py test.py
[40, 30, 20, 10]
2)sort():
In list by default insertion order is preserved. If want to sort the elements of list
according to default natural sorting order then we should go for sort() method.
 For numbers  Default Natural sorting Order is Ascending Order
 For Strings  Default Natural sorting order is Alphabetical Order
1) n = [20,5,15,10,0]
2) n.sort()
3) print(n) - [0,5,10,15,20]
5) s = ["Dog","Banana","Cat","Apple"]
6) s.sort()
7) print(s)  ['Apple','Banana','Cat','Dog']
Note: To use sort() function, compulsory list should contain only homogeneous
elements.
Otherwise we will get TypeError
1) n=[20,10,"A","B"]
2) n.sort()
3) print(n)
TypeError: '<' not supported between instances of 'str' and 'int'
Note: In Python 2 if List contains both numbers and Strings then sort() function first sort
numbers followed by strings
1) n=[20,"B",10,"A"]
2) n.sort()
3) print(n)# [10,20,'A','B']
But in Python 3 it is invalid.
To Sort in Reverse of Default Natural Sorting Order:

We can sort according to reverse of default natural sorting order by using


reverse=True
argument.
1) n = [40,10,30,20]
2) n.sort()
3) print(n)  [10,20,30,40]
4) n.sort(reverse = True)
5) print(n)  [40,30,20,10]
6) n.sort(reverse = False)
7) print(n)  [10,20,30,40]
Aliasing and Cloning of List Objects:

The process of giving another reference variable to the existing list is called aliasing.
1) x=[10,20,30,40]
2) y=x
3) print(id(x))
4) print(id(y))
The problem in this approach is by using one reference variable if we are changing
content, then those changes will be reflected to the other reference variable.
1) x = [10,20,30,40]
2) y = x
3) y[1] = 777
4) print(x) 
- [10,777,30,40]
To overcome this problem we should go for cloning.
The process of creating exactly duplicate independent object is called cloning.
We can implement cloning by using slice operator or by using copy() function
1) By using Slice Operator:
1) x = [10,20,30,40]
2) y = x[:]
3) y[1] = 777
4) print(x)  [10, 20, 30, 40]
5) print(y)  [10, 777, 30, 40]

2) By using copy() Function:


1) x = [10,20,30,40]
2) y = x.copy()
3) y[1] = 777
4) print(x)  [10, 20, 30, 40]
5) print(y)  [10, 777, 30, 40]
Using Mathematical Operators for List Objects:
We can use + and * operators for List objects.
1) Concatenation Operator (+):
We can use + to concatenate 2 lists into a single list
1) a = [10, 20, 30]
2) b = [40, 50, 60]
3) c = a+b
4) print(c) - [10, 20, 30, 40, 50, 60]
Note: To use + operator compulsory both arguments should be list objects, otherwise we
will get TypeError.
Eg:
c = a+40 - TypeError: can only concatenate list (not "int") to list.
c = a+[40] - Valid
2) Repetition Operator (*):
We can use repetition operator * to repeat elements of list specified number of
times.
1) x = [10, 20, 30]
2) y = x*3
3) print(y) -[10, 20, 30, 10, 20, 30, 10, 20, 30]
Comparing List Objects

We can use comparison operators for List objects.


1) x = ["Dog", "Cat", "Rat"]
2) y = ["Dog", "Cat", "Rat"]
3) z = ["DOG", "CAT", "RAT"]
4) print(x == y) -True
5) print(x == z) - False
6) print(x != z) - True
Note: Whenever we are using comparison operators (==, !=) for List objects then the
following should be considered
1) The Number of Elements
2) The Order of Elements
3) The Content of Elements (Case Sensitive)
Membership Operators:

We can check whether element is a member of the list or not by using memebership
operators.
1) in Operator
2) not in Operator
1) n=[10,20,30,40]
2) print (10 in n)
3) print (10 not in n)
4) print (50 in n)
5) print (50 not in n)

Output
True
False
False
True
clear() Function:
We can use clear() function to remove all elements of List.
1) n=[10,20,30,40]
2) print(n)
3) n.clear()
4) print(n)
Output D:\Python_classes>
py test.py [10, 20, 30, 40] []
Nested Lists:

we can take one list inside another list. Such type of lists are called nested lists.
1) n=[10,20,[30,40]]
2) print(n)
3) print(n[0])
4) print(n[2])
5) print(n[2][0])
6) print(n[2][1])
Output
[10, 20, [30, 40]]
10
[30, 40]
30
40
Nested List as Matrix:

In Python we can represent matrix by using nested lists.


1) n=[[10,20,30],[40,50,60],[70,80,90]]
2) print(n)
3) print("Elements by Row wise:")
4) for r in n:
5) print(r)
6) print("Elements by Matrix style:")
7) for i in range(len(n)):
8) for j in range(len(n[i])):
9) print(n[i][j],end=' ')
10) print()
Output
D:\Python_classes>py test.py
[[10, 20, 30], [40, 50, 60], [70, 80, 90]]
Elements by Row wise:
[10, 20, 30]
[40, 50, 60]
[70, 80, 90]
Elements by Matrix style:
10 20 30
40 50 60
70 80 90
Tuple Datatype
1) Tuple is exactly same as List except that it is immutable. i.e once we creates Tuple
object, we cannot perform any changes in that object.
2) Hence Tuple is Read only version of List.
3) If our data is fixed and never changes then we should go for Tuple.
4) Insertion Order is preserved
5) Duplicates are allowed
6) Heterogeneous objects are allowed.
7) We can preserve insertion order and we can differentiate duplicate objects by using
index. Hence index will play very important role in Tuple also.
8) Tuple support both +ve and -ve index. +ve index means forward direction (from left to
right) and -ve index means backward direction (from right to left)
9) We can represent Tuple elements within Parenthesis and with comma seperator.
10) Parenethesis are optional but recommended to use.
Note: We have to take special care about single valued tuple.compulsary the
value
should ends with comma, otherwise it is not treated as tuple.
1) t=(10)
2) print(t)
3) print(type(t))
4)
5) Output
6) 10
7) <class 'int'>
● 1) t=(10,)
● 2) print(t)
● 3) print(type(t))
● 4)
● 5) Output
● 6) (10,)
● 7) <class 'tuple'>
Tuple Creation:

1) t = ()
Creation of Empty Tuple
2) t = (10,)
t = 10,
Creation of Single valued Tuple, Parenthesis are Optional, should ends with
Comma
3) t = 10, 20, 30
t = (10, 20, 30)
Creation of multi values Tuples & Parenthesis are Optional.
4) By using tuple() Function:
1) list=[10,20,30]
2) t=tuple(list)
3) print(t)
4)
5) t=tuple(range(10,20,2))
6) print(t)
Accessing Elements of Tuple:

We can access either by index or by slice operator


1) By using Index:
1) t = (10, 20, 30, 40, 50, 60)
2) print(t[0])  10
3) print(t[-1])  60
4) print(t[100])  IndexError: tuple index out of range
2) By using Slice Operator:
1) t=(10,20,30,40,50,60)
2) print(t[2:5])
3) print(t[2:100])
4) print(t[::2])
Output
(30, 40, 50)
(30, 40, 50, 60)
(10, 30, 50
Mathematical Operators for Tuple:

We can apply + and * operators for tuple


1) Concatenation Operator (+):
1) t1=(10,20,30)
2) t2=(40,50,60)
3) t3=t1+t2
4) print(t3)  (10,20,30,40,50,60)
Multiplication Operator OR Repetition Operator (*)
1) t1=(10,20,30)
2) t2=t1*3
3) print(t2)  (10,20,30,10,20,30,10,20,30)

Important Functions of Tuple:


1) len()
To return number of elements present in the tuple.
Eg: t = (10,20,30,40)
print(len(t))  4
2) count()
To return number of occurrences of given element in the tuple
Eg: t = (10, 20, 10, 10, 20)
print(t.count(10))  3
3) index()
 Returns index of first occurrence of the given element.
 If the specified element is not available then we will get ValueError.
Eg: t = (10, 20, 10, 10, 20)
print(t.index(10))  0
print(t.index(30))  ValueError: tuple.index(x): x not in tuple
4)sorted()
To sort elements based on default natural sorting order
1) t=(40,10,30,20)
2) t1=sorted(t)
3) print(t1)
4) print(t)
Output
[10, 20, 30, 40]
(40, 10, 30, 20)
We can sort according to reverse of default natural sorting order as follows
t1 = sorted(t, reverse = True)
print(t1)  [40, 30, 20, 10
5) min() And max() Functions:
These functions return min and max values according to default natural sorting order.
1) t = (40,10,30,20)
2) print(min(t))  10
3) print(max(t))  40
6) cmp():
֍ It compares the elements of both tuples.
֍ If both tuples are equal then returns 0
֍ If the first tuple is less than second tuple then it returns -1
֍ If the first tuple is greater than second tuple then it returns +1
1) t1=(10,20,30)
2) t2=(40,50,60)
3) t3=(10,20,30)
4) print(cmp(t1,t2))  -1
5) print(cmp(t1,t3))  0
6) print(cmp(t2,t3))  +1
Tuple Packing and Unpacking:
We can create a tuple by packing a group of variables.
Eg:
a = 10
b = 20
c = 30
d = 40
t = a, b, c, d
print(t)  (10, 20, 30, 40)
 Here a, b, c, d are packed into a Tuple t. This is nothing but Tuple packing.
 Tuple unpacking is the reverse process of Tuple packing.
 We can unpack a Tuple and assign its values to different variables.
1) t=(10,20,30,40)
2) a,b,c,d=t
3) print("a=",a,"b=",b,"c=",c,"d=",d)
Output: a= 10 b= 20 c= 30 d= 40
Note: At the time of tuple unpacking the number of variables and number of
values
should be same, otherwise we will get ValueError.
Eg:
t = (10,20,30,40)
a, b, c = t  ValueError: too many values to unpack (expected 3)
Set datatype
 If we want to represent a group of unique values as a single entity then we should go
for set.
 Duplicates are not allowed.
 Insertion order is not preserved.But we can sort the elements.
 Indexing and slicing not allowed for the set.
 Heterogeneous elements are allowed.
 Set objects are mutable i.e once we creates set object we can perform any changes in
that object based on our requirement.
 We can represent set elements within curly braces and with comma seperation
 We can apply mathematical operations like union, intersection, difference etc on set
objects.
Creation of Set Objects:

1) s={10,20,30,40}
2) print(s)
3) print(type(s))
Output
{40, 10, 20, 30}
<class 'set'>
We can create set objects by using set() Function s = set(any sequence) Note:
֍ While creating empty set we have to take special care.
֍ Compulsory we should use set() function.
֍ s = {}  It is treated as dictionary but not empty set
Important Functions of Set:
1) add(x):
Adds item x to the set.
1) s={10,20,30}
2) s.add(40);
3) print(s) #{40, 10, 20, 30}
2) update(x,y,z):
 To add multiple items to the set.
 Arguments are not individual elements and these are Iterable objects like List,
Range
etc.
 All elements present in the given Iterable objects will be added to the set.
1) s={10,20,30}
2) l=[40,50,60,10]
3) s.update(l,range(5))
4) print(s)
Output: {0, 1, 2, 3, 4, 40, 10, 50, 20, 60, 30}
Which of the following are valid for set s?
1) s.add(10)
2) s.add(10,20,30)
3) s.update(10)
4) s.update(range(1,10,2),range(0,10,2))

Ask studnets
3) copy():
 Returns copy of the set.
 It is cloned object.
1) s = {10,20,30}
2) s1 = s.copy()
3) print(s1)
4) pop():
It removes and returns some random element from the set.
1) s={40,10,30,20}
2) print(s)
3) print(s.pop())
4) print(s)
Output
{40, 10, 20, 30}
40
{10, 20, 30}
5) remove(x):
 It removes specified element from the set.
 If the specified element not present in the Set then we will get KeyError.
1) s = {40, 10, 30, 20}
2) s.remove(30)
3) {40, 10, 20}
4) s.remove(50 )KeyError: ) 50
6) discard(x):
1) It removes the specified element from the set.
2) If the specified element not present in the set then we won't get any error.
1) s = {10, 20, 30}
2) s.discard(10)
7) clear():
To remove all elements from the Set.
1) s={10,20,30}
2) print(s)
3) s.clear()
4) print(s)
Output
{10, 20, 30}
set()
Mathematical Operations on the Set:

1) union():
x.union(y) - We can use this function to return all elements present in both sets
x.union(y) OR x|y.
1) x = {10, 20, 30, 40}
2) y = {30, 40, 50, 60}
3) print (x.union(y))  {10, 20, 30, 40, 50, 60}
4) print (x|y)  {10, 20, 30, 40, 50, 60}
2) intersection():
 x.intersection(y) OR x&y.
 Returns common elements present in both x and y.
1) x = {10, 20, 30, 40}
2) y = {30, 40, 50, 60}
3) print (x.intersection(y))  {40, 30}
4) print(x&y)  {40, 30}
3) difference():
 x.difference(y) OR x-y.
 Returns the elements present in x but not in y.
1) x = {10, 20, 30, 40}
2) y = {30, 40, 50, 60}
3) print (x.difference(y))  10, 20
4) print (x-y)  {10, 20}
5) print (y-x)  {50, 60}
4)symmetric_difference():
 x.symmetric_difference(y) OR x^y.
 Returns elements present in either x OR y but not in both.
1) x = {10, 20, 30, 40}
2) y = {30, 40, 50, 60}
3) print (x.symmetric_difference(y))  {10, 50, 20, 60}
4) print(x^y)  {10, 50, 20, 60}
4)symmetric_difference():
 x.symmetric_difference(y) OR x^y.
 Returns elements present in either x OR y but not in both.
1) x = {10, 20, 30, 40}
2) y = {30, 40, 50, 60}
3) print (x.symmetric_difference(y))  {10, 50, 20, 60}
4) print(x^y)  {10, 50, 20, 60}
Membership Operators: (in, not in)
1) s=set("durga")
2) print(s)
3) print('d' in s)
4) print('z' in s)
Output
{'u', 'g', 'r', 'd', 'a'}
True
False
Set Comprehension:
Set comprehension is possible.
1) s = {x*x for x in range(5)}
2) print (s)  {0, 1, 4, 9, 16}
3)
4) s = {2**x for x in range(2,10,2)}
5) print (s)  {16, 256, 64, 4}
Set Objects won't support indexing and slicing:
1) s = {10,20,30,40} 2) print(s[0])  TypeError: 'set' object does not support
indexing 3) print(s[1:3])  TypeError: 'set' object is not subscriptable
Write a Program to eliminate Duplicates Present in the List

Approach - 1
1) l=eval(input("Enter List of values: "))
2) s=set(l)
3) print(s)
D:\Python_classes>py test.py
Enter List of values: [10,20,30,10,20,40]
{40, 10, 20, 30}
DICTIONARY DataType
֍ We can use List, Tuple and Set to represent a group of individual objects as a single
entity.
֍ If we want to represent a group of objects as key-value pairs then we should go for
Dictionary.
֍ Duplicate keys are not allowed but values can be duplicated.
֍ Hetrogeneous objects are allowed for both key and values.
֍ Insertion order is not preserved
֍ Dictionaries are mutable
֍ Dictionaries are dynamic
֍ indexing and slicing concepts are not applicable
How to Create Dictionary?

 d = {} OR d = dict()
 We are creating empty dictionary. We can add entries as follows
1) d[100]=“RED"
2) d[200]=“BLUE"
3) d[300]=“GREEN"
4) print(d)  {100: ‘RED', 200: ‘BLUE’, 300: ‘GREEN'}
 If we know data in advance then we can create dictionary as follows
 d = {100:‘RED' ,200:‘BLUE', 300:' GREEN '}
 d = {key:value, key:value}
How to Access Data from the Dictionary?
We can access data by using keys.
1) d = {100:‘ken',200:‘adams', 300:‘is'}
2) print(d[100]) #ken
3) print(d[300]) #is
print(d[400]) - KeyError: 400
We can prevent this by checking whether key is already available or not by using
has_key() function or by using in operator
.
d.has_key(400) - Returns 1 if key is available otherwise returns 0

But has_key() function is available only in Python 2 but not in Python 3. Hence
compulsory we have to use in operator.
if 400 in d:
print(d[400])
How to Update Dictionaries?
֍ d[key] = value
֍ If the key is not available then a new entry will be added to the dictionary with
the
specified key-value pair
֍ If the key is already available then old value will be replaced with new value.
1) d={100:“red",200:“red3",300:“red"}
2) print(d)
3) d[400]=“grey"
4) print(d)
5) d[100]=“black"
6) print(d)

Output {100: ‘red', 200: ' red3', 300: ‘red'}


{100: ‘red', 200: 'ravi', 300: ‘red3 ', 400: ‘grey'}
{100: ‘black', 200: 'ravi', 300: ‘red3, 400: ‘grey'}
How to Delete Elements from Dictionary?

1) del d[key]
 It deletes entry associated with the specified key.
 If the key is not available then we will get KeyError.
1) d={100:"durga",200:"ravi",300:"shiva"}
2) print(d)
3) del d[100]
4) print(d)
5) del d[400]
Output
{100: 'durga', 200: 'ravi', 300: 'shiva'}
{200: 'ravi', 300: 'shiva'}
KeyError: 400
2) d.clear()
To remove all entries from the dictionary.
1) d={100:"durga",200:"ravi",300:"shiva"}
2) print(d)
3) d.clear()
4) print(d)

Output {100: 'durga', 200: 'ravi', 300: 'shiva'}


{}
3) del d
To delete total dictionary.Now we cannot access d.
1) d={100:"durga",200:"ravi",300:"shiva"}
2) print(d)
3) del d
4) print(d)
Output
{100: 'durga', 200: 'ravi', 300: 'shiva'}
NameError: name 'd' is not defined
Important Functions of Dictionary:

1) dict():
To create a dictionary
 d = dict()  It creates empty dictionary
 d = dict({100:"durga",200:"ravi"})  It creates dictionary with specified elements
 d = dict([(100,"durga"),(200,"shiva"),(300,"ravi")])
 It creates dictionary with the given list of tuple elements

2) len()
Returns the number of items in the dictionary.
4) get():
To get the value associated with the key
d.get(key)
If the key is available then returns the corresponding value otherwise returns
None.It
wont raise any error
d.get(key,defaultvalue)
If the key is available then returns the corresponding value otherwise returns default
value.
1) d={100:"durga",200:"ravi",300:"shiva"}
2) print(d[100])  durga
3) print(d[400])  KeyError:400
4) print(d.get(100))  durga
5) print(d.get(400))  None
6) print(d.get(100,"Guest"))  durga
7) print(d.get(400,"Guest"))  Guest
5) pop():
d.pop(key)
 It removes the entry associated with the specified key and returns the
corresponding value.
 If the specified key is not available then we will get KeyError.
1) d={100:"durga",200:"ravi",300:"shiva"}
2) print(d.pop(100))
3) print(d)
4) print(d.pop(400))
Output
durga
{200: 'ravi', 300: 'shiva'}
KeyError: 400
6) popitem():
It removes an arbitrary item(key-value) from the dictionaty and returns it.
1) d={100:"durga",200:"ravi",300:"shiva"}
2) print(d)
3) print(d.popitem())
4) print(d)
Output
{100: 'durga', 200: 'ravi', 300: 'shiva'}
(300, 'shiva')
{100: 'durga', 200: 'ravi'}
If the dictionary is empty then we will get KeyError
d={}
print(d.popitem()) ==>KeyError: 'popitem(): dictionary is empty
7) keys():
It returns all keys associated eith dictionary.
1) d={100:"durga",200:"ravi",300:"shiva"}
2) print(d.keys())
3) for k in d.keys():
4) print(k)
Output
dict_keys([100, 200, 300])
100
200
300
8) values():
It returns all values associated with the dictionary.
1) d={100:"durga",200:"ravi",300:"shiva"}
2) print(d.values())
3) for v in d.values():
4) print(v)
Output
dict_values(['durga', 'ravi', 'shiva'])
durga
ravi
shiva
9) items():
It returns list of tuples representing key-value pairs.
[(k,v),(k,v),(k,v)]
1) Output
100 -- durga
200 -- ravi
300 – shiva

10) copy():
To create exactly duplicate dictionary (cloned copy)
d1 = d.copy();
12) update():
d.update(x)
All items present in the dictionary x will be added to dictionary d

13) setdefault():
d.setdefault(k,v)
 If the key is already available then this function returns the corresponding value.
 If the key is not available then the specified key-value will be added as new item
to
the dictionary.
1) d={100:"durga",200:"ravi",300:"shiva"}
2) print(d.setdefault(400,"pavan"))
3) print(d)
4) print(d.setdefault(100,"sachin"))
5) print(d)
Output
pavan
{100: 'durga', 200: 'ravi', 300: 'shiva', 400: 'pavan'}
durga
{100: 'durga', 200: 'ravi', 300: 'shiva', 400: 'pavan'}

You might also like