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

Unit 4 Data Structure Stds in Python

This document provides an overview of data structures in Python, including lists, arrays, tuples, and dictionaries, highlighting their characteristics and advantages. It explains concepts such as mutability, order, and various operations that can be performed on these data structures. Additionally, it includes examples of how to create and manipulate arrays and lists in Python.

Uploaded by

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

Unit 4 Data Structure Stds in Python

This document provides an overview of data structures in Python, including lists, arrays, tuples, and dictionaries, highlighting their characteristics and advantages. It explains concepts such as mutability, order, and various operations that can be performed on these data structures. Additionally, it includes examples of how to create and manipulate arrays and lists in Python.

Uploaded by

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

Unit 4

Data structure in Python


Data structure : Data Structures are a way of organizing data so that it can be accessed more
efficiently depending upon the situation. Data Structures are fundamentals of any programming
language around which a program is built. The basic Python data structures in Python include list,
set, tuples, and dictionary. Each of the data structures is unique in its own way.
The data structures differ based on mutability and order. Mutability refers to the ability to change
an object after its creation. Mutable objects can be modified, added, or deleted after they’ve been
created, while immutable objects cannot be modified after their creation. Order, in this context,
relates to whether the position of an element can be used to access the element.
Advantages /Characteristics of data structure : Some of these advantages are:
1. Efficient Storage : Data structures provide efficient storage by organizing the data effectively,
which facilitates quick retrieval and maintenance of the data in the system.
2. Easy Data Processing : Data structures simplify data processing and enable faster sorting and
searching for specific data within a large data set..
3. Develop Algorithms : Algorithms for data structures help organize and access information in a
structured manner.
4. Reusability of Data : One of the fundamental advantages of data structure is that it offers data
reusability. It enables the creation of data in specific formats, which can then be stored in libraries,
allowing different clients to utilize and access the data as needed.
5. Supports Data Abstraction :The abstract data type in data structures helps support data
abstraction. Data abstraction is the process of hiding internal functions and displaying relevant and
basic information.
6. Saves Programmer’s Time :Data structures streamline the process of organizing and accessing
data, which helps save time. Developers can access data quickly and efficiently without having to
manually search through large amounts of data by selecting the appropriate data structure for their
program.
7. Increased Data Security :You can implement security features into data structures to ensure
data integrity and application security..
Array : An array is a collection of items of the same variable type that are stored at contiguous
memory locations. Each item in an array is indexed starting with 0 and elements of an array is
accessed through this index. Items stored in an array are called an elements and they can be of any
type including integers, floats, strings, etc.
Advantages /Features :
1. . Arrays are useful to handle a collection of elements like a group of numbers or characters..
2. The size of array is not fixed in Python . Hence we do not need to specify how many elements
we are going to store into an array in the beginning.
3. Arrays can grow and shrink in memory dynamically during run time.
4. When dealing with huge number of elements , arrays use less memory than lists and offer faster
execution than lists
Operations on Array in Python : Below are some operations that can be performed in an array:
 append()
 insert()
 pop ( )
 remove()
 index()
 reverse()
Creating an array
Unlike other programming languages like C++ or Java, Python does not have built-in
support for arrays. To create an array in Python, import the array module and use its array()
function. The array( ) function accepts typecode and initializer as a parameter value and returns an
object of array class. There are three ways to import the array module into our program.
1. import array
The syntax of creating array in this case will be :
a = array.array ( ‘i’, [ 1,2,3,4])
This creates an array with name ‘a’ with integer type elements 1,2,3 4 .Here the first array
represents the module name and next ‘array’ represents the class name for which object is created.
2. import array as ar
This second way of importing array module gives array an alias name ‘arr’ .Hence we can refer to
the array class of ‘ar’ module as :
a = ar.array ( ‘i’, [ 1,2,3,4])

3. from array import *


The general syntax of creating array in this case will be :
a = array ( ‘i’, [ 1,2,3,4])
Using thirds way for importing the array module the genral syntax for crating of an array is :
a = array ( type code, [Elements] )
The type codes are of various types. In above examples , it is ‘i’ which represents integer type
where we can store integers.
Various type codes to create an array are :

type code Python data type Byte size


