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

Ch No 3 Data Structure in Python

This document provides an overview of data structures in Python, specifically focusing on lists. It covers list creation, accessing values, copying, mutability, updating, and various methods for modifying lists, such as append, extend, and remove. Additionally, it explains basic operations like concatenation, repetition, slicing, and membership testing.

Uploaded by

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

Ch No 3 Data Structure in Python

This document provides an overview of data structures in Python, specifically focusing on lists. It covers list creation, accessing values, copying, mutability, updating, and various methods for modifying lists, such as append, extend, and remove. Additionally, it explains basic operations like concatenation, repetition, slicing, and membership testing.

Uploaded by

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

CH NO 3 DATA STRUCTURE IN PYTHON

MARKS:14
COURSE OUTCOME
🞆 Perform operation on Data Structure in
Python
List
LIST
🞆 A list is a collection which is ordered and
changeable. In Python lists are written with
square brackets.
🞆 The list is a most versatile data type
available in Python which can be written as a
list of comma-separated values (items)
between square brackets.
🞆 Important thing about a list is that items in a
list need not be of the same type.
CREATING A LIST
🞆 Creating a list is as simple as putting
different comma-separated values between
square brackets. For example −

🞆 Similar to string indices, list indices start at


0, and lists can be sliced, concatenated and
so on.
CREATING A LIST EXAMPLES
#creating a empty list
>>> list1=[]
>>> list1
[]

#creating a list of mixed data type


>>>list4=[1,”Two”,11.20,'x']
>>>list4
[1, ‘Two', 11.2, 'x']

#creating a list using inbuilt range() function


>>>list5=list(range(0,5))
>>> list5
[0, 1, 2, 3, 4]

#creating a list with in-built characters A,B,C


list6=list("ABC")
>>> list6
['A', 'B', 'C']

>>> list6=list("ABCdef123")
>>> list6
['A', 'B', 'C', 'd', 'e', 'f', '1', '2', '3']
ACCESSING VALUES IN LISTS

🞆 To access values in lists, use the square


brackets for slicing along with the index or
indices to obtain value available at that
index.
🞆 For example −
list1=['physics','che',1997,2002]
print ("list[0]:",list1[0])
#output:
list[0]: physics
EXAMPLE
list1=["one","two",3,10,"six",20]

print("list1:",list1)
print("list1[0]:",list1[0])
print("list1[-2]:",list1[-2])
print("list1[1:3]:",list1[1:3])
print("list1[3:]:",list1[3:])
print("list1[:4]:",list1[:4])
OUTPUT
list1: ['one', 'two', 3, 10, 'six', 20]
list1[0]: one
list1[-2]: six
list1[1:3]: ['two', 3]
list1[3:]: [10, 'six', 20]
list1[:4]: ['one', 'two', 3, 10]
COPYING THE LIST
🞆 We can make a duplicate or copy of an existing list.
For Example.
List1=[10,20,30,40]
List2=List1
In the first statement List1 is pointing to the
List[10,20,30,40]
In The second statement we are not copying List
but we are making another variable List2 and attach
it to the list pointed by List1.
Both Variable are pointing to the same list.
Due to this if we modify the List1 ,then the
modification will also take place and vice versa. in
List2
EXAMPLE
List1=[10,20,30,40]
List2=List1
print(List2)
List1.append(50)
print(List1)
print(List2)
Output:
[10, 20, 30, 40]
[10, 20, 30, 40, 50]
[10, 20, 30, 40, 50]
🞆 There are two ways to make a copy of a List
1.Using [:] operator
For Example:
List1=[10,20,30,40]
List2=List1[:]
print(List1)
print(List2)
Output
[10, 20, 30, 40]
[10, 20, 30, 40]
2.using Built in copy Function
It use copy function to make copy of an existing list.
In order to use copy function,first we have to import
For example
from copy import copy
List1=[10,20,30,40]
List2=copy(List1)
print(List1)
print(List2)
Output
[10, 20, 30, 40]
[10, 20, 30, 40]
LIST ARE MUTABLE
🞆 The value of any element inside the List can
be changed at any point of time.
🞆 The Elements of the List are accessible with
their index value.The index always start with
0 and ends with n-1,if the list contains n
elements.
🞆 Example
List1=[10,20,30,40]
List1[2]=50
print(List1)
Output
[10, 20, 50, 40]
UPDATING LISTS

🞆 You can update single or multiple elements of


lists by giving the slice on the left-hand side
of the assignment operator, and you can add
elements in a list .
🞆 For example −
EXAMPLE
>>> list1=[10,20,30,40,50]
>>> list1
[10, 20, 30, 40, 50]

#change 0th index element


>>> list1[0]=0
>>> list1
[0, 20, 30, 40, 50]

#change last index element


>>> list1[-1]=60
>>> list1
[0, 20, 30, 40, 60]
#change 1st element as sublist
>>> list1[1]=[5,10]
>>> list1
[0, [5, 10], 30, 40, 60]

#Modifying a list using slicing


# add elements to a list at the desired location
>>> list1[1:1]=[3,4]
>>> list1
[0, 3, 4, [5, 10], 30, 40, 60]

>>> list1=[10,20,30,40,50]
>>> list1[1:4]=[99,98,97]
>>> list1
[10, 99, 98, 97, 50]
#Modifying a list using slicing

list1=[10,20,30,40,50]
>>> list1[2:2]=[99,98,97]
>>> list1
[10, 20, 99, 98, 97, 30, 40, 50]

list1=[10,20,30,40,50]
>>> list1[3:2]=[99,98,97]
>>> list1
[10, 20, 30, 99, 98, 97, 40, 50]
FOLLOWING METHODS USED FOR
UPDATING LIST
1. append()
Syntax:
list.append(item)
-The item can be numbers,string,another list,dictionary etc.
-only modifies the original list.It does not return any value.
2. extend()
Syntax:
list1.extend(list2)
-This extend() method takes a list and adds it to the end.
-only modifies the original list.It does not return any value.
3. insert()
4. Syntax:
list.insert(index,element)
-The index is position where an element needs to be
inserted.
only modifies the original list.It does not return any value.
1.append()
The append() method adds an element to the
end of a list.We can insert a single item in
the list.

#add element at the end of list


>>> list1=[10,20,30]
>>> list1
[10, 20, 30]
>>> list1.append(40)
>>> list1
[10, 20, 30, 40]
2. extend()
The extend() method extends a list by
appending items. we can add several items
using extend() method.

>>> list1=[10,20,30,40]
>>> list1
[10, 20, 30, 40]
>>> list1.extend([60,70])
>>> list1
[10, 20, 30, 40, 60, 70]
3. insert()
We can insert one single item at a desired
location by using the method insert() or insert
multiple items by squeezing it into an empty
slice of a list

>>> list1.insert(1,30)
>>> list1
[10, 30, 20]
DELETE LIST ELEMENTS

Python provides many ways in which the


elements in a list can be deleted.

1. del operator or del statement-


We can delete one or more items from a list
using the keyword ‘del’.It can even delete the
list entirely.But it does not store the value for
further use.
EXAMPLE

list1=[10,20,30,40]
>>> list1
[10, 20, 30, 40]

>>> del(list1[1])
>>> list1
[10, 30, 40]

>>> del list1


>>> list1

Traceback (most recent call last):


File "<stdin>", line 1, in <module>
NameError: name 'list1' is not defined. Did you mean:
'list'?
2. pop operator or pop statement-
The pop() method in python is used to remove a
particular item/element from the given index in the
list.The pop() method is used to removes and
returns the last item if index is not provided .This
helps us implement lists as stacks(First In,Last Out
For Example
list=[10,20,30,40]
list.pop(3)
print(list)
output
[10, 20, 30]
EXAMPLE
#pop with index
list1=[10,20,30,40]
>>> list1
[10, 20, 30, 40]
list1.pop(2)
#output
30
>>>list1
[10, 20, 40]

#pop without index


>>> list1.pop()
#Output
40
3.remove operator or remove statement:-
🞆 The remove() method in python is used to
remove a particular element from the list.We
use the remove() method if we know the
item that we want to remove or delete from
the list(but not the index)
🞆 For Example
list=[10,20,30,40]
list.remove(30)
print(list)
output:
[10, 20, 40]
EXAMPLE
list1=[10,"one",20,"two"]
>>> list1.remove(20)
>>> list1
[10, 'one', 'two']

>>> list1.remove("one")
>>> list1
[10, 'two']
BASIC LIST OPERATIONS

1. Concatenation:
We can also use + operator to combine two
lists. This is also called
concatenation
>>> list1=[10,20,30]
>>> list1
[10, 20, 30]
>>> list1+[40,50,60]
[10, 20, 30, 40, 50, 60]
CONCATENATION EXAMPLE
>>> list2=[1.1,2.2,"Anna",78]
>>> list3=[1,2,3,4,5.5,"Diana"]
>>> list2+list3
[1.1, 2.2, 'Anna', 78, 1, 2, 3, 4, 5.5, 'Diana']
2. Repetition:
The * operator repeats a list for the given
number of times.
>>> list2 ['A', 'B']
>>> list2 *2
['A', 'B', 'A', 'B']

print(["re"] * 3)
#Output:
["re", "re", "re"]
3. slice:
This operation gives us character from given
index.Operator is symbolized using “[]”
brackets.
You can retrieve any element using this
operator.
>>> list2=[1.1,2.2,"Anna",78]
>>> list2[2]
'Anna'
4. Range slice or list slicing:
This operation return the characters from a
specified range.Operator is symbolized
using”[:]” sign.You can retrieve range of the
elements using this operator.

>>> list3=[1,2,3,4,5.5,"Diana"]
>>> list3[1:3]
[2, 3]
5. Membership:

-This operation is used to check whether that particular


element belongs to the list or not.
-Operator is symbolized using “in” word.
-If the element is present in the list then result will be
true otherwise false.

>>> list=[1,2,3,4,"Anna"]
>>> 2 in list
True

>>> "Anna" in list


True

>>> 5 in list
False
6 EXPLAIN INDEXING AND SLICING IN LIST WITH EXAMPLE INDEXING:

1. Indexing: An individual item in the list can be referenced


by
using an index, which is an integer number that indicates the
relative position of the item in the list.
There are various ways in which we can access the elements
of a list some as them are given below:
a). List Index: We can use the index operator [] to access
an
item in a list. Index starts from 0. So, a list having 5 elements
will have index from 0 to 4.
Example: For list index in list.
>>> list1=[10,20,30,40,50]
>>> list1[0]
10
>>> list1[1:3] # list[m:n] will return elements indexed from
m to n-1.
[20, 30]
b). Negative Indexing: 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.
Example: For negative indexing in list.
>>> list2=['p','y','t','h','o','n']
>>> list2[-1]
'n'
>>> list2[-6]
'p
2. List Slicing or range slicing:
🞆 Slicing is an operation that allows us to extract
elements from units. The slicing feature used by
Python to obtain a specific subset or element of the
data structure using the colon (:) operator.
🞆 The slicing operator returns a subset of a list called
slice by specifying two indices, i.e. start and end.
🞆 Syntax: list_variable[start_index:end_index]

