Unit 4 Final
Unit 4 Final
DATA STRUCTURES
Ex:
student = [556, ‚Mothi‛, 84, 96, 84, 75, 84 ]
print(student)
print(student[0]) # Access 0th element
print(student[0:2]) # Access 0th to 1st elements
print(student[2: ]) # Access 2nd to end of list elements
print(student[ :3]) # Access starting to 2nd elements
print(student[ : ]) # Access starting to ending elements
print(student[-1]) # Access last index value
print(student[-1:-7:-1]) # Access elements in reverse order
Output:
[556, ‚Mothi‛, 84, 96, 84, 75, 84]
Mothi
[556, ‚Mothi‛]
[84, 96, 84, 75, 84]
[556, ‚Mothi‛, 84]
[556, ‚Mothi‛, 84, 96, 84, 75, 84]
84
[84, 75, 84, 96, 84, ‚Mothi‛]
Membership in Lists:
We can check if an element is a member of a list by using „in‟ and „not in‟ operator.
If the element is a member of the list, then „in‟ operator returns True otherwise returns False.
If the element is not in the list, then „not in‟ operator returns True otherwise returns False.
Example:
x=[10,20,30,45,55,65]
a=20
print(a in x) # True
a=25
print(a in x) #
False a=45
print(a not in x) #
False a=40
print(a not in x) # True
Original List:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Sliced Lists:
[4, 6, 8]
[1, 3, 5, 7, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
List = [‘ccn’,’branch’,’python’]
# Show original list Original List:
print("\nOriginal List:\n", List) [‘ccn’,’branch’,’python’]
print("\nSliced Lists: ") Sliced Lists:
# Display sliced list [‘python’,’branch’,‘ccn’]
print(List[::-1]) [‘python’]
# Display sliced list
[‘python’] print(List[::-3])
# Display sliced
list
print(List[:1:-2])
A=[1,3,13,45,56,]
A= [1, 3, 13, 45, 56, 62,
B=[62,45,58,89,13,3,56,1]
45, 58, 89, 13, 3, 56, 1]
A.extend(B)
print("A=",A) B= [62, 45, 58, 89, 13,
print("B=",B) 3, 56, 1]
Ex-1: Output:
numbers = [1,2,3,4,5] 12345
for i in numbers:
print(i,end="")
Ex-2: Output:
list = [1, 3, 5, 7, 9] 1
# Getting length of list 3
length = len(list) 5
i = 0 7
9
while i < length:
print(list[i])
i += 1
Explain mutability:
A mutable object can be changed but an immutable object cannot.As you know, an integer
is an immutable type in Python.Let me demonstrate how you can realize this by running some
experiments. First, let’s create two variables a and b. The variable a is an integer, and the
variable b refers to a:
a=1
b=a
Now both a and b point to the same memory address. In other words, the id()function should
return the same ID for both integers:
a=1
b=a
print(id(a) == id(b))
Output:
True
And this is indeed the case.
But now, let’s change the value of a:
a = 10
Now, let’s compare the IDs of a and b again:
print(id(a) == id(b))
Output:
False
The IDs don’t match anymore. This is because now a points to a different integer object. In
other words, the integer object 1 itself never changed. But the variable a that pointed to it now
points to another integer object called 10.
So even though it looks as if you updated the original integer object, you did not. This is due
to the fact that an integer is an immutable type in Python, and you cannot change an
immutable object after creation.
Now, let’s repeat a similar experiment with a mutable object.
For example, let’s create a list:
nums = [1, 2, 3]
l = nums
Now, let’s compare the IDs of the lists:
print(id(nums) == id(l))
Output:
True
Now, let’s modify the list object by removing its first element:
del nums[0]
Let’s then check if the IDs of the two lists still match:
print(id(nums) == id(l))
Result:
True
And they do! This means nums and l still point to the same list object in memory.
To make the point clear, let’s print the contents of nums and l:
print(nums
) print(l)
Output:
[2, 3]
[2, 3]
print y # [10,20,30,40,50,0]
When we clone a list like this, a separate copy of all the elements is stored into „y‟.
The lists „x‟ and „y‟ are independent lists. Hence, any modifications to „x‟ will not affect „y‟
and vice versa.
Explain list parameters:
In python we can pass list as a parameters. in arguments what type of data is passed to
function, inside function also treated as same type.
syntax: list(iterable)
here iterable means sequence of elements.
here if we cannot pass any values of list function , then it doesn’t shown an error . we can pass list
values to a function
Example 1:To pass a list to function. OUTPUT:
>>>def color(b):
>>> for i in b:
>>> print(i)
>>>crl=["red","blue","green"]
>>>color(crl)
Example 2: OUTPUT 2:
>>>def value(b):
>>> print(b)
>>>l=[10,20,3+5j,"mouni"]
>>>value(l)
Example 3: OUTPUT3:
>>>def sort(a,b):
>>> c=a+b
>>> c.sort()
>>> return c
>>>a1=[10,5,25,30,4]
>>>a2=[6,7,40,35,71]
>>>res=sorting(a1,a2)
>>>print(res)
the above example for to pass two different lists to function.that are a1 and a2
Example 4: OUTPUT4:
>>>def count(b):
>>> even=0
>>> odd=0
>>> for i in b:
>>> if i%2==0:
>>> even+=1
>>> else:
>>> odd+=1
>>> return even,odd
>>>a=[5,10,7,8,6,9,13]
>>>even,odd=count(a)
>>>print("even is {} and odd is {}".format(even,odd))
The above example to pass a list to function andit returns to more than one
value.
Example 5: OUTPUT5:
>>>def expression(n):
>>> a=sum(n)
>>> return a
>>>x=[10,20,30,40,50]
>>>r=expression(x)
>>>print("the sum of list is ",r)
print(matrix)
TUPLES:
A Tuple is a python sequence which stores a group of elements or items. Tuples are
similar to lists but the main difference is tuples are immutable whereas lists are mutable. Once
we create a tuple we cannot modify its elements. Hence, we cannot perform operations
like append(), extend(), insert(), remove(), pop() and clear() on tuples.
Tuples are generally used to store data which should not be modified and retrieve that data on
demand.
Creating Tuples:
We can create a tuple by writing elements separated by commas inside parentheses( ).
The elements can be same datatype or different types.
tup=(10, 20, 31.5, ‘aditya’)
If we do not mention any brackets and write the elements separating them by comma, then they
are taken by default as a tuple.tup= 10, 20, 34, 47
It is possible to create a tuple from a list. This is done by converting a list into a tuple
using tuple function.
t=tuple(range(2,11,2))
print(t) # display (2,4,6,8,10)
Another way to create a tuple by using range( ) function that returns a sequence.
Tuple Assignment:
In python, we can perform tuple assignment which is a quite useful feature. We can create a
tuple in various ways We also call this feature unpacking of tuple.
The process of assigning values to a tuple is known as packing. In unpacking, we basically
extract the values of the tuple into a single variable.
Tuple Packing (Creating Tuples)
We can create a tuple in various ways by using different types of elements. Since a tuple can
contain all elements of the same data type as well as of mixed data types as well. Let us look at few
examples of creating tuples in python which we consider as packing.
Example 1: Tuple with integers as elements
>>>tup = (22, 33, 5, 23)
>>>tup
(22, 33, 5, 23)
Example 2: Tuple with mixed data type
>>>tup2 = ('hi', 11, 45.7)
>>>tup2
('hi', 11, 45.7)
Example 3: Tuple with a tuple as an element
>>>tup3 = (55, (6, 'hi'), 67)
>>>tup3
(55, (6, 'hi'), 67)
Example 4: Tuple with a list as an element
>>>tup3 = (55, [6, 9], 67)
>>>tup3
(55, [6, 9], 67)
If there is only a single element in a tuple we should end it with a comma. Since writing, just the
element inside the parenthesis will be considered as an integer.
For example,
>>>tup=(90)
>>>tup
90
>>>type(tup)
<class 'int'>
Correct way of defining a tuple with single element is as follows:
>>>tup=(90,)
>>>tup
(90,)
>>>type(tup)
<class 'tuple'>
Moreover, if you write any sequence separated by commas, python considers it as a tuple.
For example,
>>> seq = 22, 4, 56
>>>seq
(22, 4, 56)
>>>type(seq)
<class 'tuple'>
Tuple Assignment (Unpacking)
Unpacking or tuple assignment is the process that assigns the values on the right-hand side to
the left-hand side variables. In unpacking, we basically extract the values of the tuple into a single
variable.
NOTE : In unpacking of tuple number of variables on left-hand side should be equal to number of
values in given tuple a.
Example 1
>>>(n1, n2) = (99, 7)
>>>print(n1)
99
>>>print(n2)
7
Example 2
>>>tup1 = (8, 99, 90, 6.7)
>>>(roll no., english, maths, GPA) = tup1
>>>print(english)
99
>>>print(roll no.)
8
>>>print(GPA)
6.7
>>>print(maths)
90
Example 3
>>> (num1, num2, num3, num4, num5) = (88, 9.8, 6.8, 1)
#this gives an error as the variables on the left are more than the number of elements in
the tuple
Value Error: not enough values to unpack (expected 5, got 4)
Using Astersik(*)
fruits = ("apple", "banana", "cherry", "strawberry", "raspberry")
(green, yellow, *red) = fruits
print(green)
print(yellow)
print(red)
output: apple
banana
["cherry", "strawberry", "raspberry"]
Tuple comprehension
Comprehension is a technique used to create a new sequence from already existing sequence
with short and concise way. there is no tuple comprehension in python because comprehension
requires mutable data type. in python there is no syntax for tuple comprehension but indirectly we can
perform tuple comprehension. it is done by using the following types
1. wrapping generator comprehension
2. list comprehension
Example 1:
>>>t1=(5,10,15,24,26)
>>>result=(x for x in t1 if x%5==0)
>>>print(result)
>>> <generator object <genexpr> at 0x000001D48DEC6F80>
Example 2:
>>>t1=(5,10,15,24,26)
>>>result=tuple(x for x in t1 if x%5==0)
>>>print(result)
>>>(5,10,15)
Example 3:
>>>t1=[1,2,3,4,5]
>>>r=tuple([value*10 for value in t1])
>>>print(r)
>>>(10,20,30,40,50)
Dictionary:
A dictionary represents a group of elements arranged in the form of key-value pairs.
The first element is considered as „key‟ and the immediate next element is taken as its
„value‟. The key and its value are separated by a colon (:). All the key-value pairs in a dictionary
are inserted in curly braces { }.
• Keys should be unique. It means, duplicate keys are not allowed. If we enter same key
again, the old key will be overwritten and only the new key will be available.
• Keys should be immutable type. For example, we can use a number, string or tuples
as keys since they are immutable. We cannot use lists or dictionaries as keys. If they
are used as keys, we will get „TypeError‟.
Dict = {}
print(Dict)
# Creating a Dictionary
print(Dict)
# Creating a Dictionary
print(Dict)
def Convert(a):
it = iter(a)
res_dct = dict(zip(it,
it)) return res_dct
list = ['GERMANY', 'Berlin', 'INDIA', 'New Delhi', 'USA',
'Washingtone','FRANCE','Paris']
print(Convert(list))
Output:
{'GERMANY': 'Berlin', 'INDIA': 'New Delhi', 'USA': 'Washington', 'FRANCE': 'Paris'}
dic={'A':100,'B':540,'C':239}
print("Total sum of values in the dictionary:")
print(sum(dic.values()))
output:
Total sum of values in the dictionary:
879
4.42.2. Dictionary Operations And Methods:
Dictionary Operations:
Accessing Elements from Dictionary
While indexing is used with other data types to access values, a dictionary uses keys.
Keys can be used either inside square brackets [] or with the get() method.If we use the
square brackets [], KeyError is raised in case a key is not found in the dictionary. On the
other hand, the get() method returns None if the key is not found.
Dic={1:”apple”,2:”orange”,3:”grapes”}
Print(Dic[2])
>>Orange
Print(Dic.get(1))
>>apple
Adds a new pair of key and value to the dictionary, but in case that the key already exists in the
dictionary, we can update the value.
y = {}
y['one'] = 1
y['two'] = 2
print(y)
Output:{'one': 1, 'two': 2}
y['two'] = 'dos'
print(y)
Output:{'one': 1, 'two': 'dos'}
before, the key value should be an immutable data type, for that reason if you try to define a dictionary
with a mutable data type, Python will raise a TypeError: unhashable type exception.
del
Del statement can be used to remove an entry (key-value pair) from a dictionary.
y = {'one': 1, 'two': 2}
print(y)
Output:{'one': 1, 'two': 2}
del y['two']
print(y)
Output:{'one': 1}
update
This method updates a first dictionary with all the key-value pairs of a second dictionary. Keys that are
common to both dictionaries, the values from the second dictionary override those of the first.
x = {'one': 0, 'two': 2}
y = {'one': 1, 'three': 3}
x.update(y)
print(x)
Output:{'one': 1, 'two': 2, 'three': 3}
Dictionary Methods:
for loop is very convenient to retrieve the elements of a dictionary. Let‟s take a simple
dictionary that contains color code and its name as:
colors = { 'r':"RED", 'g':"GREEN", 'b':"BLUE", 'w':"WHITE" }
Here, „r‟, „g‟, „b‟ represents keys and „RED‟, „GREEN‟, „BLUE‟ and „WHITE‟ indicate
values.
4.12.2 dictionary comprehension:
Here we have two lists named keys and value and we are iterating over them with the help
of zip()
keys =
['a','b','c','d','e']
values = [1,2,3,4,5]
myDict = { k:v for (k,v) in zip(keys,
values)} print (myDict)
output:
{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
Using fromkeys() Method
Here we are using the fromkeys() method that returns a dictionary
with specific keys and values.
dic=dict.fromkeys(range(5),
True) print(dic)
Output:
{0: True, 1: True, 2: True, 3: True, 4: True}
Using dictionary comprehension make dictionary
Example 1:
Output :
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Using conditional statements in dictionary comprehension
Output :
{0: 0, 8: 512, 2: 8, 4: 64, 6: 216}
SET:
Set is another data structure supported by python. Basically, sets are same as lists but with a
difference that sets are with no duplicate entries. Technically a set is a mutable and an unordered
collection of items. This means that we can easily add or remove items from it.
Creating a Set:
A set is created by placing all the elements inside curly brackets {}. Separated by comma or
by using the built-in function set( ).
Example:
set={1,3,4,5,1,6}
print(set)
output:{1,3,4,5,6}
Updating a set:
Since sets are unordered, indexing has no meaning. Set operations do not allow users to
access or change an element using indexing or slicing.
Methods on set:
• len(S): Returns the number of elements in set S.
Program Output
A={1,2,3,4,5,6,7}
7
print(len(A))
• S1.issubset(S2): Test whether every element in S1 is in S2.
Program Output
A={1,2,3,4}
B={1,2,3,4,5,6,7} True
print(A.issubset(B))
• S1.issuperset(S2): Test whether every element in S2 is in S1.
Program Output
A={1,2,3,4}
B={1,2,3,4,5,6,7} False
print(A.issuperset(B))
Program Output
A={1,2,3,4,5,6,7}
A.add(10) {1, 2, 3, 4, 5, 6, 7, 10}
print(A)