Python Interview Questions
Python Interview Questions
o Object-oriented
o Converting one data type to another using functions like int(), float(), str()
8. How do you check the type of a variable?
o Using type(variable)
15. print(item)
23. pass
o return gives back a value to the caller; print outputs to the console.
o The area in the code where a variable is accessible: local, enclosing, global, or
built-in.
o Anonymous function:
o lambda x: x * 2
• A programming paradigm where code is organized into objects that combine data
and behavior.
class Dog:
self.name = name
• class Dog(Animal):
• pass
• The ability to use a single interface for different types (e.g., function overloading).
• Bundling data and methods together and restricting access using private members (_
or __).
40. What is the difference between @classmethod, @staticmethod, and instance
methods?
data = f.read()
print(line)
f.write("Hello")
• It raises a ValueError.
open('nofile.txt')
except FileNotFoundError:
print("Not found")
import os
os.path.exists('file.txt')
try:
risky_code()
except ValueError:
print("Caught error")
pass
class MyError(Exception):
pass
import math
help(math)
• A function that takes another function and extends its behavior without modifying it:
def decorator(func):
def wrapper():
print("Before")
func()
print("After")
return wrapper
def gen():
yield 1
yield 2
with open('file.txt') as f:
data = f.read()
82. What is the difference between deep copy and shallow copy?
import copy
shallow = copy.copy(obj)
84. How do you create a deep copy?
import copy
deep = copy.deepcopy(obj)
• A mutex that prevents multiple native threads from executing Python bytecodes
simultaneously.
• Use built-in functions, list comprehensions, avoid unnecessary loops, and use NumPy.
88. What are memory leaks in Python and how to avoid them?
• Caused by objects referencing each other cyclically. Use weak references or cleanup.
• A library for numerical computing with support for arrays, matrices, and linear
algebra.
import numpy as np
94. What is the difference between Python list and NumPy array?
• NumPy arrays are faster, support vectorized operations, and are more memory-
efficient.
import pandas as pd
df = pd.read_csv('data.csv')
• Replacing loops with array operations for faster execution using low-level
optimizations.