This will return the subset of the list starting from


start_index to one index less than that of the end index.
🞆 Example: For slicing list.

>>> l1=([10,20,30,40,50])
>>> l1[1:4]
[20, 30, 40
WRITE BASIC OPERATIONS OF LIST
1)Accessing values in list:
To access values in lists, use the square
brackets for slicing along with the index or
indices to obtain value available at that index.
Example: accessing list values.
>>> list1 = ["one","two",3,10,"six",20]
>>> list1[0]
'one'
2) Deleting Values in List
The pop() method in Python is used to remove
a particular item/element from the given
index in the list. The pop() method removes
and returns the last item if index is not
Provided
>>> list[10, 20, 40]
>>> list.pop()
40
We can delete one or more items from a list
using the keyword del. It can even delete
the list entirely. But it does not store the value
for further use
>>> list= [10, 20, 30, 40]
>>> list
[10, 20, 30, 40]
>>> del (list[1]) # del() with index
>>> list
[10, 30, 40]
The remove() method in Python issued to
remove a particular element from the list. We
use the remove() method if we know the item
that we want to remove or delete from the
list (but not the index).
>>> list=[10,"one",20,"two"]
>>> list.remove(20)
>>> list
[10, 'one', 'two']
3. Updating Lists: • List are mutable, meaning their
elements can be changed or updated unlike string or
tuple.
We can update items of the list by simply assigning the
value at the particular index
position. We
can also remove the items from the list using remove()
or pop() or del statement.
>>> list1= [10, 20, 30, 40, 50]
>>> list1
[10, 20, 30, 40, 50]
>>> list1[0]=0 # change 0th index element
>>> list1
[0, 20, 30, 40, 50]
4 Indexing
There are various ways in which we can access
the elements of a list.
List Index: We can use the index operator [] to
access an item in a list. Index starts
from 0. So, a list having 5 elements will have
index from 0 to 4.
Example:
>>> list1=[10,20,30,40,50]
>>> list1[0]
10
5. List Slicing
The slicing operator returns a subset of a list
called slice by specifying two indices, i.e.
start and end.
Syntax:
List_variable[start_index:end_index]
Example:
>>> l1=([10,20,30,40,50])
>>> l1[1:4]
[20, 30, 40]
LIST SLICING WITH STEP INDEX
Syntax:
list_name[start_index:end_index:step_size]
Ex.

