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

chapt3

Chapter 3 covers various data structures in Python, including lists, tuples, sets, and dictionaries, detailing their creation, manipulation, and operations. It explains how to perform basic operations such as accessing, updating, deleting elements, and using built-in functions for each data structure. The chapter emphasizes the differences between these structures and provides examples for better understanding.

Uploaded by

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

chapt3

Chapter 3 covers various data structures in Python, including lists, tuples, sets, and dictionaries, detailing their creation, manipulation, and operations. It explains how to perform basic operations such as accessing, updating, deleting elements, and using built-in functions for each data structure. The chapter emphasizes the differences between these structures and provides examples for better understanding.

Uploaded by

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

Chapter 3

Data Structures in Python

Unit Outcomes :
1) Write python program to use and manipulate lists
for the given problem.
2) Write python program to use and manipulate Tuples
for the given problem.
3) Write python program to use and manipulate sets
for the given problem.
4) Write python program to use and manipulate
Dictionaries for the given problem.
Lists
• It is a sequence of values written in asquare
bracket and separated by commas.
• For example
• L1=[‘AAA’,’BBB’,’CCC’]
• L2=[10,20,30,40]
• Here L1 and L2 are lists data structures.
Accessing values in Lists

• Individual elements of the list can be accessed


using index of the list.
• For example
• rollNo=[1,2,3,4,5]
• Name=[‘Amit’,’Pradeep’,’Neha’,’Amit’]
• print (rollno[0],name[0])
• print (rollno[1],name[1])
• print(rollno[1:4])
Deleting Values in List
• The deletion of any element from the list can be done
by using various functions like pop , remove, del.
• The pop function is used when we know the index of
the element, then just pass that index as an argument
to pop function.
• a=[‘u’,’v’,’w’,’x’,’y’,’z’]
• val=a.pop(1)
• val contains the deleted element and now
• a=[‘u’,’w’,’x’,’y’,’z’]
• If we do not provide any argument to the pop function
then the last element of the list will be deleted.
Deleting Values in List
• If we know the value of the element to be
deleted then the remove function is used.
• We pass actual value that is to be removed
from the list as an argument to remove
function.
• Unlike, pop function remove function does not
return any value.
• a=[‘u’,’v’,’w’,’x’,’y’,’z’]
• a.remove(‘v’)
Deleting Values in List
• In python, it is possible to remove more than
one element at a time using del function.
• a=[‘u’,’v’,’w’,’x’,’y’,’z’]
• del a[2:4]
• Now a =[‘u’,’v’,’y’,’z’]
Updating List
• Lists are mutable. It means, it is possible to
change the values of list.
• a=[‘AAA’,’BBB’,’CCC’]
• a[1]=‘XXX’
• Now a=[‘AAA’,’XXX’,’CCC’]
• Using in operator we can check whether
particular element belongs to the list or not. If
the given element is present in the list it
returns true otherwise false.
Updating List
• a=[‘AAA’,’XXX’,’CCC’]
• ‘XXX’ in a
• True
• ‘BBB’ in a
• False
Basic List Operations
1) Traversing a list
-> The for loop is used to traverse the list elements.
-> for variable in List:
body of for
-> example:
a=[‘u’,’v’,’w’,’x’,’y’,’z’]
for i in a:
print(i)
range() and enumerate() functions can also be
used to traverse the list
Traversing a list
a=[‘u’,’x’,’y’]
for i in range(len(a)):
print(a[i])
Output : u
x
y

for i in enumerate(a):
print(i)
(0, 'u')
(1, 'x')
(2, 'y')
List concatenation

• Two lists can be joined using + operator.


• L1=[1,2,3]
• L2=[4,5,6]
• L=L1+L2
• L=[1,2,3,4,5,6]
Repetition using *

• [12]*4
output :- [12, 12, 12, 12]
• [1,2,3]*5
output :- [1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3]
Finding length of a list
• The len() function is used to find the no of
elements present in the list.
• a=[1,2,3,4,5,6,7]
• a
• [1, 2, 3, 4, 5, 6, 7]
• print(len(a))
• 7
List Methods
1) append
This method adds elements at the end of the
list.
a=[10,20,30,40]
a.append(50)
a
[10, 20, 30, 40, 50]
List Methods
2) extend
This method takes the list as an argument and
appends this list at the end of old list.
a=[1,2,3]
b=[4,5,6]
a.extend(b)
a
[1, 2, 3, 4, 5, 6]
List Methods
3) Sort
This method arranges the elements in increasing order.
a=[‘x’,’y’,’u’,’v’,’w’,’z’]
a.sort()
a
[‘u’,’v’,’w’,’x’,’y’,’z’]

