0% found this document useful (0 votes)
2 views9 pages

Python Interview Guide (1)

This document contains a comprehensive list of Python interview questions and answers, covering basic to intermediate topics. Key areas include Python's features, data types, memory management, functions, and advanced concepts like decorators and comprehensions. It serves as a valuable resource for preparing for Python programming interviews.

Uploaded by

sanjeetverma9572
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views9 pages

Python Interview Guide (1)

This document contains a comprehensive list of Python interview questions and answers, covering basic to intermediate topics. Key areas include Python's features, data types, memory management, functions, and advanced concepts like decorators and comprehensions. It serves as a valuable resource for preparing for Python programming interviews.

Uploaded by

sanjeetverma9572
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Python Interview Questions and Answers

📆 Basic: Laying the Foundation

1. What is Python, and its key features?

Python is a high-level, interpreted programming language known for its simplicity and readability. It
supports multiple programming paradigms, including object-oriented, functional, and procedural. Python's
syntax is clean and allows developers to write fewer lines of code compared to other languages like Java or
C++.

Key features:

• Interpreted and dynamically typed


• Easy to learn and read
• Extensive standard library
• Cross-platform compatibility
• Automatic memory management
• Support for third-party libraries

2. What are Python's built-in data types?

Python has several built-in data types:

• Numeric types: int , float , complex


• Sequence types: str , list , tuple , range
• Set types: set , frozenset
• Mapping type: dict
• Boolean type: bool
• Binary types: bytes , bytearray , memoryview
• None type: NoneType

3. How do you declare and use variables?

Variables in Python are declared by assigning a value using the = operator. Python does not require
specifying the data type explicitly.

x = 10
name = "Alice"
price = 10.5

1
Variables can be reassigned to different types.

4. Explain the difference between a list, tuple, and set.

• List: Mutable, ordered, and allows duplicate elements. Defined with square brackets [] .
• Tuple: Immutable, ordered, and allows duplicates. Defined with parentheses () .
• Set: Mutable, unordered, and does not allow duplicates. Defined with curly braces {} .

5. How do you iterate over a list in Python?

You can iterate using a for loop:

my_list = [1, 2, 3]
for item in my_list:
print(item)

6. What are Python’s conditional statements, and how are they used?

Conditional statements allow execution of code based on certain conditions.

x = 10
if x > 0:
print("Positive")
elif x < 0:
print("Negative")
else:
print("Zero")

7. How does Python handle memory management?

Python uses a private heap space and manages memory through:

• Reference counting
• Garbage collection for cyclic references
• Built-in memory allocators and deallocators

2
8. Explain the use of the len() function.

The len() function returns the number of items in an object such as a string, list, tuple, or dictionary.

len("hello") # 5
len([1, 2, 3]) # 3

9. What is the difference between is and == in Python?

• == : Compares values (equality).


• is : Compares identities (whether two objects point to the same memory location).

a = [1, 2]
b = [1, 2]
a == b # True
a is b # False

10. How do you handle exceptions in Python?

Use try , except , finally blocks:

try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
finally:
print("Execution complete")

11. What are Python functions, and how do you define them?

Functions are blocks of reusable code. Defined using the def keyword:

def greet(name):
return f"Hello, {name}"

3
12. What is the difference between *args and **kwargs ?

• *args : Allows variable number of positional arguments.


• **kwargs : Allows variable number of keyword arguments.

def func(*args, **kwargs):


print(args)
print(kwargs)

13. How is Python's for loop different from other programming languages?

Python's for loop iterates directly over items in a sequence (e.g., list, string), not index-based unless using
range() or enumerate() .

14. Explain the purpose of the range() function.

Generates a sequence of numbers, commonly used in loops.

for i in range(3):
print(i) # 0 1 2

15. How do you import and use modules?

Use the import statement:

import math
print(math.sqrt(16)) # 4.0

16. What are Python decorators, and how do they work?

Decorators are functions that modify the behavior of other functions.

def decorator(func):
def wrapper():
print("Before")
func()
print("After")

4
return wrapper

@decorator
def say_hello():
print("Hello")

17. How do you reverse a string in Python?

Use slicing:

s = "hello"
print(s[::-1]) # "olleh"