list1=['red',1,'yellow',2,'green',3,'blue',4]
print(list1)
list2=list1[0:6:2]
print(list2)
#output:
['red', 1, 'yellow', 2, 'green', 3, 'blue', 4]
['red', 'yellow', 'green']
COMPLEX EXAMPLE OF LIST SLICING
>>> list1=[10,20,30,40,50]
>>> list1
[10, 20, 30, 40, 50]
>>> list1[::-1]
[50, 40, 30, 20, 10]
>>> list1[-1:-6:-1]
[50, 40, 30, 20, 10]
TRAVERSING A LIST
🞆 Accessing all elements of the List.
🞆 It can be done by any conditional statement of
python,but it is preferable to use for loop.
🞆 Example1
List1=[10,20,30,40]
for x in List1:
print(x)
Output:
10
20
30
40
EX:

🞆 Example2
List1=[10,20,30,40]
for i in range (len(List1)):
List1[i]=List1[i]+4
print(List1)

#Output
[14, 24, 34, 44]
EX:

list1=[[1,2,3,4],['A','B','C','D'],['@','#','$','&']]
for i in list1:
for j in i:
print(j,end=' ')
print('\n')

#output:
1234
ABCD
@#$&
METHODS OF LIST CLASS
1. list.append(item)
2. list.clear()
3. list.copy()
4. list.count(item)
5. list.extend(seq)
6. list.index(item)
7. list.insert(index,item)
8. list.pop(item)
9. list.remove(item)
10.list.reverse()
11.list.sort()
1.APPEND() METHOD

The append() method appends an element to the end of the list.


Syntax
List.append(Element)

Example

List1=[10,20,30,40]
List1.append(50)
print(List1)

Output
[10, 20, 30, 40, 50]
2.CLEAR() METHOD

🞆 The clear() method removes all the elements


from a list.
🞆 Syntax
List.clear()
🞆 Example
List1=[10,20,30,40]
List1.clear()
print(List1)
Output
[]
3.COPY() METHOD

🞆 The copy() method returns a copy of the specified


list.
🞆 Syntax

List.copy()
🞆 Example

List1=[10,20,30,40]
List2=List1.copy()
print(List2)

Output
[10, 20, 30, 40]
4.COUNT() METHOD

🞆 The count() method returns the number of


elements with the specified value.
🞆 Syntax
list.count(value)
🞆 Example
List1=[10,20,30,40,20,30,20]
x=List1.count(20)
print(x)
Output
3
5.EXTEND() METHOD

🞆 The extend() method adds the specified list elements


(or any iterable) to the end of the current list.
🞆 Syntax

List.extend(Sequence)
Sequence can be List,Tuple,Set etc
🞆 Example

List1=[10,20,30,40]
List2=[50,60]
List1.extend(List2)
print(List1)
Output
[10, 20, 30, 40, 50, 60]
6.INDEX() METHOD

🞆 The index() method returns the position at


the first occurrence of the specified value.
🞆 Syntax List.index(Element)
🞆 Example
List1=[10,20,30,40]
x=List1.index(30)
print(x)

🞆 Ouptut
2
7. INSERT() METHOD

🞆 The insert() method inserts the specified


value at the specified position.
🞆 Syntax
List.insert(position,element)
🞆 Example
List1=[10,20,30,40]
List1.insert(2,50)
print(List1)
🞆 Output
[10, 20, 50, 30, 40]
8.POP() METHOD

🞆 The pop() method removes the element at


the specified position.
🞆 Syntax
List.pop(position)
🞆 Example
List1=[10,20,30,40]
List1.pop(2)
print(List1)
🞆 Output
[10, 20, 40]
9.REMOVE() METHOD

🞆 The remove() method removes the first


occurrence of the element with the specified
value
🞆 Syntax
List.remove(Element)
🞆 Example
List1=[10,20,30,40]
List1.remove(20)
print(List1)
🞆 Output
[10, 30, 40]
10.REVERSE() METHOD

🞆 The reverse() method reverses the sorting


order of the elements.
🞆 Syntax
List.reverse()
🞆 Example
List1=[10,20,30,40]
List1.reverse()
print(List1)
🞆 Output
[40, 30, 20, 10]
11.SORT() METHOD

🞆 The sort() method sorts the list ascending by default.


🞆 You can also make a function to decide the sorting
criteria(s).
🞆 Syntax
🞆 Example
List1=[10,20,30,40]
List1.sort(reverse=True)
print(List1)
#output
[40, 30, 20, 10]

>>> List1.sort(reverse=False)
>>> List1
#output
[10, 20, 30, 40]
BUILT-IN FUNCTION
1. len(list)
2. max(list)
3. min(list)
4. sum(list)
1. LEN() METHOD
🞆 It returns the number of elements in the list.
🞆 Syntax
len(List)
🞆 Example
List1=[10,20,30,40]
x=len(List1)
print(x)

🞆 Output
4
2. MAX()
It returns the item that has the maximum
value in list.
Syntax:
max(list)

Example
List1=[10,20,30,40]
max(List1)
#Output:
40
3. MIN() METHOD
It returns the item that has the maximum
value in list.
Syntax:
min(list)

Example
List1=[10,20,30,40]
min(List1)
#Output:
10
4. SUM()
Calculate sum of all the elements of list.
Syntax:
sum(list)

Example
List1=[10,20,30,40]
sum(List1)
#Output:
100
1.Write the output of the following
>>> a=[2,5,1,3,6,9,7]
>>> a[2:6]=[2,4,9,0]
>>> print(a)
2.
>>> b=[“Hello”,”Good”]
>>> b.append(“python”)
>>>print(b)
3.
>>>t1=[3,5,6,7]
>>>print(t1[2])
>>>print(t1[-1])
>>>print(t1[2:])
>>>print(t1[:])
OUTPUT
Output:
1. [2, 5, 2, 4, 9, 0, 7]
2. ['Hello', 'Good', 'python']
3. >>>6
>>>7
>>>[6, 7]
>>>[3, 5, 6, 7]
WRITE PYTHON CODE FOR FINDING
GREATEST AMONG FOUR NUMBERS
list1 = [ ]
num = int(input("Enter number of elements in list: "))
for i in range(1, num + 1):
element = int(input("Enter elements: "))
list1.append(element)
print("Largest element is:", max(list1))

