0% found this document useful (0 votes)
5 views13 pages

Python Interview Questions Along With Their Answers

This document provides 30 Python interview questions and answers, covering basics, data structures, functions, OOP, advanced concepts, coding problems, modules, and debugging techniques. Each question is accompanied by a concise answer, making it suitable for junior to mid-level roles. The content is structured to test core knowledge and practical coding skills for technical interviews.

Uploaded by

aws.boris
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)
5 views13 pages

Python Interview Questions Along With Their Answers

This document provides 30 Python interview questions and answers, covering basics, data structures, functions, OOP, advanced concepts, coding problems, modules, and debugging techniques. Each question is accompanied by a concise answer, making it suitable for junior to mid-level roles. The content is structured to test core knowledge and practical coding skills for technical interviews.

Uploaded by

aws.boris
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

Generate 30 interview question for Python with answer

Here are **30 Python interview questions with clear, concise answers**, covering
fundamentals, intermediate concepts, and practical problem-solving—ideal for junior
to mid-level roles.

---

### **Basics & Syntax**

**1. Q: What is the difference between `list` and `tuple`?**

**A:**

- **List** is mutable (can be modified), uses `[ ]`, and is slower.

- **Tuple** is immutable (cannot be changed after creation), uses `( )`, and is faster.

→ Use tuples for fixed data (e.g., coordinates); lists for dynamic data.

---

**2. Q: Explain `==` vs `is` in Python.**

**A:**

- `==` checks **value equality** (e.g., `1 == 1.0` → `True`).

- `is` checks **identity** (same object in memory).

```python

a = [1, 2]

b = [1, 2]

print(a == b) # True (same values)

print(a is b) # False (different objects)

```
---

**3. Q: What is PEP 8?**

**A:** PEP 8 is Python’s **official style guide** for writing readable code (e.g., 4-space
indentation, max 79-char lines, snake_case for variables).

---

**4. Q: How do you handle exceptions in Python?**

**A:** Use `try`, `except`, `else`, and `finally`:

```python

try:

result = 10 / 0

except ZeroDivisionError:

print("Cannot divide by zero")

else:

print("Success")

finally:

print("Cleanup")

```

---

**5. Q: What are mutable and immutable types? Give examples.**

**A:**

- **Mutable**: Can be changed after creation → `list`, `dict`, `set`.

- **Immutable**: Cannot be changed → `int`, `str`, `tuple`, `frozenset`.


---

### **Data Structures**

**6. Q: How do you remove duplicates from a list while preserving order?**

**A:** Use `dict.fromkeys()` (Python 3.7+ preserves insertion order):

```python

lst = [1, 2, 2, 3]

unique = list(dict.fromkeys(lst)) # [1, 2, 3]

```

---

**7. Q: What is a dictionary comprehension? Give an example.**

**A:** A concise way to create dictionaries:

```python

squares = {x: x**2 for x in range(5)} # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

```

---

**8. Q: How do you merge two dictionaries?**

**A:** In Python 3.9+:

```python

d1 = {'a': 1}; d2 = {'b': 2}

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

```
Pre-3.9: `{**d1, **d2}` or `d1.update(d2)`.

---

**9. Q: What is the time complexity of `list.append()` vs `list.insert(0, x)`?**

**A:**

- `append()`: **O(1)** (amortized).

- `insert(0, x)`: **O(n)** (shifts all elements).

---

**10. Q: How do you sort a list of dictionaries by a key?**

**A:** Use `sorted()` with `key`:

```python

students = [{'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 20}]

sorted_students = sorted(students, key=lambda x: x['age'])

```

---

### **Functions & OOP**

**11. Q: What are `*args` and `**kwargs`?**

**A:**

- `*args`: Passes **variable positional arguments** as a tuple.

- `**kwargs`: Passes **variable keyword arguments** as a dict.

```python

def func(*args, **kwargs):


print(args) # (1, 2)

print(kwargs) # {'a': 3, 'b': 4}

func(1, 2, a=3, b=4)

```

---

**12. Q: Explain decorators with an example.**

**A:** Decorators wrap a function to extend behavior without modifying it:

```python

def log_time(func):

def wrapper(*args, **kwargs):

print(f"Calling {func.__name__}")

return func(*args, **kwargs)

return wrapper

@log_time

def greet():

print("Hello!")

```

---

