PYTHON Unit 4 Answer
PYTHON Unit 4 Answer
1. Write the program and perform the bubble sort on the elements
23,78,45,8,32,56?
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the
adjacent elements if they are in the wrong order.
Bubble Sort algorithm, sorts an array by repeatedly comparing adjacent elements and
swapping them if they are in the wrong order.
The algorithm iterates through the array multiple times, with each pass pushing the
largest unsorted element to its correct position at the end.
Code includes an optimization: if no swaps are made during a pass, the array is
already sorted, and the sorting process stops.
PROGRAM
def bubble_sort(arr):
n = len(arr)
# Traverse through all elements in the list
for i in range(n):
# Last i elements are already in place
for j in range(0, n - i - 1):
# Swap if the current element is greater than the next one
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
print(f"After pass {i + 1}: {arr}") # Show list after each pass
# Given list
arr = [23, 78, 45, 8, 32, 56]
print("Original array:", arr)
bubble_sort(arr)
print("Sorted array:", arr)
OUTPUT:
Pass 1 : [23, 45, 8, 32, 56, 78]
Pass 2 : [23, 8, 32, 45, 56, 78]
Pass 3 : [8, 23, 32, 45, 56, 78]
Pass 4 : [8, 23, 32, 45, 56, 78]
Pass 5 : [8, 23, 32, 45, 56, 78]
Pass 6 : [8, 23, 32, 45, 56, 78]
Sorted array: [8, 23, 32, 45, 56, 78]
2. Illustrate tuples as return values with examples.
A Tuple is a comma separated sequence of items. It is created with or
without ( ). A function can return one value. if you want to return more than one value
from a function. We can use tuple as return value.
Example :
def div(a,b):
r=a%b
q=a//b
return(r,q)
a=eval(input(“enter a value:”))
b=eval(input(“enter b value:”))
r,q=div(a,b)
print(“reminder:”,r)
print(“quotient:”,q)
Output:
enter a value:4
enter b value:3
reminder: 1
quotient: 1
Example
a={l: ‘ONE’. 2: ‘two’. 3: ‘three’}
b=a.copy()
print(b)
{1: ‘ONE’, 2: ‘two’. 3: ‘three’}
4. Illustrate the ways of creating the Tuple and the Tuple assignment with suitable
programs.
A tuple is an immutable linear data structure. Thus, in contrast to lists, once a tuple is
defined, it cannot be altered. Otherwise, tuples and lists are essentially the same. To
distinguish tuples from lists, tuples are denoted by parentheses instead of square brackets.
(a) Using Parentheses ()
t1 = (10, 20, 30)
print(t1)
# Output: (10, 20, 30)
Example:
Swapping using temporary variable:
a=20
b=50
temp = a
a=b
b = temp
print(“value after swapping is”,a,b)
OUTPUT: Value after swapping is 50 20
4. What are the accessing elements in a Tuple? Explain with suitable programs.
Accessing Elements in a Tuple
In Python, access elements in a tuple using indexing and slicing, just like with lists.
Tuples are ordered, so elements are stored in a sequence, and each element has an index
starting from 0.
OUTPUT:
Output: (20, 30, 40) - from index 1 to 3
Output: (10, 20, 30) - from start to index 2
Output: (30, 40, 50) - from index 2 to end
Output: (30, 40, 50) - from third-last to end
# Nested Tuple
nested_tuple = (1, (2, 3), 4)
# Accessing the inner tuple
print(nested_tuple[1])
4. Tuple Iteration
Iterate through a tuple using a loop.
# Example Tuple
t = (10, 20, 30, 40)
# Iterating through the tuple
for item in t:
print(item)
Output:
10
20
30
40
Operations on Tuples
1. Indexing
2. Slicing
3. Concatenation
4. Repetitions
5. Membership
6. Comparison
Creating a tuple
a=(20,40,60,”apple”,”ball”)
Indexing
print(a[0])
20
a[2]
60
Slicing
print(a[1:3])
(40,60)
Concatenation
b=(2,4)
print(a+b)
(20,40,60,”apple”,”ball”,2,4)
Repetition
print(b*2)
(2,4,2,4)
Membership
a=(2,3,4,5,6,7,8,9,10)
5 in a
True
100 in a
False
2 not in a
False
Comparison
a=(2,3,4,5,6,7,8,9,10)
b=(2,3,4)
a==b
False
a!=b
True
7.How can you pass list into function? Explain with example
In python, arguments are passed by reference. If any changes are done in the
parameter which refers within the function, then the changes also reflects back in the
calling function. When a list to a function is passed, the function gets a reference to
the list.
Passing a list as an argument actually passes a reference to the list, not a copy of
the list. Since lists are mutable, changes made to the elements referenced by the
parameter change the same list that the argument is referencing.
Example1 :
def remove(a):
a.remove(1)
a=[1,2,3,4,5]
remove(a)
print(a)
Output:
[2,3,4,5]
Example 2:
def inside(a):
for i in range(0,len(a),1):
a[i]=a[i]+10
print(“inside”,a)
a=[1,2,3,4,5]
inside(a)
print(“outside”,a)
Output
inside [11, 12, 13, 14, 15]
outside [11, 12, 13, 14, 15]
Operations on dictionary:
1. Accessing an element
2. Update
3. Add element
4. Membership
Creating a dictionary
a={1:”one”,2:”two”}
print(a)
{1: ‘one’, 2: ‘two’}
Accessing an element
a[1]
‘one’
a[0]
KeyError: 0
Update
a[1]=”ONE”
print(a)
{1: ‘ONE’, 2: ‘two’}
Add element
a[3]=”three”
print(a)
{1: ‘ONE’, 2: ‘two’, 3: ‘three’}
Membership
a={1: ‘ONE’, 2: ‘two’, 3: ‘three’}
1 in a
True
3 not in a
False
Methods on dictionary:
Method Example Output
a = {1: 'ONE', 2: 'two', 3: 'three'}
a.copy() {1: 'ONE', 2: 'two', 3: 'three'}
b = a.copy()
a = {1: 'ONE', 2: 'two', 3: 'three'} dict_items([(1, 'ONE'), (2,
a.items()
a.items() 'two'), (3, 'three')])
a = {1: 'ONE', 2: 'two', 3: 'three'}
a.keys() dict_keys([1, 2, 3])
a.keys()
a = {1: 'ONE', 2: 'two', 3: 'three'} dict_values(['ONE', 'two',
a.values()
a.values() 'three'])
a = {1: 'ONE', 2: 'two', 3: 'three'}
a.pop(key) 'three'
a.pop(3)
a.setdefault(key, a = {1: 'ONE', 2: 'two', 3: 'three'}
'four'
default) a.setdefault(4, 'four')
a = {1: 'ONE', 2: 'two', 3: 'three'}
{1: 'ONE', 2: 'two', 3: 'three', 4:
a.update(dictionary) b = {4: 'four'}
'four'}
a.update(b)
keys = ['apple', 'ball'] d = {'apple': 'for kids', 'ball': 'for
dict.fromkeys()
dict.fromkeys(keys, 'for kids') kids'}
a = {1: 'ONE', 2: 'two', 3: 'three'}
len(a) 3
len(a)
a = {1: 'ONE', 2: 'two', 3: 'three'}
a.clear() {}
a.clear()
a = {1: 'ONE', 2: 'two', 3: 'three'} Raises Name Error after
del(a)
del(a) deletion
10.Differentiate between the Tuple,List and Dictionary?
Feature Tuple List Dictionary
Ordered collection Ordered collection Unordered collection of
Definition
of elements. of elements. key-value pairs.
Syntax tuple = (1, 2, 3) list = [1, 2, 3] dict = {1: 'one', 2: 'two'}
Yes, maintains Yes, maintains
Order No, keys are unordered.
order. order.
Immutable (cannot Mutable (can
Mutability Mutable (can change).
change). change).
Can have Can have Keys must be unique;
Duplicates
duplicates. duplicates. values can be duplicates.
By index (e.g., By index (e.g.,
Accessing By key (e.g., d[1]).
t[0]). lst[0]).
Few methods (e.g., Many methods Many methods (e.g.,
Methods
count()). (e.g., append()). get(), pop()).
Slower for Slower lookup (due to
Performance Faster for iteration.
iteration. keys).
Use Case For constant data. For mutable data. For key-value pair data.
Indexing print(a[0]) 2
print(a[8]) 10
print(a[-1]) 10
Slicing print(a[0:3]) [2, 3, 4]
print(a[0:]) [2, 3, 4, 5, 6, 7, 8, 9, 10]
EXAMPLE:
a = [10, 20, 30, 40, 50]
# Accessing elements using negative indexing
print(a[-1]) # Last element
print(a[-2]) # Second last element
print(a[-3]) # Third last element
OUTPUT:
50
40
30
13.Create a python program where one list is aliased and another is cloned
and also perform the modification on both aliased and cloned list. Discuss the
effects of modifying the aliased and cloned list.
List Aliasing
Creating a copy of a list is called aliasing. When you create a copy both list will be
having same memory location. Changes in one list will affect another list. Aliasing
refers to having different names for same list values.
Example :
a= [10,20,30,40]
b=a
print (b)
a is b
b[2]=35
print(a)
print(b)
Output :
[10,20,30,40]
True
[10,20,30,40]
[10,20,35,40]
They are aliases for the same object. This phenomenon is known as aliasing. To
prevent aliasing, a new object can be created and the contents of the original can be
copied which is called cloning.
List Cloning
To avoid the disadvantages of copying we are using cloning. Creating a copy of a
same list of elements with two different memory locations is called cloning.
Changes in one list will not affect locations of another list.
Cloning is a process of making a copy of the list without modifying the original
list.
1. Slicing
2. list()method
3. copy() method
Cloning using Slicing
a=[1,2,3,4,5]
b=a[:]
print(b)
[1,2,3,4,5]
a is b
False
Cloning using List( ) method
a=[1,2,3,4,5]
b=list
print(b)
[1,2,3,4,5]
a is b
false
a[0]=100
print(a)
a=[100,2,3,4,5]
print(b)
b=[1,2,3,4,5]
Cloning using copy() method
a=[1,2,3,4,5]
b=a.copy()
print(b) [1, 2, 3, 4, 5]
a is b
False
Type Definition Effect When Modified
A new variable pointing to the same Changes made through one variable also
Aliased
memory location as the original list affect the other
A new copy of the original list stored at a Changes affect only the cloned list; the
Cloned
different memory location original remains unchanged
14.Describe the effects of modifying an element of an aliased list and how the
change affects the original list.
Aliasing means creating a new reference (not a copy) to the same list.
Any change made through one reference is reflected in the other because they
refer to the same memory location.
EXAMPLE:
original = [10, 20, 30]
alias = original # Aliasing the list
alias[1] = 99 # Modifying alias
print("Original:", original)
print("Alias:", alias)
Output:
Original: [10, 99, 30]
Alias: [10, 99, 30]
Operation Original List Alias List
After aliasing [10, 20, 30] [10, 20, 30]
After alias[1] = 99 [10, 99, 30] [10, 99, 30]
15.Write a python program that uses remove(), pop(), append() and insert() to
modify a list.
remove():
Example:
animal = [‘cat’, ‘dog’, ‘rabbit’]
animal.remove(‘rabbit’)
print(‘Updated animal list: ‘, animal)
Output:
Updated animal list: [‘cat’, ‘dog’]
Pop():
Example:
language = [‘Python’, ‘Java’, ‘C++’, ‘French’, ‘C’]
return_value = language.pop(3)
print(‘Return Value: ‘, return_value)
print(‘Updated List: ‘, language)
Output:
Return Value: French
Updated List: [‘Python’, ‘Java’, ‘C++’, ‘C’]
append():
Example :
animal = [‘cat’, ‘dog’, ‘rabbit’]
animal.append(‘goat’)
print(‘Updated animal list: ‘, animal)
Output:
Updated animal list: [‘cat’, ‘dog’, ‘rabbit’, ‘goat’]
insert():
Example:
vowel = [‘a’, ‘e’, ‘i’, ‘u’]
vowel.insert(3, ‘o’)
print(‘Updated List: ‘, vowel)
Output:
Updated List: [‘a’, ‘e’, ‘i’, ‘u’, ‘o’]
16.Given the list ['apple', 'banana', 'cherry', 'date', 'elderberry', 'fig', 'grape'],
use slicing to extract the second half of the list. Implement a solution to slice
the list and retrieve the second half of it.
Example Program
a = [1, 2, 3]
# append adds at the end
a.append(4)
print("After append:", a)
# insert adds at specific index
a.insert(1, 99)
print("After insert:", a)
Output:
After append: [1, 2, 3, 4]
After insert: [1, 99, 2, 3, 4]
PART C
1.Write code snippets in Python to perform the following
(i)Creating the list
(ii)Accessing elements in the list
(iii)Modifying elements in the list
(iv)Deleting the elements in the list