Python Practice Questions
Data Structures
Q1. What is the difference between a list and a tuple in Python?
my_list = [1, 2, 3]
my_tuple = (1, 2, 3)
Explanation: Lists are mutable (can be changed), whereas tuples are immutable (cannot be changed).
Q2. How do you use a dictionary to count character frequency in a string?
s = 'hello'
char_freq = {}
for char in s:
char_freq[char] = char_freq.get(char, 0) + 1
print(char_freq)
Explanation: Dictionaries are ideal for counting as they map keys to values efficiently.
Functions
Q1. How do you define and call a simple Python function?
def greet(name):
return f'Hello, {name}!'
print(greet('Alice'))
Explanation: Functions are defined using 'def' and can take parameters to perform tasks.
Q2. What is a lambda function and how is it used?
add = lambda x, y: x + y
print(add(2, 3))
Explanation: Lambda functions are anonymous functions used for short, simple operations.
Object-Oriented Programming
Q1. How do you define a class and create an object in Python?
class Person:
def __init__(self, name):
[Link] = name
p = Person('Alice')
print([Link])
Explanation: Classes define blueprints for objects; '__init__' initializes object attributes.
Q2. What is inheritance in Python?
class Animal:
def speak(self):
return 'Animal speaks'
class Dog(Animal):
def speak(self):
return 'Dog barks'
d = Dog()
print([Link]())
Explanation: Inheritance allows a class to derive methods and properties from another class.