The methods append, extend and sort does not return


any value. These methods simply modify the list.
Built in List Functions
• There are various built in functions in python for supporting the list
operations.
1)all()
If all the elements of the list are true or if the list is empty then it returns true
2)any()
If list contains any element it returns true and if list is empty it returns false
3)Len()
It returns length of a list
4)Max()
It returns maximum element present in the list
5)Min()
It returns maximum element present in the list
6)Sum()
It returns sum of all the elements present in the list
7)sorted()
It returns a list which is sorted.
Functions related to String
1) list()
• String is a sequence of characters and list is
sequence of values.
• But list of characters is not the string.
• We can convert the string to list of characters.
• s1='python'
• s1
• 'python'
• mylist=list(s1)
• mylist
• ['p', 'y', 't', 'h', 'o', 'n']
Functions related to String
2) split()
If the string contains multiple words then split
function can be used to split the words into list
str="python is an object oriented programming
language“
mylist=str.split()
mylist
['python', 'is', 'an', 'object', 'oriented',
'programming', 'language']
Functions related to String
3) join()
• It is exactly reverse to the split function.
• It takes the list of strings and concatenate to form a string.
mylist = ['python', 'is', 'an', 'object', 'oriented', 'programming',
'language']
ch='#'
ch.join(mylist)
'python#is#an#object#oriented#programming#language'
ch='$'
ch.join(mylist)
'python$is$an$object$oriented$programming$language'
Note : String is joined using delimitting character # and $.

WAP to create a list of even nos from 1 to 20.


even=[] # create empty list
for i in range(1,21):
if i % 2==0 :
even.append(i)
print ("even nos list is :",even )
Tuples
• Tuple is a collection of elements which are
enclosed within the parenthesis, and these
elements are separated by commas.

• How to create tuple ?


T1= (10,20,30,40)
T2=(‘a’,’b’,’c’,’d’)
T3=(“aa”,”bb”,50,60)
• Difference between tuple and List
1)Tuple use parenthesis and list use square brackets.
2)Tuples can not be changed, lists can be changed.

• Accessing values in Tuple


-> The elements in Tuple can be accessed using the
index.
T1=(1,2,3,4,5)
print(T1[2])
3
print(T1[1:3])
(2, 3)
• Deleting values in Tuple
We can delete a tuple using del statement.
T1=(1,2,3,4,5)
del T1
print(T1)
Traceback (most recent call last):
File "<pyshell#12>", line 1, in <module>
print(T1)
NameError: name 'T1' is not defined
Updating Tuple
-> Tuples are immutable. We can not change
values of tuple, we can only extract values of
tuple to create another tuple.
-> T1=(10,20,30,40,50)
T1
(10, 20, 30, 40, 50)
T2 =(60,70)
T3=T1+T2
T3
(10, 20, 30, 40, 50, 60, 70)
Basic Tuple Operations
1) len()
It is used to find total number of elements in the tuple.
T1=(10,20,30,40)
print(T1)
4

2) Concatenation()
The + operator is used to concatenate two tuples.
T1=(1,2,3)
T2=(4,5)
print(T1+T2)
(1,2,3,4,5)
Basic Tuple Operations
3) Repetition
The * operator is used for repetition of the elements.
T1=(1,2,3)
print(T1*3)
(1,2,3,1,2,3,1,2,3)

4)Membership
It means checking if the element is present in the tuple or not.
The membership operation is performed using in operator.
T1=(1,2,3,4,5)
print (3 in T1)
True
print(6 in T1)
false
Built in tuple Function
1)cmp(t1,t2)
This function compares tuple t1 and t2
It will return -1 if t1<t2
0 if t1=t2
1 if t1>t2
2) max(t1)
It returns maximum value from the given tuple t1.

3) Min(t1)
It returns minimum value from the given tuple t1.
Built in tuple Function

4) tuple(sequence)
It converts the list into tuple.
l=[1,2,3]
t=tuple(l)
print (t)
(1, 2, 3)