#output:
Enter number of elements in list: 4
Enter elements: 3
Enter elements: 6
Enter elements: 7
Enter elements: 2
Largest element is: 7
Tuples
TUPLES
🞆 A tuple is a collection which is ordered and
unchangeable.
🞆 The difference between the two is that we
cannot change the elements of a tuple once
it is assigned whereas, in a list, elements can
be changed.
🞆 In Python tuples are written with round
brackets whereas List are written in Square
brackets.
CREATING A TUPLE
🞆 A tuple is created by placing all the items
(elements) inside parentheses (), separated by
commas.
🞆 A tuple can also be created without using
parentheses. This is known as tuple packing.
🞆 A tuple can have any number of items and they
may be of different types (integer, float, list,
string, etc.).
🞆 The empty tuple is written as two parentheses
containing nothing
Tuple1=()
🞆 To write a tuple containing a single value you have
to include a comma, even though there is only one
value Tuple1=(10,)
🞆 Example
tuple1=(10,20,30,40)
tuple2=50,60,70
tuple3=()
tuple4=(80,)
print(tuple1)
print(tuple2)
print(tuple3)
print(tuple4)
Output:
(10, 20, 30, 40)
(50, 60, 70)
()
(80,)
>>> vijay=(11,'vijay','thane')
>>> (id,name,city)=vijay
>>> id
11
>>> name
'vijay'
>>> city
'thane'
>>> launge=('python','java')
>>> launge
('python', 'java')
>>> (a,b)=launge
>>> a
'python'
>>> b
'java'
SWAPPING THE VALUES OF TWO VARIABLES
USING TUPLE ASSIGNMENT

>>> x=10
>>> y=20
>>> (x,y)
(10, 20)

>>> x,y=y,x
>>> (x,y)
(20, 10)
ACCESSING VALUES IN TUPLES

🞆 To access values in tuple, use the square


brackets for slicing along with the index or
indices to obtain value available at that
index.
🞆 There are various ways in which we can
access the elements of a tuple.
1. Indexing
2. Negative Indexing
3. Slicing
INDEXING

🞆 We can use the index operator [] to access an


item in a tuple where the index starts from 0.

🞆 So, a tuple having 6 elements will have indices


from 0 to 5. Trying to access an element
outside of tuple (for example, 6, 7,...) will raise
an IndexError.

🞆 The index must be an integer; so we cannot


use float or other types. This will result in
TypeError.
🞆 nested tuples are accessed using nested
indexing
EXAMPLE
tuple1 = ('p','e','r','m','i','t')
print(tuple1[0])
print(tuple1[5])
tuple2 = ("mouse", [8, 4, 6], (1, 2, 3))
print(tuple2[0][3])
print(tuple2[1][1])
#Output:
p
t
s
4
NEGATIVE INDEXING

🞆 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.

tuple1 = ('p','e','r','m','i','t')
print(tuple1[-1])
print(tuple1[-5])
Output:
t
e
SLICING

🞆 We can access a range of items in a tuple by using the


slicing operator - colon ":“
🞆 Example

my_tuple = ('p','r','o','g','r','a','m','i','z')
print(my_tuple[1:4])
print(my_tuple[:7])
print(my_tuple[7:])
print(my_tuple[:])

