Skip to main content

Python Interview Questions (Fundamentals)

A comprehensive guide to Python interview questions, organized by category. This collection covers fundamental syntax to advanced concepts for the 2025 edition.

1. Python Basics

Answer: Python is a high-level, interpreted, and general-purpose programming language created by Guido van Rossum in 1991.Key Features:
  • Easy to Learn/Read: Simple syntax that resembles English.
  • Interpreted: Code is executed line-by-line, no separate compilation needed.
  • Dynamically Typed: Variable types are determined at runtime.
  • Object-Oriented: Supports classes and object encapsulation.
  • Extensive Libraries: Massive standard library for almost any task.
  • Cross-platform: Runs on Windows, Linux, and macOS.
Answer: Python provides several built-in types to handle different data structures:
CategoryTypes
Numericint, float, complex
Sequencelist, tuple, range, str
Mappingdict
Setset, frozenset
Booleanbool
None TypeNoneType
Answer:
FeatureListsTuples
MutabilityMutable (can change)Immutable (cannot change)
SyntaxSquare brackets []Parentheses ()
PerformanceSlowerFaster
MethodsMany built-in methodsFewer methods
Use CaseFrequent modificationsFixed data / Constants
Answer:
  • Mutable: Objects that can be modified after creation.
    • Examples: list, dict, set, and custom class objects.
    • Example: l = [1]; l[0] = 2 (Works)
  • Immutable: Objects that cannot be changed once created. Any modification creates a new object.
    • Examples: int, float, str, tuple, frozenset.
    • Example: s = 'hi'; s[0] = 'H' (Raises TypeError)
Answer: Identify operators check if two variables reference the same object in memory, not just if they have the same value.
a = [1, 2, 3]
b = a
c = [1, 2, 3]

print(a is b)      # True (same reference)
print(a is c)      # False (different reference, even if values match)
print(a == c)      # True (values are equal)
Answer:
  • Variables/Functions: snake_case (e.g., calculate_sum).
  • Classes: PascalCase (e.g., MyClass).
  • Constants: UPPER_CASE (e.g., MAX_RETRIES).
  • Private Variables: Single underscore prefix (_private).
  • Avoid: Single letters except for loops (i, j, k).
Answer:
  • == checks for Equality (Do they have the same value?).
  • is checks for Identity (Do they point to the exact same memory address?).
x = [1, 2]
y = [1, 2]
print(x == y) # True
print(x is y) # False
Note: Commonly used with None checks: if val is None:.
Answer: Used to test if a sequence (string, list, tuple, etc.) contains a specific value.
'a' in 'apple'         # True
5 in [1, 2, 3]         # False
'key' in {'key': 1}    # True (checks dictionary keys)

2. Data Structures

Answer: Common operations for list:
  • append(x): Adds x to the end.
  • insert(i, x): Inserts x at index i.
  • remove(x): Removes the first occurrence of x.
  • pop(): Removes and returns the last element.
  • extend(iter): Adds all elements from an iterable.
  • sort(): Sorts the list in place.
Answer: A concise way to create lists. Syntax: [expression for item in iterable if condition]
squares = [x**2 for x in range(10)]
evens = [x for x in range(20) if x % 2 == 0]
Answer: Unordered collections of key-value pairs. Keys must be immutable.
  • get(key, default): Safely access values without raising errors.
  • keys() / values() / items(): Views of the dictionary components.
  • update(other_dict): Merge another dictionary into the current one.
Answer:
  • Set: Mutable, unordered collection of unique elements. Supports add() and remove().
  • Frozenset: Immutable version of a set. Can be used as a dictionary key or an element of another set.
Answer:
OperationOperatorMethod
Union``set1.union(set2)
Intersection&set1.intersection(set2)
Difference-set1.difference(set2)
Sym. Diff^set1.symmetric_difference(set2)
Answer: Work on strings, lists, and tuples:
  • text[0]: Access first element.
  • text[1:4]: Slice from index 1 to 3.
  • text[::-1]: Reverse the sequence.
  • len(text): Get length.
Answer: Use the sorted() function with a lambda as the key parameter.
students = [{'name': 'John', 'age': 25}, {'name': 'Jane', 'age': 22}]
# Sort by age
sorted_list = sorted(students, key=lambda x: x['age'])
Answer:
  • Shallow Copy: Creates a new container, but elements inside still refer to the original objects.
  • Deep Copy: Creates a new container and recursively copies every object inside it (completely independent).
