You are on page 1of 84

UNIT-III

DATA STRUCTURES IN PYTHON


14 M
WHAT IS A DATA STRUCTURE?
 Data structures are a way of organizing and storing data
so that they can be accessed and worked with
efficiently.
 They define the relationship between the data, and the
operations that can be performed on the data
 Built in Data structures:
 List,
 Dictionary,
 Tuple
 Set.
LISTS [ ]:
 A list is defined as an ordered collection of items, and it is one
of the essential data structures .
 The term “ordered collections” means that each item in a list
comes with an order that uniquely identifies them.
 Lists are used to store data of different data types in a
sequential manner.
 There are addresses assigned to every element of the list,
which is called as Index.
 The index value starts from 0 and ends with n-1,if list contains
n items.
LISTS:
 Characteristics of Lists
 The lists are ordered.
 The element of the list can access by index.
 The lists are the mutable type.
 A list can store the number of various elements.

 Defining List:
 All the items in the list should be put in square brackets
[ ]and separated by commas.
 Syntax for defining list:
 list_name=[value1,value2,....value n]
 Here, list name is the name of list and value1...value n are the
values assigned to list.
CREATING A LIST
 # empty list
my_list = [ ]
 # list of integers
my_list = [1, 2, 3]
 # list with mixed datatypes
my_list = [1, "Hello", 3.4]
 Also, a list can even have another list as an item. This
is called nested list.
 # nested list
my_list = ["mouse", [8, 4, 6], ['a']]
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:
 List1=[‘physics’, ‘chemistry’, 1997, 2000]
 List2=[1,2,3,4,5]

 print( “List1[0] :”, List1[0])


 print (“List2[1:5] :”, List2[1:5])

 Output of the above code is


 List1[0] : physics
 List2[1:5] : [2,3,4,5]
ACCESSING VALUES IN LIST
 # Nested List
n_list = ["Happy", [2,0,1,5]]
 # Nested indexing

# Output: a
 print(n_list[0][1])

# Output: 5
 print(n_list[1][3])

 Negative indexing
my_list = ['p','r','o','b','e']
# Output: e
print(my_list[-1])

# Output: p
DELETING VALUES IN LIST:
 There are many ways to delete elements from list.
1. pop()method,
2. del keyword,
3. remove() method
4. clear() method
 We can use remove() method to remove a particular element
from the list.
 pop() method to remove an item at the given index. The pop()
method removes and returns the last item if index is not
provided. This helps us implement lists as stacks (first in, last
out data structure).
 We can also use the clear() method to empty a list.

 We can delete one or more items from list using del keyword. It
can even delete the list entirely.
EXAMPLE: DELETING VALUES IN LIST
my_list = ['p','r','o','b','l','e','m']
# delete one item
del my_list[2]
# Output: ['p', 'r', 'b', 'l', 'e', 'm']
print(my_list)

# delete multiple items


del my_list[1:5]
# Output: ['p', 'm']
print(my_list)

# delete entire list


del my_list
# Error: List not defined
print(my_list)
EXAMPLE: DELETING VALUES IN LIST
my_list = ['p','r','o','b','l','e','m']

my_list.remove('p')
# Output: ['r', 'o', 'b', 'l', 'e', 'm']
print(my_list)

print(my_list.pop(1))
# Output: ‘o'

print(my_list)
# Output: ['r', 'b', 'l', 'e', 'm']

print(my_list.pop())
# Output: 'm'

print(my_list)
# Output: ['r', 'b', 'l', 'e']

my_list.clear()
# Output: [ ]
UPDATE OR ADD ELEMENTS TO A LIST:
 List are mutable, meaning, their elements can be changed unlike
string or tuple.
 We can use assignment operator (=) to change an item or a
range of items.
 # mistake values
 odd = [2, 4, 6, 8]
 # change the 1st item
 odd[0] =1
 # Output: [1, 4, 6, 8]
 print(odd)

 # change 2nd to 4th items


 odd[1:4] = [3, 5, 7]
 # Output: [1, 3, 5, 7]
 print(odd)
UPDATE OR ADD ELEMENTS TO A LIST:
 We can add one item to a list using append() method or add several items using extend() method
at last index.
 we can insert one item at a desired location by using the method insert() or insert multiple items
by squeezing it into an empty slice of a list.
odd = [1, 3, 5]
odd.append(7)
# Output: [1, 3, 5, 7]
print(odd)

odd.extend([9, 11, 13])


# Output: [1, 3, 5, 7, 9, 11, 13]
print(odd)

