UNIT 3 DATA STRUCTERE IN PYTHON MARKS: 14
Marks:02
1)Write syntax for a method to sort a list.
Synatx:
list_name.sort()
Example
numbers.sort()
print(numbers)
2) What is dictionary?
Answer:
A dictionary is an unordered collection of key-value pairs, where each key is unique. It's
used to store data in a way that allows fast retrieval using a key.
Syntax: {key1: value1, key2: value2, ...}
Key Characteristics:
Unordered: The order of the key-value pairs doesn't matter.
Mutable: You can modify, add, or remove key-value pairs.
Indexed by key: Values are accessed via keys, not indexes.
13)Write down the output of the following Python code
>>>indices=['zero','one','two','three','four','five']
i) >>>indices[:4]
Output: ['zero', 'one', 'two', 'three']
ii) >>>indices[:-2]
Output:['zero', 'one', 'two', 'three']
Marks (4 to 6)
3) Write python program to perform following operations on set
OR
Write python program to perform following operations on Set (Instead of Tuple)
OR
List and explain any four built-in functions on set
i) Create set
ii) Access set Element
iii) Update set
Iv ) Delete set
. i) Create set of five elements
ii) Access set elements
iii) Update set by adding one element
iv) Remove one element from set.
Answer:
# i) Create a set of five elements
my_set = {1, 2, 3, 4, 5}
# ii) Access set elements
# Sets are unordered, so you can't access elements by index directly.
# But you can iterate over a set or use a loop.
for element in my_set:
print(element)
# iii) Update set by adding one element
my_set.add(6) # Adds the element 6 to the set
print("Updated set:", my_set)
# iv) Remove one element from set
my_set.remove(2) # Removes the element 2 from the set
print("Set after removal:", my_set)
4) What is the output of the following program?
dict1 = {‘Google’ : 1, ‘Facebook’ : 2, ‘Microsoft’ : 3}
dict2 = {‘GFG’ : 1, ‘Microsoft’ : 2, ‘Youtube’ : 3}
dict1⋅update(dict2);
for key, values in dictl⋅items( ):
print (key, values)
Answer:
Google 1
Facebook 2
Microsoft 2
GFG 1
Youtube 3
5(List data types used in python. Explain any two with example
List Data Types in Python:
1. List
2. Tuple
3. Set
4. Dictionary
5. String
1. List
A list is an ordered collection of items, which can be of different data types. Lists are
mutable (can be changed).
my_list = [1, "Hello", 3.14, True]
my_list.append("Python")
print(my_list)
#Output: [1, "Hello", 3.14, True, "Python"]
2. Tuple
A tuple is an ordered collection of items, similar to a list, but immutable (cannot be changed
after creation).
my_tuple = (1, "Hello", 3.14)
print(my_tuple)
# Output: (1, "Hello", 3.14)
6) Compare list and tuple (any four points)
Feature List Tuple
Syntax list1 = [1, 2, 3] tuple1 = (1, 2, 3)
Mutable ✅ Yes (can be changed) ❌ No (cannot be changed)
Performance Slower Faster (due to immutability)
Methods Available Many (like append(), remove()) Fewer methods
Use Case When data may change When data should stay constant
Memory Usage More Less
7) Write the output for the following if the variable course = “Python ”
OR
Explain indexing and slicing in list with example.
>>> course [ : 3 ]
>>> course [ 3 : ]
>>> course [ 2 : 2 ]
>>> course [ : ]
>>> course [ -1 ]
>>> course [ 1 ]
Answer:
Output: "Pyt"
Output: "hon"
Output: "" (empty string)
Output: "Python"
Output: "n"
Output: "y"
8) Explain four Buit-in tuple functions in python with example
ANSWER:
Built-in Tuple Functions (In Short):
1. len() – Returns number of elements
len((1, 2, 3)) → 3
2. max() – Returns largest value
max((5, 9, 1)) → 9
3. min() – Returns smallest value
min((5, 9, 1)) → 1
4. count() – Counts occurrences
(1, 2, 2, 3).count(2) → 2
9) Write the output of the following
i) >>> a=[2,5,1,3,6,9,7]
>>> a[2:6]=[2,4,9,0]
>>> print(a)
Output: [2, 5, 2, 4, 9, 0, 7]
ii) >>> b=[“Hello”,”Good”]
>>> b.append(“python”)
>>>print(b)
Output: ['Hello', 'Good', 'python']
iii) >>>t1=[3,5,6,7]
output: >>>print(t1[2])
>>>6
>>>print(t1[-1])
>>>7
>>>print(t1[2:])
>>>[6, 7]
>>>print(t1[:])
>>>[3, 5, 6, 7]
10)Write basis operations of list.
Answer:
Basic List Operations :
1. Create – my_list = [1, 2, 3]
2. Access – my_list[0] → 1
3. Modify – my_list[1] = 10
4. Add – append(), insert()
5. Remove – remove(), pop()
6. Length – len(my_list)
7. Slice – my_list[1:3]
8. Check – 2 in my_list
9. Sort – my_list.sort()
10. Loop – for i in my_list: print(i)
11) Compare list and dictionary. (Any 4 points)
List Dictionary
Ordered collection of items Collection of key-value pairs
Access by index Access by key
Syntax: [1, 2, 3] Syntax: {'a': 1, 'b': 2}
Keys must be unique
Duplicate items are allowed
12) Explain mutable and immutable data structures.
Mutable Data Structures
Definition: Their contents can be altered without creating a new object.
Common Examples:
o Lists (list)
o Dictionaries (dict)
o Sets (set)
a = [1, 2, 3]
b=a # b references the same list
a.append(4) # modify in place
print(b) # [1, 2, 3, 4]
Immutable Data Structures
Definition: Their contents cannot be changed once created. Any “modification” produces a
new object.
Common Examples:
o Integers (int)
o Floats (float)
o Strings (str)
o Tuples (tuple)
s = "hello"
t=s # t references the same string
s = s.upper() # creates a new string "HELLO"
print(t) # "hello"
Feature Mutable Immutable
❌ No (operations return
In-place change ✅ Yes (.append(), pop())
new)
Shared
C hanges visible to all refs Original stays unchanged
references
Collections you’ll update over time (buffers, Fixed data (keys in dicts,
Use cases
caches) constants)
13)Explain creating Dictionary and accessing Dictionary Elements with
example.
OR
Explain different functions or ways to remove key : value pair from Dictionary
Answer: A dictionary in Python is an unordered collection of key-value pairs. Here’s how
you can create one and access its elements:
Creating the Dictionary:
# Keys and values can be any immutable type (strings, numbers, tuples)
student = {
"name": "Alice",
"age": 23,
"major": "Physics"
All Operation in Example:
# 1. Create
product = {
"id": 101,
"name": "Laptop",
"price": 799.99,
"in_stock": True
# 2. Access
print(product["name"]) # Laptop
print(product.get("discount")) # None
print(product.get("discount", 0)) # 0
# 3. Iterate
for key, val in product.items():
print(f"{key}: {val}")
14)Write a python program to input any two tuples and interchange the
tuple variables.
# Input two tuples (enter in Python form, e.g. (1, 2, 3))
tuple1 = eval(input("Enter first tuple: "))
tuple2 = eval(input("Enter second tuple: "))
# Swap them
tuple1, tuple2 = tuple2, tuple1
# Show results
print("After swapping:")
print("First tuple:", tuple1)
print("Second tuple:", tuple2)
15)Explain Bitwise operator in Python with appropriate example
Operator Name Description
& AND 1 if both bits are 1
` ` OR
^ XOR 1 if exactly one bit is 1
~ NOT (bitwise neg.) Inverts all bits (two’s-complement form)
<< Left shift Shifts bits left by n places (fills with 0s on the right)
>> Right shift Shifts bits right by n places (sign-bit fill for negatives)
16) Write a Python program to find the factorial of a number provided by the user
# Simple program to compute factorial
num = int(input("Enter a non-negative integer: "))
factorial = 1
for i in range(1, num + 1):
factorial *= i
print(f"{num}! = {factorial}")
17)Write a Python Program to check if a string is palindrome or not.
# Simple palindrome check
s = input("Enter a string: ")
if s == s[::-1]:
print("Palindrome")
else:
print("Not a palindrome")
18) Write a Python Program to accept values from user in a list and find the
largest number and smallest number in a list.
# Read the number of elements
n = int(input("How many numbers? "))
# Read each number individually and collect into a list
numbers = []
for _ in range(n):
num = int(input("Enter a number: "))
numbers.append(num)
# Find and display largest and smallest
print("Largest number:", max(numbers))
print("Smallest number:", min(numbers))
19) Explain use of Pass and Else keyword with for loops in python
pass Keyword:
It’s a null operation — does nothing.
Used when a statement is syntactically required, but you want to do nothing (like a
placeholder).
Example:
for i in range(5):
if i == 3:
pass # Do nothing when i is 3
else:
print(i)
output:
0
1
2
4
else with for loop:
The else runs only if the loop completes normally (no break).
Useful for searching logic — "not found" scenarios.
for i in range(5):
if i == 7:
print("Found!")
break
else:
print("Not found.")
Output: Not found.
20) Write python program to display output like.
4 6 8
10 12 14 16 18
num = 2 # Start from 2
for row in range(1, 5): # 4 rows
for col in range(row):
print(num, end=" ")
num += 2
print()