#Output
('r', 'o', 'g')
('p', 'r', 'o', 'g', 'r', 'a', 'm')
('i', 'z')
('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
UPDATING TUPLES

🞆 Tuples are immutable which means you cannot


update or change the values of tuple elements.
🞆 You are able to take portions of existing tuples to
create new tuples as the following example
demonstrates
tup1 = (12, 34.56);
tup2 = ('abc', 'xyz');
# Following action is not valid for tuples
# tup1[0] = 100;
# So let's create a new tuple as follows
tup3 = tup1 + tup2;
print tup3;
Output
(12, 34.56, 'abc', 'xyz')
DELETE TUPLE ELEMENTS

🞆 we cannot change the elements in a tuple.


That also means we cannot delete or remove
items from a tuple.
🞆 But deleting a tuple entirely is possible using
the keyword del
🞆 Example
my_tuple = ('p','r','o','g','r','a','m','i','z')
# TypeError: 'tuple' object doesn't support item
deletion
# del my_tuple[3]
# Can delete an entire tuple
del my_tuple
# NameError: name 'my_tuple' is not defined
print(my_tuple)
BASIC TUPLE OPERATION
1. concatenation and repetition:
🞆 Tuples respond to the + and * operators
much like strings; they mean concatenation
and repetition here too, except that the
result is a new tuple, not a string.
🞆 In fact, tuples respond to all of the general
sequence operations we used on strings in
the prior
>>> t1=(10,20)
>>> t2=(30,40)
>>> t1+t2
(10, 20, 30, 40)
>>> t1*2
(10, 20, 10, 20)
>>> t2*3
(30, 40, 30, 40, 30, 40)
Membership Function:
we can test if an item exists in tuple or
not,using the keyword ‘in’ .The in operator
evaluates to true if it finds a variable in the
specified sequence and false.

>>> t1=(10,20,30,40,'a')
>>> 'a' in t1
True
>>> 20 in t1
True
3. Iterating through a tuple:
Iteration over a tuple specifies the way which the loop can be applied to the tuple.
Using a for loop we can iterate through each item in a tuple.following example uses
a for loop to simply iterates over a tuple.

t1=(10,20,30,'a',40)
for i in t1:
print(i)
#output:
10
20
30
a
40

for x in (1,2,3):
print(x)
1
2
3
🞆 Example
🞆 Indexing, Slicing, and Matrixes
Because tuples are sequences, indexing and
slicing work the same way for tuples as they
do for strings. Assuming following input −
L=(‘spam’,’Spam’,’SPAM!’)
BUILT-IN TUPLE FUNCTIONS
Function Description
len(tuple1) Returns the length of a tuple
max(tuple1) Returns item from the tuple
with max value.
min(Tuple) Returns item from the tuple
with min value.
tuple(sequence) Converts a list into tuple.
Zip(tuple1,tuple2) Zip elements from two tuples into a
list of tuples
count() Returns the number of
occurrences of a given element
in the tuple.
index(x) Returns the index of the first item
that is equal to x
LEN()
🞆 Python tuple method len() returns the
number of elements in the tuple.
🞆 Syntax
len(tuple)

🞆 Example
tuple1=(10,20,30,"amit",50)
print("Length=",len(tuple1))
🞆 Output
Length= 5
MAX()
🞆 Python tuple method max() returns the elements from the
tuple with maximum value.
🞆 Syntax

max(tuple)
🞆 Example

tuple1=(10,20,30,80,50)
tuple2=("Tiger","Lion","Dog","Zebra","Cat")
tuple3=("Tiger","Lion","Dog","Zebra","Zfbra")
print("Max value in Tuple=",max(tuple1))
print("Max value in Tuple=",max(tuple2))
print("Max value in Tuple=",max(tuple3))
🞆 Output

Max value in Tuple= 80


Max value in Tuple= Zebra
Max value in Tuple= Zfbra
MIN()
🞆 Python tuple method min() returns the elements
from the tuple with minimum value.
🞆 Syntax
min(tuple)
🞆 Example
tuple1=(10,20,30,80,50)
tuple2=("Tiger","Lion","Dog","Zebra","Cat")
print("Min value in Tuple=",min(tuple1))
print("Min value in Tuple=",min(tuple2))
🞆 Output
Min value in Tuple= 10
Min value in Tuple= Cat
TUPLE()
🞆 Python tuple method tuple() converts a list
of items into tuples
🞆 Syntax
tuple( seq )
🞆 Example
List1=[10,20,30,80,50]
print("Tuple=",tuple(List1))
🞆 Output
Tuple= (10, 20, 30, 80, 50)
COUNT()
🞆 count() method searches the given element
in a tuple and returns how many times the
element has occurred in it.
🞆 Syntax
tuple.count(element)
🞆 Example
tuple1=(10,20,30,80,50,20,40,20,30,20)
print("count of 20 in
tuple=",tuple1.count(20))
🞆 Output
count of 20 in tuple= 4
INDEX()

🞆 The index() method searches an element in a


tuple and returns its index.
🞆 Syntax
tuple.index(element)
🞆 Example
tuple1=(10,20,30,80,50,20)
print("index of 20 in
tuple=",tuple1.index(20))
🞆 Output
index of 20 in tuple= 1
ZIP()
The zip() function returns a zip object, which is
an iterator of tuples where the first item in
each passed iterator is paired together, and
then the second item in each passed iterator
are paired together etc.
>>> tuple1=(10,20,30,80,50)
>>>
tuple2=("Tiger","Lion","Dog","Zebra","Cat")
>>> zip(tuple1,tuple2)
#output:
<zip object at 0x000001C3A7D732C0>
>>>tuple1=(10,20,30,80,50)
>>> tuple2=("Tiger","Lion","Dog","Zebra","Cat")
>>> res=zip(tuple1,tuple2)
>>> print(list(res))

#output:
[(10, 'Tiger'), (20, 'Lion'), (30, 'Dog'), (80, 'Zebra'), (50, 'Cat')]
a=[(10, 'Tiger'), (20, 'Lion'), (30, 'Dog'), (80, 'Zebra'), (50,
'Cat')]

tuple1, tuple2 = zip(*a)


>>> tuple1
(10, 20, 30, 80, 50)
>>> tuple2
('Tiger', 'Lion', 'Dog', 'Zebra', 'Cat')
ZIP( )

>>> tup1=(1,2,3)
>>> tup2=('A','B','C')
>>> tup3=zip(tup1,tup2)
>>> list(tup3)
[(1, 'A'), (2, 'B'), (3, 'C')]
DIFFERENCE BETWEEN LIST AND
TUPLE IN PYTHON:
Sr. No List Tuple

1 List is ordered and mutable data Tuple is ordered and immutable data
structure structure

2 List is represented with the square Tuple is represented with the round
brackets [ ] separated by commas.Ex. brackets () separated by commas.Ex.
List1=[1,2,3,4] T1=(1,2,3,4)

3 List can be changed or modified after Tuples cannot be changed or modified


creation. after creation.

4 List supports more built-in methods. Tuple supports less built-in methods.

5 List has a variable length. Tuple has a fixed length.


ADVANTAGES OF TUPLE OVER LIST

🞆 We generally use tuple for heterogeneous


(different) data types and list for
homogeneous (similar) data types.
🞆 Since tuples are immutable, iterating through
tuple is faster than with list. So there is a
slight performance boost.
🞆 Tuples that contain immutable elements can
be used as a key for a dictionary. With lists,
this is not possible.
🞆 If you have data that doesn't change,
implementing it as tuple will guarantee that
it remains write-protected.
SET
SET
🞆 A set is a collection which is unordered and
un indexed.
🞆 Every element is unique (no duplicates) .
🞆 In Python sets are written with curly
brackets.
🞆 Sets can be used to perform mathematical
set operations like union, intersection,
symmetric difference etc.
🞆 Syntax:
🞆 <set_value>={value1,value2,---valueN}
🞆 Ex:
🞆 Emp={20,”Amar”,’M’,50}
CREATING A SET
🞆 A set is created by placing all the items
(elements) inside curly braces {}, separated
by comma by using the built-in function set().
🞆 It can have any number of items and they
may be of different types (integer, float,
tuple, string etc.).
set1={10,20,30,40,20}
set2={50,60,"hello",(10,20,30)}
set3={}
set4= set(set1)
print(set1)
print(set2)
print(set3)
print(set4)
Output:
{40, 10, 20, 30}
{'hello', 50, (10, 20, 30), 60}
{}
{40, 10, 20, 30}
Aset does not contain any duplicate values or elements.
>>> a={1,3,5,4,2}
>>> print("a=",a)
a= {1, 2, 3, 4, 5}
>>> colors={'red','green','blue','red'}
>>> colors
{'red', 'blue', 'green'}

#set can be created by calling a type constructor called set()

>>> s=set('abc')
>>> s
{'c', 'b', 'a'}
>>> s=set(range(1,3))
>>> s
{1, 2}
ACCESSING VALUES IN SET
🞆 You cannot access items in a set by referring
to an index, since sets are unordered the
items has no index.
🞆 But you can use loop to access the elements
or ask if a specified value is present in a set,
by using the ‘in’ keyword.
EXAMPLE
set1={10,20,30,40}
for x in set1:
print(x)
print("wheather 20 is present or not",20 in
set1)
Output:
40
10
20
30
wheather 20 is present or not True
s1={'A','B','C','D'}
for val in s1:
print(val)
#output:
D
A
B
C
HOW TO CHANGE A SET IN PYTHON OR
UPDATE A SET ?

🞆 Sets are mutable. But since they are


unordered, indexing have no meaning.
🞆 We cannot access or change an element of
set using indexing or slicing. Set does not
support it.
🞆 We can add single element using the add()
method and multiple elements using the
update() method. The update() method can
take tuples, lists, strings or other sets as its
argument. In all cases, duplicates are
avoided.
UPDATING SET
we can update a set by using add() or update()
method.

Syntax:
A.add(element)

set1={10,20,30,40}
set1.add(50)
print(set1)

{40, 10, 50, 20, 30}

>>> a={1,2,3,4}
>>> a.add(6)
>>> a
{1, 2, 3, 4, 6}
Syntax:
A.update(B)
where B can be lists/strings/tuples/sets

set1={10,20,30,40}
set1.update([40,70,80],{90,60,20})
print(set1)
Output
{70, 40, 10, 80, 50, 20, 90, 60, 30}
>>> a={1,2,3}
>>> b={'a','b','c'}
>>> a
{1, 2, 3}
>>> b
{'c', 'b', 'a'}
>>> a.update(b)
>>> a
{1, 2, 3, 'a', 'c', 'b'}
>>> a.update({3,4})
>>> a
{1, 2, 3, 4, 'a', 'c', 'b'}
HOW TO REMOVE ELEMENTS FROM A SET?

🞆 A particular item can be removed from set


using methods, discard() and remove().
🞆 The only difference between the two is that,
while using discard() if the item does not exist
in the set, it remains unchanged. But remove()
will raise an error in such condition.
🞆 Similarly, we can remove and return an item
using the pop() method-Set being unordered,
there is no way of determining which item will
be popped. It is completely arbitrary.
🞆 We can also remove all items from a set using
clear().
EXAMPLE
set1={10,20,30,40,80}
set1.discard(30)
print(set1) {40, 10, 80, 20}
set1.remove(40)
print(set1) {10, 80, 20}
set1.pop()
print(set1) {80, 20}

set1.clear()
print(set1) set()
>>> b={'a','b','c'}
>>> b
{'c', 'b', 'a'}
>>> b.discard('b')
>>> b
{'c', 'a'}
>>> b.remove('a')
>>> b
{'c'}
>>> b={'a','b','c'}
>>> b.pop()
'c'
>>> b.pop()
'b'

>>> b={'a','b','c'}
>>> b.clear()
>>> b
set()
BASIC SET OPERATION
🞆 Sets can be used to carry out mathematical
set operations like union, intersection,
difference and symmetric difference
🞆 Set operations are as Follow
Set Union
Set Intersection
Set Difference
Set Symmetric Difference
SET UNION

🞆 Union of A and B is a set of all elements from


both sets.
🞆 Union is performed using | operator.
🞆 Syntax
Set1|Set2
🞆 The union() method returns a new set
containing all items from both sets.
🞆 Syntax
set1.union(set2)
🞆 Let us consider the following two sets for the
following operations.
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
union of Set A and Set B is
A|B={1, 2, 3, 4, 5, 6, 7, 8}
EXAMPLE
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
C= {9,11,10,3}
print(A | B)
print(C.union(A))
output:
{1, 2, 3, 4, 5, 6, 7, 8}
{1, 2, 3, 4, 5, 9, 10, 11}
SET INTERSECTION

🞆 Intersection of A and B is a set of elements


that are common in both sets.
🞆 Intersection is performed using & operator.
🞆 Syntax
Set A & Set B
🞆 The intersection() method returns a set that
contains the similarity between two or more
sets
🞆 Syntax
set.intersection(set1, set2 ... etc)
🞆 Let us consider the following two sets for the
following operations.
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
Intersection of of Set A and Set B is
A & B={4, 5}
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
C= {3,5,8,9}
print(A & B)
print(C.intersection(A))
Output
{4, 5}
{3, 5}
SET DIFFERENCE

🞆 Difference of A and B (A - B) is a set of


elements that are only in A but not in B.
Similarly, B - A is a set of element in B but
not in A.
🞆 Difference is performed using - operator.
🞆 Syntax
Set A - Set B or Set B-Set A

🞆 The difference() method returns a set that


contains the difference between two sets.
set.difference(set)
🞆 Let us consider the following two sets for the
following operations.
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
Difference of Set A and Set B is
A - B={1,2,3}
B – A={6,7,8}
EXAMPLE
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
C= {3,5,8,9}
print(A - B)
print(B - A)
print(C.difference(A))
OUTPUT:
{1, 2, 3}
{8, 6, 7}
{8, 9}
SET SYMMETRIC DIFFERENCE

🞆 Symmetric Difference of A and B is a set of


elements in both A and B except those that
are common in both.
🞆 Symmetric difference is performed using ^
operator.
🞆 Syntax
Set A ^ Set B
🞆 Same can be accomplished using the method
symmetric_difference().
🞆 Syntax
set.symmetric_difference(set)
🞆 Let us consider the following two sets for the
following operations.
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
Symmetric Difference of of Set A and Set B is
A ^ B={1,2,3,6,7,8}
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
C= {3,5,8,9}
print(A ^ B)
print(C.symmetric_difference(A))
Output:
{1, 2, 3, 6, 7, 8}
{1, 2, 4, 8, 9}
BUITL IN SET FUNCTION
ADD() METHOD
🞆 The add() method adds an element to the
set.
🞆 If the element already exists, the add()
method does not add the element.
🞆 Syntax
set.add(elmnt)
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
A.add(6)
print(A)
B.add(6)
print(B)

Output
{1, 2, 3, 4, 5, 6}
{4, 5, 6, 7, 8}
CLEAR()
🞆 The clear() method removes all elements in a
set.
🞆 Syntax
🞆 set.clear()
🞆 Example
A = {1, 2, 3, 4, 5}
A.clear()
print(A)
output
Set()
COPY()
🞆 The copy() method copies the set.
🞆 Syntax
🞆 set.copy()
🞆 Example
A = {1, 2, 3, 4, 5}
B=A.copy()
print(B)

🞆 Output
{1, 2, 3, 4, 5}
DIFFERENCE_UPDATE()

🞆 The difference_update() method removes the


items that exist in both sets.
🞆 The difference_update() method is different
from the difference() method, because the
difference() method returns a new set,
without the unwanted items, and the
difference_update() method removes the
unwanted items from the original set.
🞆 Syntax
set.difference_update(set)
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
A.difference_update(B)
print(A)

OUTPUT
{1, 2, 3}
INTERSECTION_UPDATE()
🞆 The intersection_update() method removes
the items that is not present in both sets (or
in all sets if the comparison is done between
more than two sets).
🞆 The intersection_update() method is different
from the intersection() method, because the
intersection() method returns a new set,
without the unwanted items, and the
intersection_update() method removes the
unwanted items from the original set.
🞆 Syntax
🞆 set.intersection_update(set1, set2 ... etc)
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
A.intersection_update(B)
print(A)

OUTPUT
{4, 5}
ISDISJOINT()

🞆 The isdisjoint() method returns True if none of


the items are present in both sets, otherwise it
returns False.
🞆 Syntax
set.isdisjoint(set)
🞆 Example
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
C=A.isdisjoint(B)
print(C)
Output
False
ISSUBSET()

🞆 The issubset() method returns True if all items


in the set exists in the specified set, otherwise
it returns False.
🞆 Syntax
set.issubset(set)
🞆 Example
A = {4, 5}
B = {4, 5,6,7,8}
C=A.issubset(B)
print(C)
Output
True
ISSUPERSET()

🞆 The issuperset() method returns True if all items in


the specified set exists in the original set,
otherwise it returns False.
🞆 Syntax

set.issuperset(set)
🞆 Example

A = {4, 5,3}
B = {4, 5,6,7,8}
C=A.issuperset(B)
print(C)

🞆 Output
False
SYMMETRIC_DIFFERENCE_UPDATE()

🞆 The symmetric_difference_update() method


updates the original set by removing items that
are present in both sets, and inserting the other
items.
🞆 Syntax

🞆 set.symmetric_difference_update(set)

🞆 Example

A = {3,4, 5}
B = {4, 5,6,7,8}
A.symmetric_difference_update(B)
print(A)
Output
{3, 6, 7, 8}
Write python program to perform following
operations on Set (Instead of
Tuple)-06Marks
i) Create set
ii) Access set Element
iii) Update set
iv) Delete set
# To Create set
S={10,20,30,40,50}
# To Access Elements from set
print (S)
#To add element into set using add method
S.add(60)
print(S)
#To update set using update method
S.update(['A','B'])
print(S)
#To Delete element from Set using discard()
method
S.discard(30)
print(S)
#To delete element from set using remove()
method
S.remove('A')
print(S)
#To delete element from set using pop()
method
S.pop()
print(S)
output:
{50, 20, 40, 10, 30}
{50, 20, 40, 10, 60, 30}
{'B', 50, 20, 'A', 40, 10, 60, 30}
{'B', 50, 20, 'A', 40, 10, 60}
{'B', 50, 20, 40, 10, 60}
{50, 20, 40, 10, 60}
USING TUPLES
🞆 #To create tuple
🞆 tuple1=(10,20,30,40,50)
🞆 print (tuple1)
🞆 #Access tuple values
🞆 print (tuple1[1])
🞆 print (tuple1[0:3])
🞆 # deleting tuple
🞆 del tuple1
🞆 print (tuple1)
output:
(10, 20, 30, 40, 50)
20
(10, 20, 30)
Traceback (most recent call last):
File "C:\Users\Vijay Patil\AppData\Local\
Programs\Python\Python310\temp.py", line
9, in <module>
print (tuple1)
NameError: name 'tuple1' is not defined. Did
you mean: 'tuple'?
Dictionary
DICTIONARY