odd = [1, 9]
odd.insert(1,3)
# Output: [1, 3, 9]
print(odd)

odd[2:2] = [5, 7]
# Output: [1, 3, 5, 7, 9]
UPDATE OR ADD ELEMENTS TO A LIST:
 We can also use + operator to combine two lists. This is also called concatenation.
 The * operator repeats a list for the given number of times.

 sort() method is used to sort elements in ascending or descending order.

 By default Sort method sort list in Ascending order

thislist = [5,2,11,4]
thislist.sort()
print(thislist)
OUTPUT: [2,4,5,11]

To sort list in Descending order we need to mention sort(reverse=True)

thislist = [5,2,11,4]
thislist.sort(reverse=True)
print(thislist)
OUTPUT: [11, 5, 4, 2]

odd = [1, 3, 5]
# Output: [1, 3, 5, 9, 7, 5]
print(odd + [9, 7, 5])

#Output: ["re", "re", "re"]


print(["re"] * 3)
BASIC LIST OPERATIONS
Lists respond to the + and * operators much like strings..
BASIC LIST OPERATIONS -INDEXING, SLICING
 Indexing:
 An individual item in the list can be referenced by using index.
 Positive indexing: List elements can also be accessed using a Positive
index, which counts from 0 to n-1.
 Negative Indexing: List elements can also be accessed using a negative list
index, which counts from the end of the list.
 Example:
>>>list1=[10,20,30,40,50]
>>>list1[0]
10

>>>list1[3:]
[40,50]

>>>list1[-1]
50
BASIC LIST OPERATIONS -INDEXING,
SLICING
 Slicing:
 Itis an operation to extract elements from the list, it is used to
form subset.
 Syntax:
 List_var[start_index:end_index]
 Example:
>>>list1[1:4]
[20,30,40]
BUILT-IN LIST FUNCTIONS AND METHODS-
LIST METHODS
 append():Adds an element at the end of the list

 clear():Removes all the elements from the list

 copy():Returns a copy of the list

 count():Returns the number of elements with the specified value

 extend():Add the elements of a list, to the end of the current list

 index():Returns the index of the first element with the specified value

 insert():Adds an element at the specified position

 pop():Removes the element at the specified position

 remove():Removes the item with the specified value

 reverse():Reverses the order of the list

 sort():Sorts the list


1. list.append():adds an element to the list.
LIST METHODS WITH EXAMPLE

Here is an example:
a = [1, 2]
b = [6, 7, 8]
a.append(3)
a.append(b)
print(a)
# this will return:
# [1, 2, 3, [6, 7, 8]]

2. list.extend():append() will simply ‘tack’ on whatever value passed in. However, to


properly add integrate one list into another, we should use extend().
 Note that this will only work with iterable values and not single values.

Here is an example:
a = [1, 2]
b = [6, 7, 8]
a.extend(b)
print(a)
# this will return:
# [1, 2, 6, 7, 8]
LIST METHODS WITH EXAMPLE
3. list.clear(): clear() will remove all items from the list in
Python.
Here is an example:
a = [1, 2]
a.clear()
# this will return
#[]
4. list.copy():copy() will create a copy of a list in Python.
Here is an example:
a = [1, 2]
b = a.copy()
print(b)
# this will return
# [1, 2]
LIST METHODS WITH EXAMPLE
5. list.count(): count() will count the number of times a value
appears in a list.
Here is an example:
MyList= [‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘W’, ‘o’, ‘r’, ‘l’, ‘d’]
countme = MyList.count(‘l’)
print(countme)
# this will return
#3
6. list.index(): index() will find the index position of a value in a
list. Lists start their index at 0. It is also good to note that it will
stop at the first instance of the matched value. For example:
message = [‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘W’, ‘o’, ‘r’, ‘l’, ‘d’]
indexme = message.index(‘l’)
print(indexme)
# this will return
#2
LIST METHODS WITH EXAMPLE
7. list.remove()
 We can remove a specific item from the list by using remove().
Note that, similar to index(), it will only remove the first instance
of the matched value. To remove all matched values, we will need
to put them through a loop. For example:
letters = [‘a’, ‘b’, ‘f’, ‘c’, ‘f’]
letters.remove(‘f’)
print(letters)
# this will return
# [‘a’, ‘b’, ‘c’, ‘f’]
 Here’s an example of a loop to remove all values inside a list. We
pair this with range() to know how many times it appears.
letters = [‘a’, ‘b’, ‘f’, ‘c’, ‘f’]
for item in range(letters.count(‘f’))
letters.remove(‘f’)
LIST METHODS WITH EXAMPLE
8. list.pop()
 pop() will eject the last item from the array. For example:

letters = [‘a’, ‘b’, ‘f’, ‘c’, ‘f’]


letters.pop()
print(letters)
# this will return:
# [‘a’, ‘b’, ‘f’, ‘c’]
If we try to pop an empty array, we will get an IndexError
9. list.reverse()
 reverse() will do as it says reverses the list. For example:

letters = [‘a’, ‘b’, ‘f’, ‘c’, ‘f’]


letters.reverse()
print(letters)
# this will return
# [‘f’, ‘c’, ‘f’, ‘b’, ‘a’]
LIST METHODS WITH EXAMPLE
10.list.sort()
 sort() will rearrange your list to ascending order. It’s good to
note that character order is based on the ASCII table.
 sortme = [‘c’,’a’,’d’,’b’]
sortme.sort()
print(sortme)
 # this will return:
[‘a’, ‘b’, ‘c’, ‘d’]
11. list.insert():Use insert() if we want to add a value into a
specific position inside our list rather than append it at the end.
For example:
message = [‘H’, ‘l’, ‘l’, ‘o’, ‘W’, ‘o’, ‘r’, ‘l’, ‘d’]
message.insert(1, ‘e’)
print(message)
# this will return
PROGRAM ON LIST
#sum of element of list #reverse list
 list1=[1,2,3,4,5,6]  list1.reverse()
 a=sum(list1)  print(list1)
 print(a)

#Multiplication of list elements #find common element from list


 mul=1  list2=[2,3,8,9,6]
 for i in range(0,len(list1)):
 list3=[]
 mul=mul*list1[i]
 for x in list1:
 print(mul)
 if x in list2:
#maximum number of list  list3.append(x)
 list1=[1,2,3,4,5,6]

 c=max(list1)

 print(c)
 print("common elements:",list3)

#minimum number of list #find even numbers from list


 for e in list2:
 list1=[1,2,3,4,5,6]
 d=min(list1)
 if(e%2==0):
 print(d)  print(e,end=" ")
TUPLES ( ):
 Python Tuple is used to store the sequence of immutable
Python objects. The tuple is similar to lists since the value of
the items stored in the list can be changed, whereas the tuple is
immutable, and the value of the items stored in the tuple
cannot be changed.
 Tuples uses parenthesis to enclose items and items separated
with commas.
 Syntax:

tuple_name=(value1,valu2....value n)
CREATING TUPLE
 For example
Tup1=(‘physics’,’chemistry’,’1997,2000)
Tup2=(1,2,3,4,5)
 Python often recognizes that a tuple is intended even if the
parentheses are missing:
Tup3=‘a’, ‘b’, ‘c’, ‘d’
 For completeness, 0- and 1-element tuples can be defined,
but have special syntax:
a = ( ) # 0-tuple (empty tuple)
b = (item,) # 1-tuple (note the trailing comma)
c = item, # 1-tuple (note the trailing comma)
e.g tup1=(50,)
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.
 One can access the elements of a tuple in multiple ways, such
as indexing, negative indexing, range, etc.
 For example –

tup1=(‘physics’, ‘chemistry’, 1997, 2000)


tup2=(1,2,3,4,5)
print( “tup1[0] :”, tup1[0])
print(“tup2[1:5] :”, tup2[1:5])
Output of the above code is
tup1[0] : physics
tup2[1:5] : [2,3,4,5]
UPDATING TUPLES-
 Tuples are permanent which implies you can’t refresh or change
the estimations of tuple components .
 You can take parts of existing tuples to make new tuples

tup1=(12, 34.56)
tup2=(‘abc’,’xyz’)
# following action is not valid for tuples
tup1[0]=100

# to create new tuple


tup3=tup1+tup2
print(tup3)
Output of the above code is
(12, 34.56, ‘abc’, ‘xyz’)
DELETING VALUES IN TUPLES
 Tuples are unchangeable so we cannot remove items from it, but
we can delete the tuple completely.
 To explicitly remove an entire tuple, just use the del statement.

 Example:

tup1=(12, 34.56)
print(tup1)
del tup1
print(“After deleting tup1”)
print(tup1)
Output: Traceback (most recent call last):
File "F:\2019-2020\PYTH prog\tup_ex.py", line 2, in print(tup1)
NameError: name 'tup1' is not
BASIC TUPLES OPERATIONS
 Indexing in Tuples: Indexing in tuples is also pretty similar to
that in lists, the first element has index zero, and it keeps on
increasing for the next consecutive elements.
 Also, backward indexing is also valid in tuples, i.e., the last