'b' signed integer 1
'B' unsigned integer 1
'u' Unicode character 2
'h' signed integer 2
'H' unsigned integer 2
'i' signed integer 2
'I' unsigned integer 2
'l' signed integer 4
'L' unsigned integer 4
'q' signed integer 8
'Q' unsigned integer 8
'f' floating point 4
'd' floating point 8

Example : Program to show creation of array and display it Array1.py

from array import *


a = array('i', [1, 2, 3]) OUTPUT
print("The new created array 1 is : ", end=" ")
for n in a :
print( n, end=" ") The new created array 1 is : 1 2 3

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

Example : Program to access elements of array Accessing of Array.py


from array import *
a = array( 'i', [1, 2, 3,4,5,6,7,]) OUTPUT
print( " Display array", end = " ")
for i in a :
Display array 1 2 3 4 5 6 7
print( i, end=" ")
print( " \n Sliced array A :", end = " ")
b = a [1:4]
for i in b :
print( i, end=" ") Sliced array A: 2 3 4
print( " \n Sliced array B :", end = " ")
b = a [:-4]
for i in b :
Sliced array B : 2 1 2 3
print( i, end=" ")
print( " \nSliced array C :", end = " ")
b=a[-4:]
for i in b : Sliced array C : 4 5 6 7
print( i, end=" ")
print( " \nAccessing elements of Array", end = " ") Accessing elements of Array
print ( " \n First Element of Array is ", a[0]) First Element of Array is 1
print ( " \n Third Element of Array is ", a[2])
Third Element of Array is 3
a[6]=8 # Update operation
print( " Display updated Array ", end = " ")
for i in a :
print( i, end=" ")
Display updated Array 1 2 3 4 5 6 8
List : List is one of the 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 list are separated by comma ( , ) and enclosed within
the square brackets ( [ ] ).
E.g :
List1 = [ 1, 3, 5, 89 ]
List2 = [" Anas", 18, "Bariz", 27.5]

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

print(" \n Taking input from Keyboard ")


L7=list(input(" \n Enter elements of List7 :"))
print(" \n Elements of L7 are :", L7)
L8= eval(input(" \n Enter elements of List8 :"))
print(" \n Elements of L7 are :", L8)

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

print( " \n Elements of List L1 :", L1) Elements of List L1 : [1, 2, 3, 4, 5, 6, 7, 8]


print( " ")
print( " Using for Loop to display Elements of List L1 :") Using for Loop to display Elements of List L1 :
for i in L1 :
print( i, end=" ") 12345678
print( " \n Elements of List L2 :", L2) Elements of List L2 : [1, 2, ['Apple', 'For'], ['Pear'], 4]
print(" The value of fourth Element in L1 is :" , L1[3]) The value of fourth Element in L1 is : 4
print(" The value of fourth Element in L2 is :" , L2[3]) The value of fourth Element in L2 is : ['Pear']
print(" The value of first item in third Element in L2 is :" , The value of first item in third Element in L2 is :
L2[2][0]) Apple
print(" Sliced List L1 with step of 2 will be as : ", Sliced List L1 with step of 2 will be as : [1, 3, 5, 7]
L1[0:7:2])
print(" Elements of List L1 with -ve indices will be as : ", Elements of List L1 with -ve indices will be as :
L1[-8:]) [1, 2, 3, 4, 5, 6, 7, 8]
print("\n Slice operation") Slice operation
L3=L1[3:6]
print(" Elements of Slices array L3 are : ", L3) Elements of Slices array L3 are : [4, 5, 6]
print("\n Update operation") Update operation
L1[7]=9
print( " Display updated List L1 : ", L1) Display updated List L1 : [1, 2, 3, 4, 5, 6, 7, 9]
L2[2][1]='Banana'
print( " Display updated List L 2 : ", L2) Display updated List L1 : [1, 2, ['Apple', 'Banana'],
['Pear'], 4]

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

3. Using Built-in function tuple ( )


< tuple_name> = ( ) # This creates an empty tuple
4. Creating a tuple with a single element :
< tuple_name> = ( 2024 , )
In this case we to include a final comma after element .It is mandatory , otherwise Python
will not interpret it as a tuple , rather a regular value enclosed in parenthesis.
Example : # Program to show creation of Tuple CreatingTuple.py

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