🞆 Python dictionary is an unordered collection


of items. While other compound data types
have only value as an element, a dictionary
has a key: value pair.
🞆 A dictionary is a collection which is
unordered, changeable and indexed.
🞆 In Python dictionaries are written with curly
brackets, and they have keys and values.
HOW TO CREATE A DICTIONARY?

🞆 Creating a dictionary is as simple as placing items


inside curly braces {} separated by comma.
🞆 An item has a key and the corresponding value
expressed as a pair, key: value.
🞆 While values can be of any data type and can repeat,
keys must be of immutable type (string, number or
tuple with immutable elements) and must be unique.
🞆 Each key is separated from its value by a colon (:),
the items are separated by commas, and the whole
thing is enclosed in curly braces.
🞆 An empty dictionary without any items is written with
just two curly braces, like this: {}.
🞆 we can also create a dictionary using the built-in
function dict()
EXAMPLE
# empty dictionary
my_dict = { }
# dictionary with integer
keys
my_dict = {1: 'apple', 2: 'ball'}
# dictionary with mixed
keys
my_dict = {'name': 'John', 1: [2, 4, 3]}
# using dict()
my_dict = dict({1:'apple', 2:'ball'})
# sequence having each item as a
pair
my_dict = dict([(1,'apple'), (2,'ball')])
ACCESSING VALUES IN DICTIONARY

