Python Core Concepts - Part 1 (Questions 1-26)
Explore 26 carefully selected Python interview questions covering Core Data Types, OOP, Memory Management, and Decorators. This guide helps you build a strong foundation in Python fundamentals.
🧠 Core Data Types & Fundamentals
- 1. What are Python's core data types? IntegersFloatsStringsListTupleDictSetFrozenset
- 2. What is OOP in Python? Object-Oriented Programming (OOP) organizes code using classes and objects. Python supports key OOP concepts like inheritance, polymorphism, encapsulation, and abstraction.
- 3. What are the key differences between Python 2 and Python 3? • print is a function in Python 3, not a statement• Improved Unicode support by default• / performs true division, // for integer division• xrange() became range()• Better exception handling syntax
- 4. Explain mutable vs. immutable data types in Python Mutable types (e.g., lists, dictionaries, sets) can be changed after creation.Immutable types (e.g., strings, tuples, numbers) cannot be changed once created.
- 5. What is the Global Interpreter Lock (GIL) in Python? The GIL is a mechanism that synchronizes and manages thread execution. It allows only one thread to execute Python bytecode at a time, preventing deadlocks but limiting true parallelism. Use multiprocessing for CPU-bound parallel tasks.
- 6. How does Python's memory management work? 1. Everything in Python is an object2. Objects and data structures are stored in private heap space3. Python memory manager handles allocation and deallocation automatically4. Uses reference counting and garbage collection to free unused memory
7. What is memoryview in Python?
A view object for binary data without copying. It allows access to an object's internal buffer directly, improving performance for large data structures.- 8. What is garbage collection? Automatic memory cleanup of unreferenced/unused objects. Python uses reference counting combined with a cyclic garbage collector to handle circular references.
🎨 Decorators & Functions
- 9. What is a decorator in Python? Provide an example. A decorator is a function that modifies another function's behavior.
def my_decorator(func): def wrapper(*args, **kwargs): print("Before function call") result = func(*args, **kwargs) print("After function call") return result return wrapper @my_decorator def say_hello(): print("Hello!") say_hello() - 10. Explain
*argsand**kwargs*args passes variable non-keyword arguments (tuple)**kwargs passes keyword arguments as key-value pairs (dictionary)def example(*args, **kwargs): print(args) # (1, 2, 3) print(kwargs) # {'name': 'John', 'age': 25} example(1, 2, 3, name='John', age=25) - 11. What is a lambda function? When would you use it? A small anonymous one-liner function that can take any number of arguments but can only have one expression. Useful for short, one-time operations.
add = lambda x, y: x + y print(add(5, 3)) # Output: 8 # Common use with map, filter numbers = [1, 2, 3, 4] squared = list(map(lambda x: x**2, numbers))
📦 Data Structures
- 12. Differentiate between list and tuple List: Mutable, uses square brackets
[], used for ordered collections that can changeTuple: Immutable, uses parentheses(), used for fixed collections or record-like structures - 13. What are generators and iterators? How do they differ? Iterator: An object that can be iterated upon (e.g., lists, strings). Uses
__next__()method.Generator: A simple way to create iterators using functions withyieldstatements, producing values one at a time and saving memory.def my_generator(): yield 1 yield 2 yield 3 gen = my_generator() print(next(gen)) # 1 print(next(gen)) # 2
⚠️ Exception Handling
- 14. How do you handle exceptions in Python? Exceptions are handled using
try,except,else, andfinallyblocks.try: result = 10 / 0 except ZeroDivisionError: print("Cannot divide by zero!") except Exception as e: print(f"Error: {e}") else: print("No exception occurred") finally: print("This always executes") - 15. How can you handle multiple exceptions? Use tuples in except clause to catch multiple exception types.
try: # some code pass except (TypeError, ValueError) as e: print(f"Type or Value Error: {e}") - 16. Explain how async file I/O works Using
aiofilesorasynciofor non-blocking reads/writes, allowing other tasks to run while waiting for I/O operations.
🔧 Context Managers
- 17. What is a context manager? How do you create one? A context manager is an object that defines
__enter__and__exit__methods, ensuring resources are properly managed (e.g., files closed, locks released).class FileManager: def __init__(self, filename): self.filename = filename def __enter__(self): self.file = open(self.filename, 'r') return self.file def __exit__(self, exc_type, exc_val, exc_tb): self.file.close() # Usage with FileManager('file.txt') as f: content = f.read() - 18. Explain the purpose of
__init__.pyin a Python package__init__.pysignals to Python that a directory should be treated as a package. It can also contain initialization code for the package or define__all__for explicit exports.
🌐 Environment & Best Practices
- 19. What is a virtual environment and why is it important? A virtual environment (venv) is an isolated Python environment that allows you to install project-specific dependencies without interfering with other projects or the global Python installation.
# Create virtual environment python3 -m venv myenv # Activate (Linux/Mac) source myenv/bin/activate # Activate (Windows) myenv\Scripts\activate # Deactivate deactivate
- 20. What is PEP 8? PEP 8 is Python's official style guide, providing conventions for writing readable and consistent Python code (e.g., indentation, naming conventions, line length of 79 characters).
🎯 OOP Concepts
21. What is @staticmethod vs @classmethod?
@staticmethod doesn't access the class or instance, used for utility functions@classmethod receives the class (cls) as first argument, used for factory methodsclass MyClass: @staticmethod def static_method(): print("Static method") @classmethod def class_method(cls): print(f"Class method of {cls}")- 22. How do you implement inheritance in Python? Inheritance allows a class (child) to inherit attributes and methods from another class (parent).
class Animal: def speak(self): return "Generic sound" class Dog(Animal): # Dog inherits from Animal def speak(self): return "Woof!" dog = Dog() print(dog.speak()) # Output: Woof! - 23. What are comprehensions (list, dict, set)? Compact syntax to create lists, dictionaries, or sets from existing iterables.
# List comprehension squares = [x**2 for x in range(10) if x % 2 == 0] # [0, 4, 16, 36, 64] # Dict comprehension square_dict = {x: x**2 for x in range(5)} # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16} # Set comprehension unique_squares = {x**2 for x in [1, 2, 2, 3, 3]} # {1, 4, 9} 24. Describe
super()and its use casesuper()provides a way to call methods of a parent class from a child class, especially useful in__init__or when overriding methods to extend functionality.class Parent: def __init__(self, name): self.name = name class Child(Parent): def __init__(self, name, age): super().__init__(name) self.age = age25. What is the difference between
==andis?== checks for value equalityis checks for identity (if two variables refer to the exact same object in memory)a = [1, 2, 3] b = [1, 2, 3] c = a print(a == b) # True (same values) print(a is b) # False (different objects) print(a is c) # True (same object)
26. What is the purpose of
__slots__in a class?__slots__defines a fixed set of attributes for instances of a class, saving memory by preventing the creation of__dict__for each instance.class Point: __slots__ = ['x', 'y'] def __init__(self, x, y): self.x = x self.y = y # This saves memory for large numbers of instances