t1=tuple("python")
>>> print(t1)
('p', 'y', 't', 'h', 'o', 'n')
Sets
-> Sets are data structures that, follows
following rules.
1) Items in a set are unique.
2) Items in a set are not ordered.

How to create set?


s={1,2,3,4,5}
print(s)
{1,2,3,4,5}
Sets
The set can also be created by using set
function.

color=set(['red','green','blue'])
print(color)
{'red', 'green', 'blue'}
Accessing values in set
We can not access the values in set using index as the set is
unordered and has no index.
It is possible to iterate through each item of a set using for loop.
s={'a','b',3,4,"amit"}
for i in s:
print(i)

3
4
b
a
amit
Deleting values in set
• For removing item from the set either remove or
discard method is used.
• del keyword is used to delete the set completely.

s={10,20,30,40,50}
s.remove(40)
print(s)
{10, 50, 20, 30}
s.discard(20)
print (s)
{10, 50, 30}
Deleting set
del s
print(s)
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module> print(s)
NameError: name 's' is not defined
Updating values in set
• Once the set is created, we can not change the values
in the set. But we can add elements to the set by using
add() method.
• By using update() method more than one element can
be added to the set.
s={10,20,30,40,50}
s.add(25)
print(s)
{40, 10, 50, 20, 25, 30}
s.update([35,45])
print(s)
{35, 40, 10, 45, 50, 20, 25, 30}
Basic Set Operations
1) Union
The union between two sets, results in a third set with all the
elements from both sets.
It is performed using the operator |.
Example :
>>> s={1,2,3}
>>> s1={2,3,4}
>>> s2=s|s1
>>> print(s2)
{1, 2, 3, 4}
>>> s3=s.union(s1)
>>> print(s3)
{1, 2, 3, 4}
>>>
Basic Set Operations

2) Intersection
-> The intersection of two sets is a third set in which
only common elements from both the sets are enlisted.
-> It is performed using & operator.

>>> set1={1,2,3,4,5,6}
>>> set2={4,5,6,7,8,9}
>>> set3=set1&set2
>>> set3
{4, 5, 6}
Basic Set Operations
3) Difference
-> Difference of A and B i.e.(A-B) is a set of
elements that are only in A but not in B.
-> Similarly B-A is a set of elements in B but not
in A.
->The operator – is used for difference.
-> The method difference is also used for
specifying the difference.
Basic Set Operations

3)Difference

>>> A={1,2,3,4,5,6}
>>> B={4,5,6,7,8,9}
>>> C=A-B
>>> C
{1, 2, 3}
>>> B-A
{8, 9, 7}
>>> A.difference(B)
{1, 2, 3}
Basic Set Operations
4) Symmetric difference
-> It is a set of elements in both A and B except those that
are common in both.
-> It is performed using ^ operator.
-> The symmetric_difference() method can also be used.
>>> A={1,2,3,4,5,6}
>>> B={4,5,6,7,8,9}
>>> C=A^B
>>> C
{1, 2, 3, 7, 8, 9}
>>> A.symmetric_difference(B)
{1, 2, 3, 7, 8, 9}
Built in Set function
1)all()
It returns true if all elements of the set are true.
It also returns true if the set is empty.
2) any()
It returns true if any element of the set is true. If set is empty it returns false.
3) len()
It returns the length of the set.
4)max()
It returns maximum value present in the set.
5) min()
It returns minimum value present in the set.
6) sorted()
It returns a new sorted list from the elements.
Sorted(s1,reverse=True)
7) sum()
It returns the sum of all elements in the set.
Built in Set function

>>> print(all(set1))
True
>>> print(any(set1))
True
>>> set2={}
>>> print(all(set2))
True
>>> print(any(set2))
False
Dictionaries
• It is unordered collection of items.
• These items are in the form key-value pairs.
• Dictionary always represent the mappings of
keys with values.

How to create Dictionary?


• Items of the dictionary are written within the
{} brackets and are separated by commas.
• The key value pair is represented using :
operator. i.e. key:value
Dictionaries
• d1={1:"Ankit" , 2:"Amaan" , 3:'Nazifa' ,
4:'Dhruv'}
• >>> d1
• {1: 'Ankit', 2: 'Amaan', 3: 'Nazifa', 4: 'Dhruv'}
Dictionaries
>>> d1={1:"Ankit" , 2:"Amaan" , 3:'Nazifa' ,
4:'Dhruv'}
>>> d1
{1: ‘Smit', 2: ‘John', 3: 'Niya', 4: 'Daksh'}