element can be accessed using the index -1 and the consecutive
previous numbers by -2, -3 and so on. Let's take an example,
>>> example = ("apple", "orange", "banana", "berry", "mango" )
>>> print (example[0]);
 Output:

‘apple’
BASIC TUPLES OPERATIONS
 Slicing Tuple:
As tuples are immutable, we can take slices of one tuple
and place them in another tuple.

>>> t = (1, 2, 3, 4)
>>> print(t[2:4])
(3,4)
 Here, t[2:4] means, slice the tuple starting from
index 2 upto the index 4, and take that slice out.
 Slicing can be done backwards as well using the negative
indexes for traversing the tuple from backward direction.
BASIC TUPLES OPERATIONS
 Concatenation Operation :Concatenation simply
means linking things together. We can concatenate tuples
together.
 Here note one thing we can perform different operations
on tuples without changing its own definition.
Tuple1 = (1, 3, 4)
Tuple2 = (‘red’, ’green’, ‘blue’)
print (Tuple1 + Tuple2)

 Output:
 (1,3,4,’red’,’green’,’blue’)
BASIC TUPLES OPERATIONS
 Repetition operation:
 We can also repeat the elements in tuple for given number of
times using * operator.

>>>tuple1=(1,2,3)
>>>tuple1*2

Output:
(1,2,3,1,2,3)
BUILT IN TUPLE FUNCTIONS:
 Python has some built-in functions which can be performed directly
on the tuples.
 For e.g.,

1. max(),
2. min(),
3. len(),
4. sum(),
5. sorted() etc.
 max(tuple): It gives the maximum value from the tuple; here, the
tuple should not contain string values.
 Code:

 tuple1 = (1, 2, 3, 6)
print(max(tuple1))
Output:
 6
BUILT IN TUPLE FUNCTIONS:
 min(tuple): It gives the minimum value from the tuple; here the
condition is tuple should not contain string values.
 Code:
 tuple1 = (1, 2, 3, 6)
print(min(tuple1))
 Output:
1

 sum(tuple): The elements in a tuple should be integers only for


this operation. The sum will provide a summation of all the
elements in the tuple.
 Code:
 tuple1 = (1, 2, 3, 6)
print(sum(tuple1))
 Output:

BUILT IN TUPLE FUNCTIONS:
 sorted(tuple): If the elements are not arranged in order, we can use the sorted inbuilt function.
 Code: (Ascending)
 tuple2= (1, 4, 3, 2, 1, 7, 6)
print(sorted(tuple2))
 Output:
 (1,1,2,3,4,6,7)
 Code: (Descending)
 tuple2= (1, 4, 3, 2, 1, 7, 6)
print(sorted(tuple2,reverse=True))
 Output:
 (7,6,4,3,2,1,1)

 len(tuple) – Description The function len() returns the number of elements in the tuple.
 Syntax :len(tuple)
tup1,tup2=(123,'XYZ','PQR'),(456,'abc')
print(len(tup1))
print(len(tup2))
 Output:

3
2
METHODS OF TUPLE: (NOT IN
SYLLABUS READ ONCE)
 Count()- Returns the number of times a specified value
occurs in a tuple.
 index()- Searches the tuple for a specified value and
returns the position of where it was found.
 Example

tuple1=(123,789,123)
print(tuple1.index(789))
print(tuple1.count(123))
 Output
1
2
SETS { }:
 A Python set is the collection of the unordered items. Each
element in the set must be unique, immutable, and the sets
remove the duplicate elements. Sets are mutable which means
we can modify it after its creation.
 It is an unordered collection of objects, meaning it does not
record element position or order of insertion and so cannot
access elements using indexes.
 A set object contains one or more items, not necessarily of the
same type, which are separated by a comma and enclosed in
curly brackets {}.
SETS:
 A set doesn't store duplicate objects. Even if an object is
added more than once inside the curly brackets, only one
copy is held in the set object. Hence, indexing and slicing
operations cannot be done on a set object.
 Only immutable (and hashable) objects can be a part of a
set object. Numbers (integer, float, as well as complex),
strings, and tuple objects are accepted, but set, list, and
dictionary objects are not.
 Syntax:

Set_name={value1,value2,...valuen}
DEFINING AND ACCESSING ELEMENTS
IN SET
 A set contains an unordered collections of items. Set is
defined by values separated by comma inside braces {}.
 Another method is by making use of set()

 Example– # method1 to define set using {}


set1={'x','y','z'}
print(set1)
# method2 to define set using ()
set2=set(['x','y','x','z'])
print(set2)
 Output-