🞆 To access dictionary elements, you can use


the square brackets along with the key to
obtain its value.
🞆 While indexing is used with other container
types to access values, dictionary uses keys.
Key can be used either inside square
brackets or with the get() method.
🞆 The difference while using get() is that it
returns None instead of KeyError, if the key is
not found.
Dict1={1:20,2:'Amit',3:20.54}
print(Dict1[2])
print(Dict1.get(3))
print(Dict1[4])

#Output:
Amit
20.54
Traceback (most recent call last):
File "E:/prg/Dict.py", line 4, in <module>
print(Dict1[4])
KeyError: 4
UPDATING DICTIONARY

🞆 You can update a dictionary by adding a new


entry or a key-value pair, modifying an
existing entry, or deleting an existing entry
HOW TO CHANGE OR ADD ELEMENTS IN A
DICTIONARY?

🞆 Dictionary are mutable. We can add new


items or change the value of existing items
using assignment operator.
🞆 If the key is already present, value gets
updated, else a new key: value pair is added
to the dictionary.
🞆 Example
Dict1={1:20,2:'Amit',3:20.54}
Dict1[2]='Rohan'
print(Dict1)
Dict1[4]='Amol'
print(Dict1)

#Output
{1: 20, 2: 'Rohan', 3: 20.54}
{1: 20, 2: 'Rohan', 3: 20.54, 4: 'Amol'}
HOW TO DELETE OR REMOVE ELEMENTS
FROM A DICTIONARY?

🞆 We can remove a particular item in a


dictionary by using the method pop(). This
method removes as item with the provided
key and returns the value.
🞆 The method, popitem() can be used to
remove and return an arbitrary item (key,
value) form the dictionary. All the items can
be removed at once using the clear()
method.
🞆 We can also use the del keyword to remove
individual items or the entire dictionary itself.
EXAMPLE
Dict1={1:20,2:'Amit',3:20.54,4:'Amol',5:60}
Dict1.pop(3)
print(Dict1)
Dict1.popitem()
print(Dict1)
del Dict1[1]
print(Dict1)
Dict1.clear()
print(Dict1)
Output
{1: 20, 2: 'Amit', 4: 'Amol', 5: 60}
{1: 20, 2: 'Amit', 4: 'Amol'}
{2: 'Amit', 4: 'Amol'}
{}
PROPERTIES OF DICTIONARY KEYS

🞆 Dictionary values have no restrictions. They can


be any arbitrary Python object, either standard
objects or user-defined objects
🞆 There are two important points to remember
about dictionary keys −
🞆 (a) More than one entry per key not allowed.
Which means no duplicate key is allowed. When
duplicate keys encountered during assignment,
the last assignment wins.
Dict1={1:20,2:'Amit',3:20.54,4:'Amol',1:60}
print(Dict1[1])
Output
60
🞆 (b) Keys must be immutable. Which means you
can use strings, numbers or tuples as dictionary
keys but something like ['key'] is not allowed.
🞆 Example
Dict1={1:20,[2]:'Amit',3:20.54,4:'Amol',1:60}
print(Dict1)
Output
Traceback (most recent call last):
File "E:/prg/Dict.py", line 1, in <module>
Dict1={1:20,[2]:'Amit',3:20.54,4:'Amol',1:60}
TypeError: unhashable type: 'list'
>>>
BASIC DICTIONARY OPERATIONS

1.Traversing OR Iterating Through a


Dictionary
2. Dictionary Membership Test
1.TRAVERSING OR ITERATING THROUGH A
DICTIONARY

🞆 Using a for loop we can iterate though each


