Python
Q
What is the difference between a list comprehension and a generator expression in Python?
A list comprehension eagerly evaluates and returns a complete list in memory, while a generator
expression returns an iterator that yields items lazily. This makes generator expressions far more
memory-efficient for large datasets — they compute values on demand rather than storing everything
upfront.
List comprehension:
lst = [x*x for x in range(5)]
print(lst[0]) # 0
print(lst[0]) # still 0 (reusable)
generator expression:
gen = (x*x for x in range(5))
print(next(gen)) # 0
print(next(gen)) # 1
Python
Q
Define a class.
A class is a blueprint for creating objects. It bundles data (attributes) and functions (methods) that
operate on that data. Classes define the structure and behaviour that their instances will have.
Python
Q
Define an object and give a real‑time example.
An object is a concrete instance of a class, holding actual values for the attributes defined by its
class and able to execute its methods. Real‑time example: a specific car (e.g. a red Toyota Camry) is
an object of the Car class — it has attributes like color = 'red' and can
perform actions like accelerate().
Python
Q
Difference between class variable and instance variable.
Class variables are shared across all instances of a class; they are defined inside the class but
outside any method. Instance variables are unique to each object, typically set inside
__init__. Changing a class variable affects every instance, while changing an instance
variable affects only that particular object.
Python
Q
Difference between list and tuple.
Lists are mutable, ordered collections defined with []; tuples are immutable, ordered
collections defined with (). Tuples are slightly more memory‑efficient and can be used as
dictionary keys because they are hashable.
Python
Q
How method overloading can be achieved in Python.
Python does not support traditional method overloading (multiple methods with the same name but
different signatures). Instead, you use default arguments, *args, **kwargs,
or type‑checking inside a single method to handle varied inputs.
Python
Q
What is method overloading?
Method overloading is the ability of a class to have multiple methods with the same name but different
parameters (number, type, or order). In statically typed languages it is resolved at compile time;
Python simulates it through flexible argument handling.
Python
Q
What is a dynamically typed language?
A dynamically typed language checks variable types at runtime rather than compile time. In Python, you
never declare a type; a variable can refer to an integer at one moment and a string later.
Python
Q
What is PEP 8?
PEP 8 is the official style guide for Python code. It provides conventions for indentation, naming,
line length, imports, and comments to promote readability and consistency across the Python ecosystem.
Python
Q
What is the Scope in Python?
Scope determines where a variable is accessible. Python follows the LEGB rule: Local (inside a
function), Enclosing (nonlocal), Global (module‑level), and Built‑in. Variables are looked up in that
order.
Python
Q
How to create a constructor in Python.
A constructor is defined by the __init__ method inside a class. It is automatically called
when an object is instantiated and is used to initialise instance attributes. Example:
def __init__(self, name): self.name = name.
Python
Q
How Python supports multiple inheritance.
Python allows a class to inherit from several parent classes by listing them in the class definition.
The method resolution order (MRO), computed using C3 linearization, decides which parent’s method is
called first.
Python
Q
Give an example of method overriding.
Method overriding occurs when a subclass provides its own implementation of a method already present
in its parent. Example:
class Child(Parent): def show(self): print("Child") replaces the show
method of Parent.
Python
Q
Define abstraction. Give one real‑time example for abstraction.
Abstraction hides complex implementation details and exposes only the essential features. Real‑time
example: a car’s steering wheel – the driver knows how to turn left or right without understanding the
steering mechanism underneath.
Python
Q
List the different types of inheritance.
The main inheritance types are: single, multiple, multilevel, hierarchical, and hybrid. Python
supports all of them, and its multiple inheritance can be used to create mixin classes.
Python
Q
Give one example of dictionary comprehensions.
{x: x**2 for x in range(5)} results in {0:0, 1:1, 2:4, 3:9, 4:16}.
Dictionary comprehensions provide a concise way to build dictionaries from an iterable.
Python
Q
Write the usage of lambda functions.
Lambda functions are small, anonymous functions defined with the lambda keyword. They are
often used for short operations passed as arguments to higher‑order functions like
sorted(), map(), and filter(), e.g.
sorted(items, key=lambda x: x.price).
Python
Q
What is the difference between .py and .pyc files?
.py files contain human‑readable source code. .pyc files store compiled
bytecode, automatically generated by Python to speed up imports. They reside in the
__pycache__ directory and are platform‑independent.
Python
Q
What does *args and **kwargs mean?
*args captures any number of positional arguments as a tuple.
**kwargs captures any number of keyword arguments as a dictionary. They make functions
highly flexible without forcing a fixed signature.
Python
Q
How to create an empty class in Python.
Use the pass statement: class Empty: pass. This creates a valid class with no
attributes or methods, often used as a placeholder.
Python
Q
List the keywords and their functionality used in exception handling.
try – wraps code that might raise an exception.
except – catches and handles specific exceptions.
else – runs only if no exception occurred.
finally – always executes, used for cleanup.
raise – explicitly raises an exception.
Python
Q
What does the ‘#’ symbol do in Python?
The # symbol denotes a single‑line comment. Everything from # to the end of
the line is ignored by the interpreter, used to explain or annotate code.
Python
Q
What is the difference between a Mutable datatype and an Immutable datatype?
Mutable types (list, dict, set) can be changed after creation
without changing their identity. Immutable types (int, str,
tuple) cannot be modified in place; any “change” creates a new object.
Python
Q
What is List Comprehension? Give an Example.
List comprehension is a syntactic shortcut for building lists. Example:
[x*2 for x in range(5)] produces [0, 2, 4, 6, 8]. It is more readable and
often faster than a traditional loop.
Python
Q
What is the difference between a List and a Dictionary?
A list is an ordered sequence of elements accessed by integer index. A dictionary is an unordered
collection of key‑value pairs accessed by unique keys. Lists are best for ordered data; dictionaries
excel at fast lookups.
Python
Q
What is the difference between / and // in Python?
/ performs true division, always returning a float. // is floor
division, returning the largest integer less than or equal to the exact quotient. Example:
5 / 2 = 2.5, 5 // 2 = 2.
Python
Q
What is Polymorphism in Python? How polymorphism can be achieved.
Polymorphism allows objects of different classes to respond to the same method call in their own way.
In Python, it is achieved through duck typing (any object with the required method works) or method
overriding in subclasses.
Python
Q
What is a translator?
A translator converts source code from one language to another. An interpreter (like CPython) executes
code line‑by‑line, while a compiler translates the whole program upfront. Python’s interpreter first
compiles to bytecode and then interprets that.
Python
Q
Difference between Procedural vs OOP.
Procedural programming focuses on functions and sequences of actions; data is separate. OOP bundles
data and behaviour into objects, promoting modularity, reuse, and modelling of real‑world entities.
Python
Q
Explain recursion with an example.
Recursion is when a function calls itself to solve smaller sub‑problems. Example – factorial:
def fact(n): return 1 if n == 0 else n * fact(n-1). A base case is essential to prevent
infinite recursion.
Python
Q
Difference between return and yield statements.
return sends a value back to the caller and terminates the function.
yield produces a value and pauses the function, turning it into a generator that can
resume and produce more values later.
Python
Q
What is the use of an abstract class?
An abstract class (using the abc module) defines a common interface that subclasses must
implement. It cannot be instantiated on its own, enforcing a contract for derived classes and ensuring
consistency.
Python
Q
What is a docstring?
A docstring is a string literal placed as the first statement in a module, function, class, or method.
It describes the purpose and usage of the code and is accessible via help() and
__doc__.
Python
Q
What is MRO?
Method Resolution Order is the sequence in which base classes are searched when looking for a method
in multiple inheritance. Python uses the C3 linearization algorithm; you can inspect it via
ClassName.__mro__.
Python
Q
Difference between counter‑controlled and event‑controlled loop.
A counter‑controlled loop runs a fixed number of times (e.g. for i in range(10)). An
event‑controlled loop runs until a condition becomes false (e.g. while x > 0). The former
knows the iterations in advance; the latter depends on runtime conditions.
Python
Q
Write a program to check given string is a palindrome or not without using predefined methods.
def is_palindrome(s):
left, right = 0, len(s)-1
while left < right:
if s[left] != s[right]: return False
left += 1; right -= 1
return True
It compares characters from both ends without using slicing or reversed().
Python
Q
Give an example program to explain abstraction.
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self): pass
class Circle(Shape):
def __init__(self, r): self.r = r
def area(self): return 3.14 * self.r ** 2
The user only sees area() without knowing the formula details — that’s abstraction.
Python
Q
Give an example program for inheritance.
class Animal:
def speak(self): print("Some sound")
class Dog(Animal):
def speak(self): print("Bark")
d = Dog()
d.speak() # prints "Bark"
Dog inherits from Animal and overrides the speak method.
Python
Q
Find second largest number from a given list.
def second_largest(lst):
unique = list(set(lst))
if len(unique) < 2: return None
unique.sort()
return unique[-2]
Alternatively, you can keep track of the top two values in a single pass for better efficiency.
Python
Q
Check given number is prime or not.
def is_prime(n):
if n < 2: return False
for i in range(2, int(n**0.5)+1):
if n % i == 0: return False
return True
Only checking up to the square root of n makes the algorithm efficient.
Python
Q
Write a program to calculate the gcd of a list of numbers.
import math
from functools import reduce
def gcd_of_list(nums):
return reduce(math.gcd, nums)
This uses Python’s built‑in math.gcd and applies it cumulatively across the list.