{'z', 'y', 'x'}


{'z', 'y', 'x'}
DEFINING AND ACCESSING ELEMENTS IN
SET
 Index cannot be used in sets to access the elements of set as
it is unordered.
 Loops are used to access the elements as shown in example
below
 Example–

set1=set(['p','q','r','s'])
for i in set1:
print(i)
 Output

p
r
q
s
DELETING VALUES IN SET–
 There are different ways to delete values in a set.
 Elements/items in set can be deleted using pop, remove or
discard method as shown in example.
 pop method removes random item from a set and return it.

 remove method is used to remove element from a set.

 Similarly discard method is also used remove element from


a set but the only difference between them is that remove
method raises key error if the specified item is not present
in the set.
DELETING VALUES IN SET
 Example-
set1=set(['p','q','r','s'])
print(set1)
set1.pop()
print(set1)
set1.discard('q')
print(set1)
set1.remove('a')
output-
{'r', 'p', 'q', 's'}
{'p', 'q', 's'}
{'p', 's'}
Traceback (most recent call last): File "D:\python programs\
trial.py", line 7, in set1.remove('a')
KeyError: 'a
UPDATING SETS
 Elements/items in set can be added by using add or update method as shown in
example.
 The add() method takes one argument which the element we want to add in set.

 Example–
set1={'p','q','r','s'}
set1.add('E')
print(set1)
 Output-

{'r', 'p', 'q', 's', 'E'}

 Loops can be used to add multiple elements at a time using add() method.
 Example-

set1={'p','q','r','s'}
t={1,2}
for i in t:
set1.add(i)
print(set1)
 Output:

{'q', 1, 2, 's', 'r', 'p'}


UPDATING SETS
 The update() method accepts lists, strings, tuples as well as
other sets as its arguments.
 In all of these cases, duplicate elements are avoided.

Example-
set1={'p','q','r','s'}
set1.add('E')
print(set1)
set1.update({'G','A'})
print(set1)
output-
{'r', 'E', 'p', 's', 'q'}
{'r', 'E', 'A', 'G', 'p', 's', 'q'}
BASIC SET OPERATIONS
 Set has four basic operations which are enlisted below
1) Union,
2) Intersection,
3) Difference and
4) Symmetric Difference
 Union- Union operation performed on two sets returns all the elements
from both the sets.
Union of set A and set B is defined as the set that consists of all
elements belonging to either set A or set B(or both).
It is performed by using | operator.
 Example:
A={1,2,4,6,8} OR A=set([1,2,4,6,8])
B={1,2,3,4,5} B=set([1,2,3,4,5])
C=A|B C=A|B
print(C) print(C)
Output- {1, 2, 3, 4, 5, 6, 8}
SET UNION
BASIC SET OPERATIONS
 Intersection-
 Intersection operation performed on two sets returns all the elements
which are common or in both the sets.
 Intersection of set A and set B is defined as the set that consists of
all elements that belong to both A and B.
 It is performed by using & operator.
 Example–

A={1,2,4,6,8}
B={1,2,3,4,5}
C=A&B
print(C)

 Output-

{1, 2, 4}
BASIC SET OPERATIONS
 Difference-
 Difference operation performed on two sets returns all the elements
which are present in set 1 but not in set2.
 It is performed by using - operator.
 Example–
A={1,2,4,6,8}
B={1,2,3,4,5}
C=A-B
print(C)

 Output-
{8, 6}
BASIC SET OPERATIONS
 Symmetric Difference-
 Symmetric difference operation is performed by using
^(XOR) operator.
 The Symmetric difference of two sets returns all the elements
which belongs either to set 1 or set2 but not both.
 It is performed by using ^ operator.

A={1,2,4,6,8}
B={1,2,3,4,5}
C=A^B
print(C)

Output-
{3, 5, 6, 8}
# PROGRAM TO PERFORM DIFFERENT SET OPERATIONS
A = {0, 2, 4, 6, 8}
B = {1, 2, 3, 4, 5}
# union
print("Union :", A | B)
# intersection
print("Intersection :", A & B)
# difference
print("Difference :", A - B)
# symmetric difference
print("Symmetric difference :", A ^ B)
Output-
('Union :', set([0, 1, 2, 3, 4, 5, 6, 8]))
('Intersection :', set([2, 4]))
('Difference :', set([8, 0, 6]))
('Symmetric difference :', set([0, 1, 3, 5, 6, 8]))
BUILT-IN SET METHODS
 add() – Adds an element to a set
 clear()- Removes all elements from the set

 e.g.

