Unit 4 Data Structure Stds in Python
Unit 4 Data Structure Stds in Python
print( )
b = array('d', [2.5, 3.2, 3.3])
print("\nThe new created array 2 is : ", end=" ")
for n in b:
The new created array 2 is : 2.5 3.2 3.3
print(n, end=" ")
print( )
c = array('u', ['a','b','c'])
print("\nThe new created array 3 is : ", end=" ")
for n in c: The new created array 2 is : a b c
print(n, end=" ")
Length of an array : To find out the number of elements of an array we can use the len ( )
function :
Example : Program to find length of an array. Arraylength.py
from array import *
a = array('i', [1, 2, 3]) OUTPUT
length = len( a)
print (" Length of array is: " , length) Length of array is: 3
print("The Elements of an array are : ", end=" ")
for n in range(length) :
print( a[n], end=" ") The Elements of an array are : 1 2 3
As lists are mutable various operations which can be performed on lists are :
Append ( )
Insert ( )
Extend ( ) # list.extend(list1) Appends list1 to list
Remove ( )
Pop ( ) , etc
Key Features :
1.Heterogeneous : Lists can contain items of different types at the same time (including integers,
floating point numbers, strings and boolean values).
2. Ordered : A list is order collection of objects . It means that the order in which elements are
added are preserved, and cannot change the place automatically. The order is preserved even after
operations like insertion or deletion. This means that elements can be accessed and referred to by
their position in the list.
3. Indexing : Elements in a list are accessed using their position or index. The index starts from 0,
and each element has a unique index corresponding to its position in the list. Negative indexing can
be used to access elements from the end of the list.
4. Slicing : Lists support slicing, which allows you to extract sublists based on specified indices.
Slicing can be used to create new lists, copy parts of an existing list, or perform selective operations
on elements.
5. Mutable : Lists are mutable, meaning that their elements can be modified after creation. You can
change the values of existing elements, add new elements, or remove existing elements in place. This
flexibility makes lists well-suited for dynamic data handling.
6. Dynamic: Lists can dynamically grow or shrink as needed. You need not to specify the size of
list when creating it.You can append new elements to the end of the list or insert them at specific
positions. Similarly, you can remove elements from the list. This dynamic nature makes lists
adaptable to changing data requirements..
7. Duplicates : List can contain duplicate elements. We can have multiple occurrences of the same
element in the list.
8. Nested : Lists can contain other lists or sublist as elements , creating nested lists. In python,
nesting of lists is allowed upto certain number of times.
Declaring / Creating / initializing a List
1. Lists in Python can be created by just placing the sequence inside the square brackets [ ].
Square brackets indicate start and end of the list , consisting of elements separated by commas.,
E.g
[ 5 , 10 , 15 ]
[ ‘a’, ‘b’, ‘c’ ]
So general syntax is :
< list_name> = [ Value , …..]
< list_name> = [ ]
This construct is known as list display construct.
Example : Program to show creation of list Creating List.py
L1 = [ 5 , 10 , 15 ] OUTPUT
print(" \n Elements of L1 are :", L1)
Elements of L1 are : [5, 10, 15]
L2 = [ ]
print(" \n Blank list :", L2) Blank list : [ ]
L3 = [ [1,2,3], ['a','b'], [4,5,6]]
print(" \n Nested list :", L3) Nested list : [[1, 2, 3], ['a', 'b'], [4, 5, 6]]
print(" \n Creating a list using list function :")
Creating a list using list function :
L4= list ( )
print(" \n Elements of L4 are :", L4)
L5 = list("Hello") Elements of L4 are : [ ]
print(" \n Elements of L5 are :", L5) Elements of L5 are : ['H', 'e', 'l', 'l', 'o']
print(" \n Creating a list L6 from existing list L1 :")
Creating a list L6 from existing list L1 :
L6=L1
print(" \n Elements of L6 are :", L6) Elements of L6 are : [5, 10, 15]
Example : Program to show creation of List from KB Creating List1.py
OUTPUT :
Taking input from Keyboard
Enter elements of List7 :12345
Elements of L7 are : ['1', '2', '3', '4', '5']
Enter elements of List8 :12345
Elements of L8 are : 12345
Size of Python list : Python len( ) function is used to get the length of the list.
E.g : sizeoflist.py
list1 = [ ] OUTPUT
size = len(list1) 0
print (size)
list2= [ 1, 2,( 1,2,3), ’ahmad’ ]
print (len(list2)) 4
Accessing Elements of List : Like strings to access values in lists, use the square brackets
( slicing operator [ ] ) for slicing along with the index or indices to obtain value available at that
index. List indices start from 0 ( zero) to the length of -1. The list index can be a positive or
negative integer value or an expression which evaluates to an integer value.
Example : Various Operations of Lists Accessing of List.py
L1 = [ 1,2,3,4,5,6,7,8] # single dimensional list OUTPUT
L2 = [ 1, 2, ['Apple', 'For'], ['Pear'], 4]
# Multi dimensional list
Tuple : Tuple is another built-in data types in Python. It is a sequence data type which is used to
store the collection of data elements. These data elements can be of the same type or they can be of
different data types as well. The items in the Tuple are separated by comma ( , ) and enclosed
within the parentheses ( ). Tuples are similar to lists but the main difference is Tuples are
immutable whereas lists are mutable. So we cannot modify its elements once it is created. Hence
we cannot perform operations like Append ( ), Insert ( ), Extend ( ), Remove ( ), Pop ( ), clear etc
on Tuples.Tuples are generally used to store data which should not modified and retrieve that data
on demand.
E.g :
Tuple1 = [ 2, 6, 10, 49 ]
Tuple2 = [" Adnan", 18, "Aamir", 37.5]
Key Features :
1.Heterogeneous : Tuples can contain items of different types at the same time (including
integers, floating point numbers, strings and boolean values).
2. Ordered : A Tuple is order collection of objects . It means that the order in which elements are
added are preserved, and cannot change the place automatically. The order is preserved even after
operations like insertion or deletion. This means that elements can be accessed and referred to by
their position in the list.
3. Indexing : Elements in a tuple are accessed using their position or index. The index starts from
0, and each element has a unique index corresponding to its position in the list. Negative indexing
can be used to access elements from the end of the list.
4. Slicing : Tuples support slicing, which allows you to extract subtuples based on specified
indices. Slicing can be used to create new tuples, copy parts of an existing tuple, or perform
selective operations on elements.
5. Immutable : Tuples are immutable, meaning that their elements can’t be modified, added etc
after creation. However , if the element of a tuple is of mutable type e.g list , then we can modify that
elements.
6. Duplicates : Tuples can contain duplicate elements. We can have multiple occurrences of the
same element in the tuple.
7. Nested : Tuples can contain other Tuple or sublist as elements , creating nested tuples.
8.Memory Efficiency : Tuples are memory efficient than lists because they are immutable. Once a
tuple is created , its size and structure cannot change allowing for better memory management.
Creating a Tuple
Lists can be created in number of ways . Some common methods are :
1. Using parentheses ( ): In this case all the items of Tuple are separated by comma and enclosed
in a parenthesis / round brackets. Round brackets indicate start and end of the Tuple.
The syntax in this case will be :
< tuple_name> = ( Value1 , Value2, ….Value n )
E.g : tup = ( ‘ Birds ’, ‘ Animals ’, 2024)
The above construct is known as tuple display construct.
2. Without using parentheses ( ): If we have got sequence of comma separated values , python
will automatically create a tuple form it.
< tuple_name> = Value1 , Value2, ….Value n
T1 = ( 5 , 10 , 15 ) OUTPUT
print(" \n Elements of T1 are :", T1)
Elements of T1 are : (5, 10, 15)
T2 = 5 , 10 , 15
print(" \n Elements of T2 are :", T1) Elements of T2 are : (5, 10, 15)
T3 = ( )
print(" \n Blank Tuple :", T3 ) Blank Tuple : ( )
print(" \n Creating a Tuple using Tuple function :")
Creating a Tuple using Tuple function :
T4 = tuple((" Hello", "all", "Students")) # note the double
round-brackets
print(" \n Creating a Singleton Tuple using Tuple function Creating a Singleton Tuple using Tuple function
:") :
T5= tuple ( " Hello", )
print(" \n Elements of Singleton Tuple T5 are :", T5) Elements of Singleton Tuple T5 are : (' ', 'H', 'e',
'l', 'l', 'o')
T6 = ( (1,2,3), ('a','b'), (4,5,6))
print(" \n Nested Tuple :", T6) Nested Tuple : ((1, 2, 3), ('a', 'b'), (4, 5, 6))
Size of Tuple : Python len( ) function is used to get the length of the Tuple.
Example :
Tuple1 = ( ) OUTPUT
size = len(Tuple1)
print (size) 0
Tuple2 = ( 'ahmad', )
print (len(Tuple2)) 1
Tuple3 = ( 5,10,15 ) 3
print (len(Tuple3))
Accessing Elements of Tuple : Like Lists to access values in Tuples, use the square brackets
( slicing operator [ ] ) for slicing along with the index or indices to obtain value available at that
index. Tuple indices start from 0 ( zero) to the length of -1. The Tuple index can be a positive or
negative integer value or an expression which evaluates to an integer value.
Example : Program to access the elements of Tuples Accessing of Tuples.py
Dictionary : Dictionary is another built in data type in python which is used to store the data in
key-value pairs. ( key and value of that key). So, we can say dictionaries are a collection of some
key-value pairs. Keys in these act as unique identifiers and the values are the data elements
associated with those keys.
A telephone directory can be compared to a dictionary in Python. In this directory , the
subscriber’s number gets stored according to his name and address. So name becomes a key for
reference and telephone number becomes the value to be searched for. Similarly in python if we
access a key , then we will get its corresponding value that has been saved with the key. Values
can be any type of objects. These values can be changed after being created defined as the
dictionary is mutable data structure. .However , the keys in dictionary must be immutable and
cannot accept duplicate values. The keys can be integer, string , a tuple ( containing only
immutable entries) . Also keys are case sensitive i.e same name but different case of keys will be
treated differently.
If we try to give mutable type as key , python will give an error as “unhashable type”
E.g :
Dic1 = { ‘R’: Rainy , ‘S’: Summmer, ‘W’: Winter }
Dic2 = {‘ Name’ : “Adnan”, ‘marks’: [10,20,30] }
Key Features :
1.Key-Value Pairs: Dictionaries in Python consists of ‘key-value pairs’. Each key is unique s
and is used to access its corresponding value. So , each key maps to its value. Each key is separated
from its value by a colon ( : ) and key value pairs are separated from each other by commas , and
entire dictionary is enclosed in curly braces { }.
2.Order : In python 3.6 and early versions dictionaries were unordered collections. (That
means the order in which items were inserted in Dictionary is not
necessarily same in which they are stored or retrieved). But from python 3.7 on
wards dictionaries are ordered collections i.e they maintain there insertion order of keys.
3.Heterogeneous : Dictionaries can have values of different data types. Only thing is that
keys must of an immutable type.
4. Mutable : Dictionaries are mutable. We can add new items , delete or change the value of
existing key-value pairs. However keys are immutable.
5. Duplicate Keys / Values : Dictionary keys are unique and immutable. Values however can be
changed , as they are mutable and we can have duplicate values also .
6. Indexed by keys : The elements of key are indexed by keys and not by their relative positions or
indices. .
7. Dynamic : Dictionaries can grow or shrink dynamically to accommodate any number of key-
value pairs . So , size of dictionary is not fixed and can change based on the operations performed on
it.
8. Nested : These can be nested .Value associated with a key can be another dictionary or list.
E,g : Dictionary1 = {'a': 11 , 'b': 12, 'c': [11, 12, 'd'], 'd': {'e': 13}}
Creating a Dictionary
Dictionary can be created in number of ways . Some common methods are :
1. Using parentheses { }: It can be created by placing items ( i.e key value pair ) inside curly
braces { } separated by commas.
The syntax in this case will be :
< dictionary_name> = { key1: value1 , key2: value2, ……. Keyn : valuen }
E.g : D1 = {'a': 11 , 'b': 12, 'c': [11, 12, 'd'], 'd': {'e': 13}}
D2 = {1: 'one', (1, 2, 3) : 'two', 2.2: 'Float' }
2. Empty Dictionary : This can be created by just using curly braces { } with nothing inside them.
D3 = { }
3. Using Built-in function dict ( )
< dictionary _name> = dict ( ) .
print(" \n Creating a Dictionary using Dictionary function dict ( ) Creating a Dictionary using Dictionary function dict (
:") ):
D4 = dict( I='one', II =' Two')
print(" \n Elements of D4 are :", D4) Elements of D4 are : {'I': 'one', 'II': 'Two'}
D5 = { }
print(" \n Blank Dictionary :", D5 ) Blank Dictionary : { }
print (" \n Adding elements to D5") Adding elements to D5
D5[1]="Name"
D5[2]="Age"
D5[3]="Rollno" # We can modify the value of element as D3[3]
= “Class”
print(" \n Elements of D5 are :", D5) Elements of D5 are : {1: 'Name', 2: 'Age', 3: 'Rollno'}
Size of Dictionary : Python len( ) function is used to get the length of the Dict.
Accessing Elements of Dictionary : In python we can access the values associated with keys in a
dictionary by accessing values using keys , iterating over keys , iterating over values iterating over
key –value pairs and by get method.
Example : Program to access the elements of Dictionary Accessing of Dictionary.py
print(" \n Elements of D1 :", D1 , " \n Elements of D2 :", D2 ) Elements of D1 : {'a': 11, 'b': 12, 'c': [11, 12, 'd'],
'd': {'e': 13}}
Elements of D2 : {1: 'one', (1, 2, 3): 'two', 2.2:
'Float'}
print(" \n Accessing elements of dictionary through iteration :") Accessing elements of dictionary through
for key in D1: iteration :
print ( key , ":", D1[ key]) a : 11
b : 12
c : [11, 12, 'd']
d : {'e': 13}
Sets
A set is a both unordered.and unindexed collection of elements that can have only distinct values
and no duplicates. It is one of the four built-in data types (List, Dictionary, Tuple, and Set) in
python While sets are mutable, meaning you can add or remove elements after their creation, the
individual elements within the set must be immutable and cannot be changed directly. Sets are
defined while using curly braces .
E.g :
Set1 = S1 = { 5 , 10 , 15 ,5 }
Set2 = { "Anas", "Bariz" , "Musavir" }
Note : Sets are unordered , so you cannot be sure in which order the items will appers.
Sets can also be utilized to conduct mathematical set operations such as union, intersection, and
symmetric difference, among others.
Key Features :
1.Heterogeneous : Sets can contain items of different types at the same time (including integers,
floating point numbers, strings and boolean values).
2. Unordered : As sets are unordered collection of elements , set elements can appear in a different
order every time we use them, and cannot be referred to by index or key.
3. Duplicates : Duplicate elements if added will be ignored by set ,maintaining only unique
elements.
4. Iteration : We can iterate over the elements of set using while or for loop .
5. Immutable : While sets are mutable, meaning you can add or remove elements after their
creation, the individual elements within the set are immutable . So we can add or remove elements
after creation of set but we cannot change its elements.
6. Dynamic : Sets can grow or shrink dynamically as elements are added or removed from it.
You need not to specify the size of Set while creating it.
7. Set operations : Sets can also be utilized to conduct mathematical set operations such as union,
intersection, and symmetric difference, among others.
Creating a Set
Set can be created in number of ways . Some common methods are :
1. Using curly Braces { }: It can be created by placing items inside curly braces { } separated by
commas.
The syntax in this case will be :
< Set_name> = { Item1, Item2 , Item3 ….. }
E.g : S1 = {"abc", 34, True, 40, "male"}
S2 = {"Hello", 34, -13, , "male"}
S1 = { 5 , 10 , 15 ,9 }
print(" \n Elements of S1 are :", S1) Elements of S1 are : {9, 10, 5, 15}
S2 = { "Anas", "Bariz" , "Musavir" }
print(" \n Elements of S2 are :", S2) Elements of S2 are : {'Musavir', 'Bariz', 'Anas'}
print ( "\n Using set function") Using set function
S3=set ( )
print(" \n Empty set S3 :" , S3) Empty set S3 : set( )
S4=set(S2)
print(" \n Elements of S4 are :", S4) Elements of S4 are : {'Musavir', 'Bariz', 'Anas'}
S5={ 5,12,23,5,19,5,24}
print(" \n Elements of S5 with duplicate elements :" , S5) Elements of S5 with duplicate elements : {5, 12,
19, 23, 24}
L1=[2,3,4,5,]
S8={L1}
print(" \n Elements of S8 are :", S8) # It will produce error as that TypeError: unhashable type: 'list'
# set elements must be immutable
# But lists and dictionaries are mutable,
# so they can’t be set elements:
Size of Set : Python len( ) function is used to get the length of the Set. It takes
Set as an argument and returns its length.
E.g : SizeofSet.py
Set = set( ) OUTPUT
size = len(Set)
print (size) 0
Set1 = {(1,2,3,5,6)} # Takes whole tuple as one element
size = len(Set1)
print (size) 1
Set2 = {(1,2,3,5,6), (1,2,3,5,6)} # Repeated elements not counted
size = len(Set2)
print (size) 1
Set3 ={ 1,2,3,'a',7,'b',2,'a'} # Repeated elements not counted
size = len(Set3)
print (size) 6
Access Items in a Set
You cannot access items in a set by referring to an index or a key.
But you can loop through the set items using a for loop, or ask if a specified value
is present in a set, by using the in keyword.
S1 = { 5 , 10 , 15 ,9, 15 }
S2 = { 1,2,3,10}
print(" \n Elements of S1 are :", S1) Elements of S1 are : {9, 10, 5, 15}
for i in S1:
print(i) # we can iterate through elements of a set 9
10
# S1[4]=6 Assigment is not supported by sets 5
# TypeError: 'set' object does not support 15
item assignment,
So first change Set into list or tuple
L1 = list (S1)
L1[0] = 12
print(" \n Updated elements of L1 are :", L1) # element changed Updated elements of L1 are : [12, 10, 5, 15]
S1=set(L1) # changing list back into set
print(" \n Updated elements of S1 are :", S1) Updated elements of S1 are : {10, 12, 5, 15}
print ("Union of Set S1 and Set S2") Union of Set S1 and Set S2
print(S1.union(S2)) {1, 2, 3, 5, 9, 10, 17}
print ("Intersection of Set S1 and Set S2") Intersection of Set S1 and Set S2
print(S1.intersection(S2)) {10}
print ("Difference of Set S1 and Set S2") Difference of Set S1 and Set S2
print(S1.difference(S2)) {9, 5, 17}
print ( " Adding elements of set S2 into Set S1") Adding elements of set S2 into Set S1
S1.update(S2)
print(S1) # this will add more than one element {1, 2, 3, 5, 9, 10, 17}
Difference between, list , and tuple Set and dictionary
List Tuple Set Dictionary
list is an ordered A tuple is an ordered A set is an unordered A Dictionary is ordered
collection of collection of collection of unique collection of key-value pairs
elements. elements. elements. (Python 3.7 and above)
The list can be A tuple can be The set can be The dictionary can be
represented by [ ] represented by ( ) represented by { } represented by { }
The list allows Tuple allows The Set will not allow The dictionary doesn’t allow
duplicate elements duplicate elements duplicate elements duplicate keys.
A list can be created Tuple can be created
A set can be created A dictionary can be created
using the list() using the tuple()
using the set() function using the dict() function.
function function.
A set is mutable but A dictionary is mutable, its
A list is mutable A tuple is immutable its elements are Keys are not duplicated and
immutable are immutable.
Creating an empty Creating an empty Creating a set
Creating an empty dictionary
list Tuple
a=set()
d={}
l=[] t=() b=set(a)