18. How do you check if an element exists in a list?

Use the in keyword:

if 5 in [1, 2, 5]:
print("Found")

19. What is a lambda function? Provide an example.

A lambda is an anonymous function:

square = lambda x: x * x
print(square(5)) # 25

🔢 Intermediate: Keep Practicing

1. Explain the difference between shallow copy and deep copy in Python.

A shallow copy creates a new object, but does not create copies of nested objects; they still reference the
original. A deep copy creates a new object and recursively copies all nested objects.

import copy
original = [[1, 2], [3, 4]]

5
shallow = copy.copy(original)
deep = copy.deepcopy(original)

2. What are Python comprehensions, and how are they used?

Comprehensions provide a concise way to create collections. They are more readable and efficient than
traditional loops.

squares = [x * x for x in range(10)]


even_set = {x for x in range(10) if x % 2 == 0}

3. How does Python's garbage collection work?

Python uses automatic garbage collection based on reference counting and a cyclic garbage collector that
removes cycles of objects referencing each other.

4. Explain Python's Global Interpreter Lock (GIL).

The GIL is a mutex that protects access to Python objects, preventing multiple native threads from
executing Python bytecodes simultaneously. This simplifies memory management but can be a bottleneck
in CPU-bound multi-threaded programs.

5. What is the difference between mutable and immutable objects?

• Mutable: Can be changed after creation (e.g., list, dict, set).


• Immutable: Cannot be changed after creation (e.g., int, str, tuple).

6. How do you use the zip() function?

Combines multiple iterables element-wise.

names = ["Alice", "Bob"]


ages = [25, 30]
combined = list(zip(names, ages))

6
7. Explain the difference between @staticmethod and @classmethod.

• @staticmethod : Doesn't access class or instance, acts like a regular function.


• @classmethod : Takes cls as the first argument, can access/modify class state.

8. How do you merge two dictionaries?

d1 = {'a': 1}
d2 = {'b': 2}
merged = {**d1, **d2}

Or use:

d1.update(d2)

9. What is the difference between sort() and sorted()?

• sort() : Sorts the list in-place, returns None .


• sorted() : Returns a new sorted list.

10. How do you handle file operations?

Use open() in combination with context managers ( with ).

with open("file.txt", "r") as file:


data = file.read()

11. What are Python's iterators and generators?

• Iterator: Object implementing __iter__() and __next__() .


• Generator: Function using yield to return values lazily.

def gen():
yield 1
yield 2

7
12. How do you use the with statement?

Manages resources automatically, ensuring proper acquisition and release.

with open("file.txt") as f:
data = f.read()

13. What is Python's itertools module, and when would you use it?

itertools provides tools for efficient looping (e.g., combinations , permutations , cycle ,
chain ). Useful for handling large datasets and performance-critical tasks.

14. Explain the difference between positional and keyword arguments.

• Positional: Based on argument order.


• Keyword: Specified using parameter names.

def func(a, b): ...


func(1, 2) # positional
func(a=1, b=2) # keyword

15. How do you perform matrix operations in Python?

Use NumPy:

import numpy as np
A = np.array([[1, 2], [3, 4]])
B = np.array([[5, 6], [7, 8]])
result = A + B

16. What are Python's metaclasses, and how are they used?

Metaclasses are classes of classes, defining how classes behave. You can use them to control class creation.

class Meta(type):
def __new__(cls, name, bases, dct):
return super().__new__(cls, name, bases, dct)

8
17. How do you perform unit testing?

Use the unittest module:

import unittest
class TestMath(unittest.TestCase):
def test_add(self):
self.assertEqual(2 + 3, 5)

18. Explain how Python's os module is used.

Used for interacting with the operating system:

• File and directory handling


• Environment variables
• Process management

import os
print(os.getcwd())

19. What are argsort() and argmax() functions?

From NumPy:

• argsort() : Returns indices that would sort an array.


• argmax() : Returns the index of the maximum value.

20. How do you optimize code performance?

• Use built-in functions and libraries


• Profile with cProfile , timeit
• Avoid unnecessary computations
• Use generators
• Use NumPy for numerical tasks

[Advanced section to be continued next. Would you like to proceed with it now?]

You might also like