A={1,2,4,6,8}
B={2,4}
print(A)
A.clear()
print(A)
B.add(5)
print(B)
Output-
 {1, 2, 4, 6, 8}

 set()

 {2,5,4}
BUILT-IN SET METHODS
 union() – Returns a new set containing the union of two or
more sets.
 intersection()- Returns a new set which is the intersection of
two or more sets
 e.g.

A={1,2,4,6,8}
B={2,4}
print(A.union(B))
print(A.intersection(B))
Output-
{1, 2, 4, 6, 8}
{2, 4}
BUILT-IN SET METHODS
 difference() – Returns a new set containing the difference
between two or more set.
 e.g. A = {0, 2, 4, 6, 8}
B = {1, 2, 3, 4, 5}
print(A.difference(B))
 Output :
{0, 8, 6}
 symmetric_difference()- Returns a new set with the
symmetric differences of two or more sets.
 e.g. A = {0, 2, 4, 6, 8}

B = {1, 2, 3, 4, 5}
print(A.symmetric_difference(B))
 Output-
{0, 1, 3, 5, 6, 8}
BUILT-IN SET METHODS
 isdisjoint() – Return true if two sets have null intersection.
 e.g. A={1,2,4,6,8}

B={3,5}
print(A.isdisjoint(B))
 Output
True
 issubset()- Report whether another set contains this set.

 e.g. A={1,2,4,6,8}
B={2,6}
print(B.issubset(A))
 Output

True
BUILT-IN SET METHODS
 issuperset() – Determines whether one set is a superset of the
other.
 e.g. A={1,2,4,6,8}
B={1,2,4}
print(A.issuperset(B))
 Output
True
 pop()- Remove and return an arbitrary set element. Raises
keyerror if the set is empty.
 e.g. A={5,2,4,6,8}
print(A)
print(A.pop())
 Output-
{2, 4, 5, 6, 8}
2
BUILT-IN SET METHODS
 remove() – Remove an element from a set, which must be a
member.
 If the element is not a member, raise a keyerror.

 e.g. A={5,2,4,6,8}

print(A)
A.remove(4)
print(A)
 Output-
{2, 4, 5, 6, 8}
{2, 5, 6, 8}
BUILT-IN SET FUNCTIONS
 all() – Return True if all elements of the set are True(or if the set is empty)
 e.g.

set1={'p','q','r','s'}
print(all(set1))
set2=set()
print(all(set2))
set3={0,1,2,3}
print(all(set3))
 Output

True
True
False
set1={'p','q','r','s'}
 any() – Return True if any elements of the set is True. If the set is empty, return False.
print(any(set1))
 e.g. set1={'p','q','r','s'} OR set2={0,1}
print(any(set1)) print(any(set2))
set2=set() set3={0}
print(any(set2)) print(any(set3))
 Output OUTPUT-
True
True
True
False
BUILT-IN SET FUNCTIONS
 len() – Return the length (number of items) in the set. e.g.
set1={'p','q','r','s'}
print(len(set1))
set2=set()
print(len(set2))
 Output
4
0
 max() – Return the largest item in the set. e.g. set1={'p','ss','st','sz','r','q'}
print(max(set1))
set2={4,5,1,2}
print(max(set2))
 Output

sz
5
BUILT-IN SET FUNCTIONS
 min() – Return the smallest item in the set. e.g.
set1={‘r','q',‘p','s'}
print(min(set1))
set2={4,5,1,2}
print(min(set2))
 Output

p
1
 sorted() – Return a new sorted list from elements in the set. e.g. set1={4,5,1,2}

 print(sorted(set1)) # for Asending


 set1={'f','m','a','k','mzt','mm'}

 print(set1)

 print(sorted(set1,reverse=True)) # For Desending

 Output-

[1, 2, 4, 5]
{'a', 'k', 'm', 'mzt', 'f', 'mm'}
BUILT-IN SET FUNCTIONS
 sum() – Return the sum of all elements in the set. e.g.
set1={4,5,1,2}
print(sum(set1))
 Output

12
#WRITE A PYTHON PROGRAM TO CREATE A SET, ADD
MEMBER(S) IN A SET AND REMOVE ONE ITEM FROM A SET

s1={5,8,10,5,7}  Output-
print(s1) {8, 10, 5, 7}
s1.add(3) {3, 5, 7, 8, 10}
print(s1) {3, (2, 6), 5, 7, 8, 10}
s1.add((2,6)) {3, (2, 6), 5, 7, 8}
print(s1) {(2, 6), 5, 7, 8}
s1.remove(10)
print(s1)
s1.pop()
print(s1)
DICTIONARIES :
 Dictionary data structure is used to store key value pairs
