Python Interview Questions and Answers
1. What are the key features of Python?
- Easy to learn and use
- Interpreted and dynamically typed
- Object-oriented
- Extensive standard libraries
- Cross-platform compatibility
2. What is the difference between list and tuple?
- List is mutable (modifiable), tuple is immutable.
- Lists use more memory, while tuples are memory efficient.
- Lists have more built-in functions compared to tuples.
3. What is the difference between 'is' and '=='?
- 'is' compares object identity (memory location).
- '==' compares values.
4. Explain *args and **kwargs in Python.
- *args allows passing multiple positional arguments.
- **kwargs allows passing multiple keyword arguments.
5. How do you implement a stack using a list?
class Stack:
def __init__(self):
self.stack = []
def push(self, item):
self.stack.append(item)
def pop(self):
return self.stack.pop() if self.stack else None
6. What is method overloading and method overriding?
- Method Overloading: Same method name but different parameters (not directly supported in
Python).
- Method Overriding: Child class redefines a method from the parent class.
7. How to read and write a file in Python?
with open('file.txt', 'r') as f:
content = f.read()
with open('file.txt', 'w') as f:
f.write('Hello World')
8. What is the difference between raise and assert?
- 'raise' is used to throw exceptions manually.
- 'assert' is used for debugging to check conditions.
9. How to read a CSV file using Pandas?
import pandas as pd
df = pd.read_csv('data.csv')
print(df.head())
10. Write a Python function to check if two strings are anagrams.
def is_anagram(str1, str2):
return sorted(str1) == sorted(str2)
print(is_anagram('listen', 'silent')) # True