key in a dictionary.
🞆 Example
Dict1={1:20,2:'Amit',3:20.54,4:'Amol'}
for i in Dict1:
print(Dict1[i])
🞆 Output
20
Amit
20.54
Amol
2. Dictionary Membership Test
🞆 We can test if a key is in a dictionary or not
using the keyword in. Notice that membership
test is for keys only, not for values.
🞆 Example
Dict1={1:20,2:'Amit',3:20.54,4:'Amol'}
print(2 in Dict1)
print(6 in Dict1)
🞆 Output
True
False
BUILT IN DICTIONARY FUNCTION
CLEAR()
🞆 The clear() method removes all the elements
from a dictionary.
🞆 Syntax
dictionary.clear()
🞆 Example
Dict1={1:20,2:'Amit',3:20.54,4:'Amol'}
Dict1.clear()
print(Dict1)
🞆 Output
{}
COPY()
🞆 The copy() method returns a copy of the
specified dictionary.
🞆 Syntax
dictionary.copy()
🞆 Example
Dict1={1:20,2:'Amit',3:20.54,4:'Amol'}
Dict2=Dict1.copy()
print(Dict2)
🞆 Output
{1: 20, 2: 'Amit', 3: 20.54, 4: 'Amol'}
FROMKEYS()
🞆 The fromkeys() method returns a dictionary
with the specified keys and values.
🞆 Syntax
dict.fromkeys(keys, value)
🞆 Example
key =(1,2,3,4)
value=20
Dict2=dict.fromkeys(key,value)
print(Dict2)
🞆 Output
{1: 20, 2: 20, 3: 20, 4: 20}
GET()

🞆 The get() method returns the value of the


item with the specified key.
🞆 Syntax
dict.get(key[, value])
The get() method takes maximum of two
parameters:
key - key to be searched in the dictionary
value (optional) - Value to be returned if the
key is not found. The default value is None.
EXAMPLE
Dict1={1:20,'Name':'Amit',3:20.54,4:'Amol'}
print(Dict1.get('Name'))
print(Dict1.get(5))
print(Dict1.get(5,40))

Output
Amit
None
40
ITEMS()

🞆 The items() method returns a view object.


The view object contains the key-value pairs
of the dictionary, as tuples in a list.
🞆 The view object will reflect any changes done
to the dictionary,
🞆 Syntax
🞆 dictionary.items()
🞆 Example
Dict1={1:20,2:'Amit',3:20.54,4:'Amol'}
print(Dict1.items())
Dict1[2]='Amar'
print(Dict1.items())
🞆 Output
dict_items([(1, 20), (2, 'Amit'), (3, 20.54), (4,
'Amol')])
dict_items([(1, 20), (2, 'Amar'), (3, 20.54), (4,
'Amol')])
KEYS()

🞆 The keys() method returns a view object. The


view object contains the keys of the
dictionary, as a list.
🞆 The view object will reflect any changes done
to the dictionary,
🞆 Syntax
dictionary.keys()
Dict1={1:20,2:'Amit',3:20.54,4:'Amol'}
print(Dict1.keys())
Dict1[5]='Amar'
print(Dict1.keys())

Output
dict_keys([1, 2, 3, 4])
dict_keys([1, 2, 3, 4, 5])
POP()
🞆 The pop() method removes the specified item
from the dictionary.
🞆 The value of the removed item is the return
value of the pop() method,
🞆 Syntax
dictionary.pop(keyname, defaultvalue)
Dict1={1:20,2:'Amit',3:20.54,4:'Amol'}
Dict1.pop(2)
print(Dict1)
element=Dict1.pop(5,'Amar')
print(element)
Dict1.pop(6)
print(Dict1)
Output
{1: 20, 3: 20.54, 4: 'Amol'}
Amar
Traceback (most recent call last):
File "E:\prg\Dict.py", line 6, in <module>
Dict1.pop(6)
KeyError: 6
POPITEM()
🞆 The popitem() method removes the item that was last
inserted into the dictionary. In versions before 3.7, the
popitem() method removes a random item.
🞆 The removed item is the return value of the popitem()
method, as a tuple
🞆 Syntax

dictionary.popitem()
🞆 Example

Dict1={1:20,2:'Amit',3:20.54,4:'Amol'}
element=Dict1.popitem()
print(element)

🞆 Output
(4, 'Amol')
SETDEFAULT()
🞆 The setdefault() method returns the value of
a key (if the key is in dictionary). If not, it
inserts key with a value to the dictionary.
🞆 Syntax
dictionary.setdefault(keyname, default_value)
🞆 The setdefault() takes maximum of two
parameters:
key - key to be searched in the dictionary
default_value (optional) - key with a value
default_value is inserted to the dictionary if key
is not in the dictionary.
If not provided, the default_value will be None.
Dict1={1:20,2:'Amit',3:20.54,4:'Amol'}
print(Dict1.setdefault(2))
element=Dict1.setdefault(5,'Amar')
print(element)
print(Dict1)
Output
Amit
Amar
{1: 20, 2: 'Amit', 3: 20.54, 4: 'Amol', 5: 'Amar'}
UPDATE()
🞆 The update() method adds element(s) to the
dictionary if the key is not in the dictionary. If
the key is in the dictionary, it updates the
key with the new value.
🞆 Syntax
dictionary.update(iterable)
Dict1={1:20,2:'Amit',3:20.54,4:'Amol'}
Dict2={2:50}
Dict1.update(Dict2)
print(Dict1)
Dict3={5:90}
Dict1.update(Dict3)
print(Dict1)
🞆 Output
{1: 20, 2: 50, 3: 20.54, 4: 'Amol'}
{1: 20, 2: 50, 3: 20.54, 4: 'Amol', 5: 90}
VALUES()

🞆 The values() method returns a view object. The


view object contains the values of the dictionary,
as a list.
🞆 The view object will reflect any changes done to
the dictionary
🞆 Syntax
dictionary.values()

🞆 Example
Dict1={1:20,2:'Amit',3:20.54,4:'Amol'}
print(Dict1.values())
Output
dict_values([20, 'Amit', 20.54, 'Amol'])
COMPARE LIST AND DICTIONARY
🞆 Write a program to create dictionary of
student the includes their ROLL NO and
NAME
🞆 i) Add three students in above dictionary
🞆 ii) Update name=’Shreyas’ of ROLL NO=2
🞆 iii) Delete information of ROLL NO=1
1)
>>> dict1={1:"Vijay",2:"Santosh",3:"Yogita"}
>>>print(dict1)
{1: 'Vijay', 2: 'Santosh', 3: 'Yogita'}
ii)
>>>dict1[2]="Shreyas"
>>>print(dict1)
{1: 'Vijay', 2: 'Shreyas', 3: 'Yogita'}
iii)
>>>dict1.pop(1)
‘Vijay'
>>>print(dict1)
{2: 'Shreyas', 3: 'Yogita'}
End

You might also like