indexed by keys.
 Dictionary in Python is an unordered collection of data values,
used to store data values like a map, which unlike other Data
Types that hold only single value as an element.
 It has a key: value pair where each value is associated with a
key.
 A key and its value are separated by a colon(:) between them.

 The items or elements in dictionary are separated by commas


and all the elements must be enclosed in curly braces.
CREATING DICTIONARIES
 The syntax for defining/creating a dictionary in python is
dict_name={key1:value1,key2:value2,…keyN:value}
 A dictionary can be used to store a collection of data values in a
way that allows them to be individually referenced.
 Rather than using an index to identify a data value, each item in
a dictionary is stored as a key value pair.
 The simple method to create a dictionary is simple assign the
pair of key:value pairs to the dictionary using operator(=).
EXAMPLE TO CREATE DICTIONARIES
# Creating an empty Dictionary
Dict = {}
print("Empty Dictionary: ")
print(Dict)

# Creating a Dictionary with Integer Keys


Dict= {1: 'Amol', 2: 'Ramesh', 3: 'Arun'} print("\nDictionary
with the use of Integer Keys: ") print(Dict)

# Creating a Dictionary with Mixed keys


Dict = {'Name': 'Amol', 1: [1, 2, 3, 4]} print("\nDictionary with
the use of Mixed Keys: ") print(Dict)
EXAMPLE TO CREATE DICTIONARIES
# Creating a Dictionary with dict() method
Dict = dict({1: 'Amol', 2: 'Ramesh', 3:'Arun'}) print("\
nDictionary with the use of dict(): ")
print(Dict)

# Creating a Dictionary with each item as a Pair


Dict = dict([(1, 'Amol'), (2, 'Arun')])
print("\nDictionary with each item as a pair: ") print(Dict)
OUTPUT
 Empty Dictionary:
 {}

 Dictionary with the use of Integer Keys:


 {1: 'Amol', 2: 'Ramesh', 3: 'Arun'}
 Dictionary with the use of Mixed Keys:
 {'Name': 'Amol', 1: [1, 2, 3, 4]}
 Dictionary with the use of dict():
 {1: 'Amol', 2: 'Ramesh', 3: 'Arun'}
 Dictionary with each item as a pair:
 {1: 'Amol', 2: 'Arun'}
ACCESSING VALUES IN DICTIONARY
 We can access the items of a dictionary by following ways:
# Accessing a element from a Dictionary
Dict = {1: 'Amol', 'name': 'Ramesh', 3: 'Arun'}
# accessing a element using key(string key)
print("Accessing a element using key:")
print(Dict['name'])

# accessing a element using key (number key)


print("Accessing a element using key:")
print(Dict[1])

# accessing a element using get() method


print("Accessing a element using get:")
print(Dict.get(3))
OUTPUT:
 Accessing a element using key: Ramesh
 Accessing a element using key: Amol

 Accessing a element using get: Arun


DELETING VALUES IN 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 popitem() method removes the item that was last inserted
into the dictionary.

 All items can be removed at once using clear() method.


 The del keyword is also used to remove individual items.
EXAMPLE–
 # Initial Dictionary
Dict = { 5 : 'A', 6 : 'To', 7 : 'Z', 'A' : {1 : 'Amol', 2 :
'Ramesh', 3 : 'Arun'}, 'B' : {1 : 'Amit', 2 : 'Rahul'}}
print("Initial Dictionary: ")
print(Dict)

o/p
Initial Dictionary: {5: 'A', 6: 'To', 7: 'Z', 'A': {1: 'Amol',
2: 'Ramesh', 3: 'Arun'}, 'B': {1: 'Amit', 2: 'Rahul'}}
# DELETING A KEY VALUE
del Dict[6]
print("\nDeleting a specific key: ")
print(Dict)
o/p
Deleting a specific key: {5: 'A', 7: 'Z', 'A': {1: 'Amol', 2: 'Ramesh', 3:
'Arun'}, 'B': {1: 'Amit', 2: 'Rahul'}}

# Deleting a Key using pop()


Dict.pop(5)
print("\nPopping specific element: ")
print(Dict)

o/p
Popping specific element: {7: 'Z', 'A': {1: 'Amol', 3: 'Arun'}, 'B': {1:
'Amit', 2: 'Rahul'}}
# DELETING A KEY FROM NESTED DICTIONARY
del Dict['A'][2]
print("\nDeleting a key from Nested Dictionary: ")
print(Dict)
o/p
Deleting a key from Nested Dictionary: {5: ‘A', 7: 'Z', 'A': {1: 'Amol',
3: 'Arun'}, 'B': {1: 'Amit', 2: 'Rahul'}}

# Deleting Key-value pair using popitem()


Dict.popitem()
print("\nPops an arbitrary key-value pair: ")
print(Dict)
o/p
Pops an arbitrary key-value pair: {7: 'Z', 'A': {1: 'Amol', 3: 'Arun'}}
# DELETING ENTIRE DICTIONARY
Dict.clear()
print("\nDeleting Entire elements in Dictionary: ")
print(Dict)
o/p
Deleting Entire Dictionary: {}
UPDATING DICTIONARY
 You can update a dictionary by including another entry or a key
esteem match.
 It is flexible data type that can be modified according to the
requirements which makes it is a mutable data type.
 The dictionary are mutable means changeable. 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
EXAMPLES
 dict1={'name':'vijay','age':40}
 dict1['age']=35

 print(dict1)

o/p- {'name': 'vijay', 'age': 35}

Example
 dict1={'name':'vijay','age':40}

 dict1['add']='Kolhapur'

 print(dict1)

o/p- {'name': 'vijay', 'age': 40, 'add': 'Kolhapur'}


BASIC DICTIONARY OPERATIONS
 Dictionary membership Test:
 We can test if a key is in a dictionary or not using keyword in.
 It is the test for keys not for values.
 Example: dict1={1:1,2:4,3:9,4:16,5:25}

print(dict1)
print(1 in dict1)
print(6 in dict1)
o/p- {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
True
False
BASIC DICTIONARY OPERATIONS
 Traversing Dictionary:
 Using a for loop we can iterate through each key in a
dictionary.
 Example dict1={1:1,2:4,3:9,4:16,5:25}
 for i in dict1:
 print(i,dict1[i])
 o/p
 1 1 2 4 3 9 4 16 5 25
BUILT-IN DICTIONARY FUNCTIONS :
 Built-in functions like all(), any(), len(), cmp(), sorted() etc. are
commonly used with dictionary to perform different tasks.
 all() - Return True if all keys of the dictionary are true (or if the
dictionary is empty).
 any() - Return True if any key of the dictionary is true. If the
dictionary is empty, return False.
 len() - Return the length (the number of items) in the
dictionary.
 sorted() -Return a new sorted list of keys in the dictionary
EXAMPLE
squares = {1: 1, 7: 9, 5: 25, 3: 49, 9: 81}
squares1={}
print(all(squares))
print(any(squares1))
print(len(squares))
print(sorted(squares))
 Output

True
False
5
[1, 3, 5, 7, 9]
BUILT-IN DICTIONARY METHODS
 clear() - Removes all the elements from the dictionary.
 copy() – Returns a copy of the dictionary
 fromkeys() – It creates a new dictionary with default value for all
specified keys. If the default value is not specified all the keys are set
to none.
 get() – Returns the value of the specified key.
 items() – Returns a list containing a tuple for each key value pair.
 keys() – Returns a list containing the dictionary keys.
 pop() – Removes the element with the specified key.
 popitem() – The popitem() method removes the item that was last
inserted into the dictionary.
 setdefault() - It is similar to get(), but will set dict[key]=default if key
is not already in dict.
 update() – Updates the dictionary with key-value pairs of another
dictionary.

EXAMPLE-# BUILT-IN DICTIONARY METHODS
squares = {1:1, 2:4, 3:9, print(squares.get(2))
4:16, 5:25} for i in squares.items():
squares3={} print(i)
print(squares.pop(4)) print(squares.keys())
print(squares) squares1.setdefault(7,None)
squares1=squares.copy() print(squares1)
print(squares1) squares3.update(squares)
print(squares.popitem()) print(squares3)
print(squares) print(squares.values())
squares2=squares.fromkeys squares.clear()
([1,3],5)
print(squares)
print(squares2)
OUTPUT
 16
 {1: 1, 2: 4, 3: 9, 5: 25}
 {1: 1, 2: 4, 3: 9, 5: 25}
 (5, 25)
 {1: 1, 2: 4, 3: 9}
 {1: 5, 3: 5}
 4
 (1, 1)
 (2, 4)
 (3, 9)
 dict_keys([1, 2, 3])
 {1: 1, 2: 4, 3: 9, 5: 25, 7: None}
 {1: 1, 2: 4, 3: 9}
 dict_values([1, 4, 9])

You might also like