PYTHON PROGRAMMING
[Link]. (Computer Applications) 2025-2026
UNIT 3 - 5 Mark Questions & Answers
Topics: Tuples | Dictionaries | Sets | Iterators | Generators | Functions
SECTION A: TUPLES
Q1. What is a Tuple? Explain the need for Tuple with examples.
A tuple is an ordered, immutable collection of elements in Python. Unlike lists, tuples cannot be
modified after creation. They are defined using parentheses ( ).
Need for Tuples:
• Tuples are faster than lists due to immutability.
• Used to store fixed data that should not change (e.g., coordinates, RGB values).
• Tuples can be used as keys in dictionaries (lists cannot).
• Useful for returning multiple values from a function.
Syntax:
t = (10, 20, 30, 'Hello')
print(t) # Output: (10, 20, 30, 'Hello')
print(t[0]) # Output: 10
print(t[-1]) # Output: Hello
Tuple with single element:
t = (5,) # Comma required for single-element tuple
print(type(t)) # Output: <class 'tuple'>
Q2. Explain Tuple methods and Tuple unpacking with examples.
Tuple Methods:
• count(x) – Returns the number of times x appears in the tuple.
• index(x) – Returns the first index of x in the tuple.
Examples:
t = (1, 2, 3, 2, 4, 2)
print([Link](2)) # Output: 3
print([Link](3)) # Output: 2
Tuple Unpacking:
Tuple unpacking allows assigning elements of a tuple to multiple variables in one step.
t = (10, 20, 30)
a, b, c = t
print(a, b, c) # Output: 10 20 30
# Swap values using tuple unpacking
x, y = 5, 10
x, y = y, x
print(x, y) # Output: 10 5
# Nested tuple unpacking
t = ((1, 2), (3, 4))
(a, b), (c, d) = t
print(a, b, c, d) # Output: 1 2 3 4
Q3. Write a Python program to demonstrate Sequence of Unpacking in Tuples.
Sequence unpacking is the process of assigning tuple elements to individual variables. Python
matches positions automatically.
# Basic Unpacking
student = ('Ravi', 21, 'Computer Applications')
name, age, course = student
print('Name:', name)
print('Age:', age)
print('Course:', course)
# Extended unpacking using *
marks = (95, 88, 76, 92, 85)
first, *middle, last = marks
print('First:', first) # 95
print('Middle:', middle) # [88, 76, 92]
print('Last:', last) # 85
# Unpacking in a loop
data = [(1, 'Apple'), (2, 'Banana'), (3, 'Cherry')]
for num, fruit in data:
print(num, '-', fruit)
SECTION B: DICTIONARIES
Q4. What is a Dictionary in Python? Explain with examples of creating and accessing
a Dictionary.
A Dictionary is an unordered, mutable collection of key-value pairs. It is defined using curly
braces { }. Keys must be unique and immutable; values can be of any type.
Creating a Dictionary:
d = {'name': 'Arun', 'age': 22, 'city': 'Chennai'}
print(d)
# Output: {'name': 'Arun', 'age': 22, 'city': 'Chennai'}
Accessing Values:
print(d['name']) # Output: Arun
print([Link]('age')) # Output: 22
print([Link]('phone', 'Not Found')) # Output: Not Found
Adding and Updating:
d['email'] = 'arun@[Link]' # Add new key
d['age'] = 23 # Update existing key
Deleting:
del d['city'] # Remove key
[Link]('email') # Remove and return value
Q5. Explain the Basic Operations and Dictionary Operations in Python.
Basic Operations on Dictionary:
• len(d) – Returns number of key-value pairs.
• in – Check if a key exists.
• not in – Check if a key does not exist.
d = {'a': 1, 'b': 2, 'c': 3}
print(len(d)) # Output: 3
print('a' in d) # Output: True
print('z' not in d) # Output: True
Dictionary Methods:
• keys() – Returns all keys.
• values() – Returns all values.
• items() – Returns all key-value pairs.
• update() – Merges another dictionary.
• clear() – Removes all elements.
• copy() – Returns a shallow copy.
d = {'x': 10, 'y': 20, 'z': 30}
print([Link]()) # dict_keys(['x', 'y', 'z'])
print([Link]()) # dict_values([10, 20, 30])
print([Link]()) # dict_items([('x',10),('y',20),('z',30)])
# Iterating through dictionary
for key, value in [Link]():
print(key, '->', value)
SECTION C: SETS
Q6. Explain Sets in Python with its properties and basic operations.
A Set is an unordered, mutable collection of unique elements. Sets are defined using curly
braces { } or the set() function. They do not allow duplicate values.
Properties of Sets:
• Unordered – No index-based access.
• Unique – Duplicates are automatically removed.
• Mutable – Elements can be added or removed.
• Heterogeneous – Can store different types of data.
Creating a Set:
s = {1, 2, 3, 4, 5}
s2 = set([3, 3, 4, 5, 5])
print(s2) # Output: {3, 4, 5} (duplicates removed)
Set Operations:
• Union (|) – All elements from both sets.
• Intersection (&) – Common elements.
• Difference (-) – Elements in one but not the other.
• Symmetric Difference (^) – Non-common elements.
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}
print(A | B) # {1, 2, 3, 4, 5, 6} - Union
print(A & B) # {3, 4} - Intersection
print(A - B) # {1, 2} - Difference
print(A ^ B) # {1, 2, 5, 6} - Symmetric Diff
SECTION D: ITERATORS AND GENERATORS
Q7. What is an Iterator in Python? Explain with examples.
An Iterator is an object that implements the __iter__() and __next__() methods. It allows
sequential traversal of elements without loading all data into memory at once.
Key Methods:
• __iter__() – Returns the iterator object itself.
• __next__() – Returns the next element; raises StopIteration when exhausted.
# Using iter() and next()
nums = [10, 20, 30]
it = iter(nums)
print(next(it)) # 10
print(next(it)) # 20
print(next(it)) # 30
# Custom Iterator
class CountUp:
def __init__(self, limit):
[Link] = limit
[Link] = 0
def __iter__(self):
return self
def __next__(self):
if [Link] < [Link]:
[Link] += 1
return [Link]
raise StopIteration
c = CountUp(3)
for val in c:
print(val) # 1, 2, 3
Q8. What is a Generator in Python? How does it differ from an Iterator? Give
examples.
A Generator is a special type of iterator created using a function with the yield keyword. It
generates values lazily (one at a time), saving memory compared to returning a full list.
Generator Function:
def count_gen(n):
for i in range(1, n+1):
yield i
g = count_gen(4)
print(next(g)) # 1
print(next(g)) # 2
for val in count_gen(3):
print(val) # 1 2 3
Generator Expression:
gen = (x*x for x in range(5))
for v in gen:
print(v) # 0 1 4 9 16
Difference between Iterator and Generator:
Iterator Generator
Created using class with __iter__ and Created using function with yield keyword
__next__
More code required Concise and easy to write
Does not manage state automatically Automatically manages state using yield
Slower due to manual implementation Faster and memory efficient
SECTION E: FUNCTIONS
Q9. What is a Function in Python? Explain the types of arguments with examples.
A Function is a reusable block of code that performs a specific task. It is defined using the def
keyword.
Syntax:
def function_name(parameters):
# body
return value
Types of Arguments:
1. Required (Positional) Arguments:
def add(a, b):
return a + b
print(add(10, 20)) # Output: 30
2. Keyword Arguments:
def greet(name, msg):
print(msg, name)
greet(msg='Hello', name='Priya') # Order doesn't matter
3. Default Arguments:
def power(base, exp=2):
return base ** exp
print(power(3)) # Output: 9 (uses default exp=2)
print(power(3, 3)) # Output: 27
4. Variable Length Arguments (*args):
def total(*nums):
return sum(nums)
print(total(1, 2, 3, 4)) # Output: 10
5. Keyword Variable Length (**kwargs):
def info(**details):
for k, v in [Link]():
print(k, ':', v)
info(name='Raj', age=21, city='Chennai')
Q10. Explain Anonymous Functions (Lambda) and Recursive Functions in Python
with examples.
Lambda (Anonymous) Functions:
A lambda function is a small, unnamed function defined using the lambda keyword. It can take
multiple arguments but has only one expression.
Syntax:
lambda arguments: expression
# Simple lambda
square = lambda x: x * x
print(square(5)) # Output: 25
# Lambda with two arguments
add = lambda a, b: a + b
print(add(3, 7)) # Output: 10
# Lambda with filter()
nums = [1, 2, 3, 4, 5, 6]
evens = list(filter(lambda x: x % 2 == 0, nums))
print(evens) # [2, 4, 6]
# Lambda with map()
doubled = list(map(lambda x: x * 2, nums))
print(doubled) # [2, 4, 6, 8, 10, 12]
Recursive Functions:
A recursive function is a function that calls itself to solve smaller subproblems. It must have a
base case to stop recursion.
# Factorial using Recursion
def factorial(n):
if n == 0 or n == 1:
return 1
return n * factorial(n - 1)
print(factorial(5)) # Output: 120
# Trace: 5*4*3*2*1 = 120
# Fibonacci using Recursion
def fib(n):
if n <= 1:
return n
return fib(n-1) + fib(n-2)
for i in range(7):
print(fib(i), end=' ') # 0 1 1 2 3 5 8
Q11. Explain Scope of Variables in Python: Local and Global Variables with examples.
Scope refers to the region of a program where a variable can be accessed.
Local Variables:
Variables defined inside a function. They are only accessible within that function.
def greet():
msg = 'Hello' # local variable
print(msg)
greet() # Hello
# print(msg) # Error: msg not defined outside
Global Variables:
Variables defined outside all functions. They can be accessed anywhere in the program.
count = 0 # global variable
def increment():
global count
count += 1
increment()
increment()
print(count) # Output: 2
Note:
• Without the global keyword, assigning to a variable inside a function creates a local
copy.
• The global keyword is used to modify a global variable inside a function.
• Python uses LEGB rule: Local -> Enclosing -> Global -> Built-in.
Q12. Explain Nesting of Functions and Passing Arguments in Python.
Nesting of Functions:
Python allows defining a function inside another function. The inner function can access
variables of the outer function (closure).
def outer():
x = 10
def inner():
print('Inner x:', x) # accesses outer's x
inner()
print('Outer x:', x)
outer()
# Output:
# Inner x: 10
# Outer x: 10
Passing a Function as an Argument:
def apply(func, value):
return func(value)
def double(n):
return n * 2
print(apply(double, 5)) # Output: 10
Returning a Function (Closure):
def multiplier(factor):
def multiply(num):
return num * factor
return multiply
triple = multiplier(3)
print(triple(4)) # Output: 12
[Link]. (Computer Applications) | Unit 3 Notes | Prepared for 5-Mark Questions