0% found this document useful (0 votes)
20 views19 pages

PYTHON Unit 4 Answer

The document provides a comprehensive question bank for Python programming, covering topics such as bubble sort, tuples, dictionaries, and list operations. It includes code examples, explanations of methods, and operations for each data structure, as well as comparisons between them. Additionally, it demonstrates how to manipulate and access elements in these data structures through various programming techniques.

Uploaded by

akashpalani6065
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views19 pages

PYTHON Unit 4 Answer

The document provides a comprehensive question bank for Python programming, covering topics such as bubble sort, tuples, dictionaries, and list operations. It includes code examples, explanations of methods, and operations for each data structure, as well as comparisons between them. Additionally, it demonstrates how to manipulate and access elements in these data structures through various programming techniques.

Uploaded by

akashpalani6065
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 19

PYTHON

UNIT 4 QUESTION BANK ANSWER


PART B

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

3. How does make a copy of dictionary using copy( ) method?


 Python dictionary is an unordered collection of items. While other compound data
types have only value as an element, a dictionary has a key: value pair.
 It returns copy of the dictionary, here copy of dictionary ‘a’ get stored in to dictionary
‘b’
Syntax:
new_dict = original_dict.copy()

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)

(b) Without Parentheses (Comma-Separated Values)


t2 = 1, 2, 3
print(t2)
# Output: (1, 2, 3)

(c) Single Element Tuple (Must use comma)


t3 = (5,) # Tuple with one item
print(t3)
# Output: (5,)
t4 = (5) # Not a tuple, just an integer
print(type(t4))
# Output: <class 'int'>

(d) Using tuple() Constructor


t5 = tuple([100, 200, 300])
print(t5)
# Output: (100, 200, 300)
Tuple Assignment
Tuple assignment allows variables on the left of an assignment operator and
values of tuple on the right of the assignment operator.

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

Swapping using tuple assignment:


a=20
b=50
(a,b)=(b,a)
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.

1. Accessing Elements Using Indexing


 Indexing allows you to access a specific element by its position in the tuple.
# Example Tuple
t = (10, 20, 30, 40, 50)
# Accessing elements using index
print(t[0]) # Output: 10
print(t[2]) # Output: 30
print(t[4]) # Output: 50
 You can use negative indexing to access elements from the end of the tuple.
print(t[-1]) # Output: 50 (last element)
print(t[-2]) # Output: 40 (second last element)

2. Accessing Elements Using Slicing


 Slicing allows you to access a range of elements in the tuple.
# Example Tuple
t = (10, 20, 30, 40, 50)
# Accessing a range of elements using slicing
print(t[1:4])
print(t[:3])
print(t[2:])
print(t[-3:])

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

3. Accessing Single and Multiple Elements in Nested Tuples


If the tuple contains another tuple or list, you can access the inner elements by chaining
index access.

# Nested Tuple
nested_tuple = (1, (2, 3), 4)
# Accessing the inner tuple
print(nested_tuple[1])

# Output: (2, 3) - access the second element (which is a tuple)


print(nested_tuple[1][0])

# Output: 2 - access the first element of the inner tuple.

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

5. Explain the basic Tuple operations with examples.

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]

8.Write a Python program for adding elements to a dictionary.


Add elements to a dictionary using the following methods:
1. Using square brackets ([]) to assign a new key-value pair.
2. Using the update() method to add multiple key-value pairs.
Creating a dictionary
a={1:”one”,2:”two”}
print(a)
{1: ‘one’, 2: ‘two’}
Update
a[1]=”ONE”
print(a)
{1: ‘ONE’, 2: ‘two’}
Add element
a[3]=”three”
print(a)
{1: ‘ONE’, 2: ‘two’, 3: ‘three’}
9.Describe the methods and operations of Dictionaries.

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.

11.Demonstrate the basic list operations in detail with necessary programs.


List is an ordered sequence of items. Values in the list are called elements / items.
It can be written as a list of comma-separated items (values) between square
brackets [ ]. Items in the lists can be of different data types.

Operation Example Output

Create a List a = [2, 3, 4, 5, 6, 7, 8, 9, 10] [2, 3, 4, 5, 6, 7, 8, 9, 10]

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]

Concatenation b = [20, 30] print(a + b) [2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 30]

Repetition print(b * 3) [20, 30, 20, 30, 20, 30]

Updating a[2] = 100 print(a) [2, 3, 100, 5, 6, 7, 8, 9, 10]

Membership print(5 in a) True


print(100 in a) False
print(2 not in a) False
Comparison b = [2, 3, 4] print(a == b) False
print(a != b) True

12.Illustrate negative indexing in list with an example


Negative indexing allows you to access elements from the end of the list in
Python.

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.

Extracting Second Half of a List Using Slicing


fruits = ['apple', 'banana', 'cherry', 'date', 'elderberry', 'fig', 'grape']
# Get the midpoint of the list
mid = len(fruits) // 2
# Slice from midpoint to end
second_half = fruits[mid:]
print("Second half of the list:", second_half)
Output
Second half of the list: ['date', 'elderberry', 'fig', 'grape']

17.Compare and contrast insert() and append() in terms of performance and


use case.
Feature append() insert()
Adds an element at the end of Inserts an element at a specific
Definition
the list position
Syntax list.append(element) list.insert(index, element)
When you want to add at the When you want to add at a certain
Use Case
end position
Slower – O(n) (needs shifting
Performance Faster – O(1)
items)
Example a.append(10) ➝ [1, 2, 10] a.insert(1, 99) ➝ [1, 99, 2]
Feature append() insert()
Modifies list? Yes Yes

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

You might also like