We can also create a dictionary using the word dict


>>> colordict=dict({0:'Red',1:"Green", 2:'Blue'})
>>> colordict
{0: 'Red', 1: 'Green', 2: 'Blue'}
>>>
Accessing values in Dictionary
• We can access the element in the dictionary
using the keys.
d1={1:“Smit" , 2:“John" , 3:'Nia' , 4:'Daksh'}
>>> print(d1[1])
Smit
>>> print(d1[3])
Nia
Traversing Dictionary
for i in d1:
print(i,d1[i])
1 Smit
2 john
3 Nia
4 Daksh
Deleting and Updating values in Dictionary
• For removing an item from the dictionary we
use the keyword del.
>>> del d1[4]
>>> d1
{1: ‘Smit', 2: ‘John', 3: 'Nia'}
>>>d1[2]='Sushant'
>>> d1
{1: ‘Smit', 2: 'Sushant', 3: 'Nia'}
Basic Dictionary Operations
1) Adding item to Dictionary
>>>d1
{1: ‘Smit', 2: ‘Sushant', 3: 'Nia'}
>>> d1[4]='Sakshi'
>>> d1
{1: ' Smit ', 2: 'Sushant', 3: 'Nia', 4: 'Sakshi'}
>>> d1[6]='Meet'
>>> d1[5]='Ritu'
>>> d1
{1: ‘Smit', 2: 'Sushant', 3: 'Nia', 4: 'Sakshi', 6: 'Meet', 5:
'Ritu'}
>>>
Basic Dictionary Operations
2) Checking length
The len() function gives the no of pairs in the dictionary.
>>> len(d1)
6

3) Iterating through Dictionary


for i in d1:
print(i,d1[i])
1 Ankit
2 Sushant
3 Nazifa
4 Sakshi
6 Meet
5 Ritu
Built in Dictionary Functions
1) clear()
Removes all items from dictionary.
>>> d1.clear()
>>> d1
{}
2) copy()
Returns a copy of dictionary.
>>> d1
{1: ‘Smit', 2: 'Sushant', 3: 'Nia', 4: 'Sakshi', 6: 'Meet', 5: 'Ritu'}
>>> d2=d1.copy()
>>> d2
{1: ‘Smit', 2: 'Sushant', 3: 'Nia', 4: 'Sakshi', 6: 'Meet', 5: 'Ritu'}
>>>
Built in Dictionary Functions
3) fromkeys()
It creates a new dictionary from given sequence
of elements and values provided by user.
>>> keys={10,20,30}
>>> values='Number'
>>> d2=dict.fromkeys(keys,values)
>>> d2
{10: 'Number', 20: 'Number', 30: 'Number'}
>>>
Built in Dictionary Functions
4) get ()
It returns the value for the specified key if key is in dictionary.
>>> student={ 'rollno':10,'name':'Aakash','marks':90}
>>> student
{'rollno': 10, 'name': 'Aakash', 'marks': 90}
>>> print("Name :" ,student.get('name'))
Name : Aakash
>>> print("Name :" ,student.get('rollno'))
Name : 10
>>> print("Name :" ,student.get('marks'))
Name : 90
>>>
Built in Dictionary Functions
5) values()
It returns the value object that displays the list of
values present in the dictionary

>>> marksdictionary={'m1':85,'m2':90,'m3':94}
>>> print(marksdictionary.values())
dict_values([85, 90, 94])
>>>
Built in Dictionary Functions
6) pop()
It removes and returns an element from a
dictionary having the given key.

>>> student
{'rollno': 10, 'name': 'Aakash', 'marks': 90}
>>> val=student.pop('rollno')
>>> val
10
>>>
Programs

• WAP to sort the elements of dictionary


• WAP to create a tuple from given dictionary
elements.
c={'red':10, 'blue':34, 'yellow':16, 'orange':23}
clist=list(c.keys())
print(clist)
clist.sort()
print("sorted list based on keys")
for i in clist:
print (i)

Output :
RESTART: C:/Users/Lab 13-25/AppData/Local/Programs/Python/Python37-
32/clist1.py
['red', 'blue', 'yellow', 'orange']
sorted list based on keys
blue
orange
red
yellow
>>>

You might also like