**13. Q: What is the difference between `@staticmethod` and `@classmethod`?**

**A:**

- `@staticmethod`: No access to `cls` or `self`; behaves like a regular function.

- `@classmethod`: Gets `cls` (class) as first argument; often used for alternative
constructors.
```python

class Person:

@classmethod

def from_string(cls, s):

return cls(s.split()[0]) # Alternative constructor

```

---

**14. Q: What is `__init__`?**

**A:** The **constructor** method called when a new object is created. Initializes
instance attributes:

```python

class Dog:

def __init__(self, name):

self.name = name

```

---

**15. Q: How do you make a class iterable?**

**A:** Implement `__iter__` and `__next__` (or just `__iter__` returning a generator):

```python

class CountDown:

def __init__(self, start):

self.start = start

def __iter__(self):

n = self.start
while n > 0:

yield n

n -= 1

```

---

### **Advanced Concepts**

**16. Q: What is the GIL (Global Interpreter Lock)?**

**A:** The GIL is a mutex that allows **only one thread to execute Python bytecode at a
time**. It prevents true parallelism in CPU-bound multithreaded Python code (use
multiprocessing instead).

---

**17. Q: What are generators? How are they different from lists?**

**A:** Generators **yield items one at a time** (lazy evaluation), using less memory:

```python

def gen():

yield 1

yield 2

# vs list [1, 2] which stores all in memory

```

---

**18. Q: How does a context manager work?**


**A:** Context managers (used with `with`) handle setup/teardown via `__enter__`
and `__exit__`:

```python

class FileManager:

def __enter__(self):

self.file = open("test.txt")

return self.file

def __exit__(self, *args):

self.file.close()

with FileManager() as f:

print(f.read())

```

---

**19. Q: What is `__slots__` used for?**

**A:** `__slots__` restricts attributes to reduce memory usage (no `__dict__`):

```python

class Point:

__slots__ = ['x', 'y'] # Prevents adding other attributes

```

---

**20. Q: What are type hints? Give an example.**

**A:** Type hints specify expected data types (improve readability, not enforced at
runtime):

```python
def greet(name: str) -> str:

return f"Hello, {name}"

```

---

### **Coding Problems**

**21. Q: Check if a string is a palindrome (ignore case/symbols).**

**A:**

```python

def is_palindrome(s):

cleaned = ''.join(c.lower() for c in s if c.isalnum())

return cleaned == cleaned[::-1]

```

---

**22. Q: Find the first non-repeating character in a string.**

**A:**

```python

def first_unique(s):

from collections import Counter

count = Counter(s)

for char in s:

if count[char] == 1:

return char

return None
```

---

**23. Q: Reverse a string without slicing (`[::-1]`).**

**A:**

```python

def reverse_str(s):

return ''.join(reversed(s)) # or use a loop

```

---

**24. Q: Implement Fibonacci using recursion + memoization.**

**A:**

```python

from functools import lru_cache

@lru_cache(maxsize=None)

def fib(n):

if n <= 1:

return n

return fib(n-1) + fib(n-2)

```

---

**25. Q: Find two numbers in a list that sum to a target.**


**A:**

```python

def two_sum(nums, target):

seen = {}

for i, num in enumerate(nums):

complement = target - num

if complement in seen:

return [seen[complement], i]

seen[num] = i

```

---

### **Modules & Best Practices**

**26. Q: What is a virtual environment? Why use it?**

**A:** A virtual environment isolates project dependencies (e.g., `venv` or `conda`).


Prevents conflicts between package versions across projects.

---

**27. Q: How do you install packages in Python?**

**A:** Use `pip`:

```bash

pip install requests

pip install -r requirements.txt

```
---

**28. Q: What is the purpose of `if __name__ == "__main__":`?**

**A:** Ensures code runs **only when the script is executed directly** (not when
imported as a module).

---

### **Error Handling & Debugging**

**29. Q: How do you raise a custom exception?**

**A:**

```python

class CustomError(Exception):

pass

raise CustomError("Something went wrong!")

```

---

**30. Q: How do you debug Python code?**

**A:** Use:

- `print()` statements (quick & dirty)

- `logging` module (structured)

- Debugger: `import pdb; pdb.set_trace()` or IDE breakpoints.

---
These questions test **core knowledge**, **practical coding**, and **best
practices**—perfect for technical interviews!

You might also like