Python Interview Questions
What is python
Python is a high-level, interpreted programming language known for its readability and simplicity.
What are Python's built-in data types?
The main built-in data types include integers, floats, strings, lists, tuples, sets, and dictionaries.
What is a list in Python?
A list is a mutable, ordered collection of items that can contain mixed data types.
What is a tuple?
-
- tuple is an immutable, ordered collection of items, similar to a list.
How do you create a dictionary in Python?
-
- You create a dictionary using curly braces, e.g.,
my_dict = {'key': 'value'}
.
- You create a dictionary using curly braces, e.g.,
What is a set?
-
- A set is an unordered collection of unique items.
What is the difference between == and is?
-
==
checks for value equality, whileis
checks for reference equality (identity).
How do you handle exceptions in Python?
-
- You handle exceptions using
try
andexcept
blocks.
- You handle exceptions using
What is a lambda function?
-
- A lambda function is a small anonymous function defined using the
lambda
keyword.
- A lambda function is a small anonymous function defined using the
What is the purpose of the self keyword in Python?
self
refers to the instance of the class and is used to access instance variables and methods.
What are list comprehensions?
-
- List comprehensions provide a concise way to create lists using a single line of code.
What is the difference between a shallow copy and a deep copy?
A shallow copy creates a new object but inserts references into it, while a deep copy creates a new object and recursively adds copies of nested objects.
Explain the concept of decorators in Python.
-
- Decorators are functions that modify the behavior of another function or method.
What are generators in Python?
-
- Generators are a way to create iterators using the
yield
statement, allowing lazy evaluation.
- Generators are a way to create iterators using the
What is the Global Interpreter Lock (GIL)?
-
- GIL is a mutex that protects access to Python objects, preventing multiple threads from executing Python bytecode simultaneously.
-
How do you create a class in Python?
-
- Use the
class
keyword, e.g.,class MyClass: pass
.
- Use the
What are Python modules?
-
- Modules are files containing Python code that can be imported and reused in other Python scripts.
What is the purpose of __init__ method?
-
__init__
is a constructor method that initializes instance variables when an object is created.
What are Python's built-in functions?
-
- Some built-in functions include
len()
,type()
,int()
,str()
, andprint()
.
- Some built-in functions include
What is the difference between break and continue?
break
exits the loop, while continue
skips to the next iteration of the loop.
What is the purpose of the with statement?
-
- The
with
statement simplifies exception handling by encapsulating common preparation and cleanup tasks.
- The
Explain the concept of metaclasses.
-
- Metaclasses are classes of classes that define how a class behaves. They control class creation.
How do you manage memory in Python?
-
- Python manages memory using automatic garbage collection.
What are context managers?
-
- Context managers are objects that manage resources, using
__enter__
and__exit__
methods.
- Context managers are objects that manage resources, using
What is monkey patching?
-
- Monkey patching refers to modifying or extending libraries or classes at runtime.
How do you read and write files in Python?
-
- Use
open()
to read or write files, and methods like.read()
,.write()
, and.close()
.
- Use
**What are *args and kwargs?
-
*args
allows you to pass a variable number of non-keyword arguments, while**kwargs
allows for variable keyword arguments.
What is the purpose of the pass statement?
-
pass
is a null statement used as a placeholder for future code.
How do you implement inheritance in Python?
-
- Inherit from a parent class by specifying it in parentheses, e.g.,
class Child(Parent):
.
- Inherit from a parent class by specifying it in parentheses, e.g.,
What are the different types of inheritance?
Types include single inheritance, multiple inheritance, and multilevel inheritance.
What is a stack?
-
- A stack is a data structure that follows the Last In First Out (LIFO) principle.
What is a queue?
-
- A queue is a data structure that follows the First In First Out (FIFO) principle.
How do you implement a linked list in Python?
-
- Create a
Node
class and aLinkedList
class to manage nodes.
- Create a
What is a binary tree?
-
- A binary tree is a tree data structure in which each node has at most two children.
How do you perform a depth-first search (DFS)?
-
- Use recursion or a stack to explore as far as possible along each branch before backtracking.
How do you perform a breadth-first search (BFS)?
-
- Use a queue to explore all neighbors at the present depth prior to moving on to nodes at the next depth level.
What is a hash table?
-
- A hash table is a data structure that maps keys to values for fast lookup.
How do you sort a list in Python?
-
- Use the
.sort()
method for in-place sorting or thesorted()
function for a new sorted list.
- Use the
What is a binary search?
-
- A binary search is an efficient algorithm for finding an item in a sorted array, dividing the search interval in half.
What are the time complexities of common operations in a list?
Access: O(1), Search: O(n), Insertion: O(n), Deletion: O(n).
What is NumPy?
-
- NumPy is a library for numerical computing in Python, providing support for arrays and matrices.
What is Pandas?
-
- Pandas is a library for data manipulation and analysis, offering data structures like DataFrames.
What is Matplotlib?
-
- Matplotlib is a plotting library for creating static, interactive, and animated visualizations.
What is Flask?
-
- Flask is a lightweight web framework for building web applications in Python.
What is Django?
-
- Django is a high-level web framework that encourages rapid development and clean design.
What is TensorFlow?
-
- TensorFlow is an open-source library for machine learning and deep learning applications.
What is scikit-learn?
-
- Scikit-learn is a machine learning library that provides simple and efficient tools for data analysis.
What is Beautiful Soup?
-
- Beautiful Soup is a library for parsing HTML and XML documents and extracting data from them.
What is OpenCV?
-
- OpenCV is an open-source computer vision and machine learning software library.
What is PyTorch?
PyTorch is an open-source machine learning library used for applications such as computer vision and natural language processing.
What is the difference between class and instance variables in Python?
- Class variables are shared among all instances of the class.
- Instance variables are unique to each instance.
What is method overriding in Python?
Method overriding occurs when a child class provides a specific implementation of a method that is already defined in its parent class.
What is method overloading in Python?
Python does not support method overloading in the traditional sense. However, you can achieve similar behavior using default arguments.
What is abstraction in Python?
Abstraction refers to hiding the internal details and showing only the necessary functionality.
What is encapsulation in Python?
Encapsulation is the concept of bundling data and methods that operate on the data within a single class, and restricting access to some of the class’s components.
What is polymorphism in Python?
-
Polymorphism allows different classes to be treated as instances of the same class through inheritance.
What is inheritance in Python?
Inheritance allows a class (child class) to inherit attributes and methods from another class (parent class).
How can you handle memory leaks in Python?
- Avoid reference cycles by using weak references (
weakref
module). - Use tools like
gc
to identify and handle garbage collection issues.
Write a Python program to reverse a string.
def reverse_string(s):
return s[::-1]
Write a Python program to check if a string is a palindrome.
def is_palindrome(s):
return s == s[::-1]
How to find the second largest number in a list?
def second_largest(numbers):
unique_numbers = list(set(numbers))
unique_numbers.sort()
return unique_numbers[-2]
Write a Python program to find the factorial of a number.
def factorial(n):
return 1 if n == 0 else n * factorial(n – 1)
How to find all prime numbers up to a given number?
def prime_numbers(limit):
primes = []
for num in range(2, limit + 1):
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
break
else: primes.append(num)
return primes
Write a Python program to find the longest common prefix in a list of strings.
def longest_common_prefix(strs):
if not strs:
return “”
prefix = strs[0]
for s in strs[1:]:
while not s.startswith(prefix):
prefix = prefix[:-1]
if not prefix:
return ” “
return prefix
How do you find the missing number in an array of integers from 1 to n?
def missing_number(arr):
n = len(arr) + 1
return n * (n + 1) // 2 – sum(arr)
Write a Python function to check if two strings are anagrams.
def are_anagrams(s1, s2):
return sorted(s1) == sorted(s2)
How do you merge two sorted arrays?
def merge_sorted_arrays(arr1, arr2):
return sorted(arr1 + arr2)
Write a Python program to remove duplicates from a list.
def remove_duplicates(lst):
return list(set(lst))
How do you define a class in Python?
class MyClass:
def __init__(self, name):
self.name = name
How do you implement a singleton pattern in Python?
class Singleton:
_instance = None
def __new__(cls):
if not cls._instance:
cls._instance = super(Singleton, cls).__new__(cls)
return cls._instance
What is multiple inheritance and how is it implemented in Python?
Multiple inheritance allows a class to inherit from more than one parent class. It is implemented like this:
class A:
pass
class B:
pass
class C(A, B):
pass
What is monkey patching in Python?
Monkey patching refers to modifying or extending the behavior of libraries or classes at runtime.
Eg:
def new_method(self):
print(“Monkey patched!”)
SomeClass.method = new_method
What is a context manager in Python?
A context manager is used to manage resources, such as file streams. It is implemented using the with
statement to ensure that resources are cleaned up after use.
-
with open('file.txt', 'r') as file:
data = file.read()
How do you handle exceptions in Python?
Exceptions are handled using try
, except
, else
, and finally
blocks.
Example:
try:
x = 1 / 0
except ZeroDivisionError:
print(“Division by zero!”)
What are list comprehensions in Python?
List comprehensions provide a concise way to create lists by iterating over an iterable and optionally applying a filter.
What is a lambda function in Python?
A lambda function is an anonymous function expressed as a single statement. It is defined using the lambda
keyword.
add = lambda x, y: x + y