import copy
shallow = copy.copy(original)
deep = copy.deepcopy(original)

3. Object-Oriented Programming

Answer:
  1. Encapsulation: Bundling data and methods, hiding internal state.
  2. Abstraction: Hiding complexity and showing only necessary features.
  3. Inheritance: Creating new classes based on existing ones.
  4. Polymorphism: Ability for different objects to respond to the same method call differently.
Answer:
class Person:
    def __init__(self, name, age):
        self.name = name  # Instance attribute
        self.age = age

    def greet(self):
        return f"Hi, I'm {self.name}"

p1 = Person("Adam", 30)
Answer:
  • Instance: Accesses self. Standard method.
  • Class: Accesses cls. Decorated with @classmethod. Operates on class state.
  • Static: No access to self or cls. Decorated with @staticmethod. Just a utility function.
Answer: Inheritance allows code reuse. super() is used to call methods (usually the constructor) from the parent class.
class Animal:
    def speak(self): return "Mute"

class Dog(Animal):
    def speak(self): return "Woof"
Answer: Special methods starting and ending with __.
  • __init__: Constructor.
  • __str__: Human-readable string representation.
  • __repr__: Detailed developers representation.
  • __len__: Custom length logic.
  • __add__: Operator overloading for +.
Answer: Allows methods to be accessed like attributes while providing “Getter” and “Setter” logic.
class User:
    def __init__(self, age): self._age = age
    
    @property
    def age(self): return self._age
    
    @age.setter
    def age(self, value):
        if value < 0: raise ValueError("Age can't be negative")
        self._age = value

4. Functions and Decorators

Answer:
  • *args: Accepts a variable number of positional arguments (as a tuple).
  • **kwargs: Accepts a variable number of keyword arguments (as a dictionary).
Answer: Small anonymous functions. Limited to a single expression. square = lambda x: x * x
Answer: Functions that wrap another function to modify its behavior without changing its source code.
def my_decorator(func):
    def wrapper():
        print("Before")
        func()
        print("After")
    return wrapper

@my_decorator
def say_hi(): print("Hi")
Answer: A function that “remembers” variables from its enclosing scope even after the outer function has finished execution.
Answer: Generators produce values one at a time using yield. They are memory efficient because they don’t store the whole sequence in RAM.
def count_to_three():
    yield 1
    yield 2
    yield 3

5. File Handling and I/O

Answer: Always use the with statement (context manager) to ensure files are closed properly.
# Reading
with open('file.txt', 'r') as f:
    content = f.read()

# Writing ('w' overwrites, 'a' appends)
with open('file.txt', 'w') as f:
    f.write("Hello")
Answer:
import json
data = {"id": 1}
string = json.dumps(data)  # To String
obj = json.loads(string)   # From String

6. Exception Handling

Answer: Used to handle errors gracefully.
try:
    x = 1 / 0
except ZeroDivisionError:
    print("Cannot divide by zero")
Answer:
  • else: Runs if NO exception occurred.
  • finally: ALWAYS runs (cleanup code).

8. Advanced Concepts

Answer:
  • Iterable: Any object you can loop over (List, Tuple). Implements __iter__.
  • Iterator: The actual object that tracks state during iteration. Implements __next__.
Answer:
  • Multithreading: Shares memory. Best for I/O-bound tasks. Subject to the GIL.
  • Multiprocessing: Separate memory space. Best for CPU-bound tasks. True parallelism.
Answer: A mutex that allows only one thread to execute Python bytecode at a time. It prevents race conditions in memory management but limits CPU-bound multithreaded performance.

10. Data Science & Numerical Python

Answer: A library for high-performance numerical computing. It provides ndarray, which is faster and more memory-efficient than Python lists for mathematical operations.
Answer: A library for data manipulation and analysis. Key structures are Series (1D) and DataFrame (2D table).

Additional Important Topics

Answer:
  • enumerate(iterable): Adds a counter (index) to an iterable.
  • zip(*iterables): Aggregates elements from multiple iterables into tuples.
Answer: Generates a sequence of numbers. In Python 3, it’s a “range object” (lazy), not a static list, making it memory efficient.
Answer: The official style guide for Python code. Key rules:
  • Use 4 spaces for indentation.
  • Limit lines to 79 characters.
  • Use blank lines to separate functions/classes.
  • Imports should be at the top.