T1 = ( 1,2,3,4,5,6,7,8) # single dimensional list OUTPUT


T2 = (1, 2, ['Apple', 'For'],('Pear', 'Banana'), 4)
# Multi dimensional Tuple / Nested
print( " \n Elements of Tuple T1 :", T1, end = " ") Elements of Tuple T1 : (1, 2, 3, 4, 5, 6, 7, 8)
print( " ")
print( "\n Using for Loop to display Elements of Tuple T1 :") Using for Loop to display Elements of Tuple T1 :
for i in T1 : 12345678
print( i, end = " ")
print( " \n Elements of Tuple T2 :", T2)
Elements of Tuple T2 : (1, 2, ['Apple', 'For'], ('Pear',
print(" The value of fourth Element in T1 is :" , T1[3]) 'Banana'), 4)
print(" The value of fourth Element in T2 is :" , T2[3]) The value of fourth Element in T1 is : 4
The value of fourth Element in T2 is : ('Pear',
print(" The value of first item in third Element in L2 is :" , 'Banana')
T2[2][0]) The value of first item in third Element in L2 is :
print( " Access all the Elements of Tuple T1 upto Fourth Apple
Element :") Access all the Elements of Tuple T1 upto Fourth
print(" The value of upto fourth Element in Tuple T1 is :" , Element :
T1[0:4]) The value of upto fourth Element in Tuple T1 is : (1,
2, 3, 4)
print(" Sliced Tuple T1 with step of 2 will be as : ",
T1[0:7:2]) Sliced List T1 with step of 2 will be as : (1, 3, 5, 7)

print(" Elements of Tuple T1 with -ve indices will be as : ",


T1[-8:]) Elements of List L1 with -ve indices will be as : (1,
print("\n Slice operation") 2, 3, 4, 5, 6, 7, 8)
T3=T1[3:6] Slice operation
print(" Elements of Sliced array T3=T1[3:6] are : ", T3)
Elements of Sliced array T3=T1[3:6] are : (4, 5, 6)

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 ( ) .

# Program to show creation of Dictionary Creating Dictionary.py


D1 = { 'a' : 11 , 'b': 12, 'c' : [11, 12,'d'], 'd':{'e':13}}
# This is Nested Dictionary also
D2 = { 1: 'one', (1,2,3):'two', 2.2 :'Float'}
print(" \n Elements of D1 are :", D1, " \n Elements of D2", D2) Elements of D1 are : {'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 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.

E.g : SizeofDictionary.py OUTPUT


Dict1 = { }
size = len(Dict1)
print (size) 0
Dict2 = (1: ‘a’, 2:’b’, 3:’c’, 4:'c' )
print (len(Dict2)) 4

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

D1 = { 'a' : 11 , 'b': 12, 'c' : [11, 12,'d'], 'd':{'e':13}}


D2 = { 1: 'one', (1,2,3):'two', 2.2 :'Float'}

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}

Accessing elements of dictionary through in built


print(" \n Accessing elements of dictionary through in built
functions :
functions :")
dict_keys(['a', 'b', 'c', 'd'])
print(D1.keys ( ) ) # It returns keys of the dictionary items only
print(D1.values ( ) ) # It returns values of keys of the dictionary . dict_values([11, 12, [11, 12, 'd'], {'e': 13}])
print(D1.items ( ) ) # It returns key-value pairs of the dictionary. dict_items([('a', 11), ('b', 12), ('c', [11, 12, 'd']),
('d', {'e': 13})])

print(" \n Accessing elements of D1 :") Accessing elements of D1 :


print (" First value :", D1['a'], "\nThird Value :",D1['c']) First value: 11
Third Value : [11, 12, 'd']

print(" \n Accessing elements of D2 :")


Accessing elements of D2 :
print(" First value : ",D2[1], " \nLast value :",D2[2.2])
First value : one
Last value : Float

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"}

2. Using Built-in function set ( )


< Set _name> = set ( ) .
E.g : my_stds = [122,132,111]
S3= set( my_stds)
3. Empty Set : This can be created by just using set function with nothing inside them.
S4 = set ( )
# Program to show creation of Set Creatingset.Py

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.

# Program to access the elements of Set Accesing of Set.py

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)

You might also like