Python Interview Questions and Answers | Tutorials Logic
Tutorials Logic, IN +91 8092939553 info@tutorialslogic.com
Navigation
Home About Us Contact Us Blogs FAQs
Tutorials
All Tutorials
Services
Academic Projects Resume Writing Interview Questions Website Development
Compiler Tutorials
Python

Top 25 Python Interview Questions

Curated questions covering OOP, data structures, decorators, generators, async, and Python best practices.

01

What are Python's key features?

Python is an interpreted, dynamically typed, high-level language. Key features: readable syntax, extensive standard library, multiple paradigms (OOP, functional, procedural), garbage collection, and a large ecosystem (NumPy, Django, Flask, TensorFlow).

02

What is the difference between a list, tuple, and set?

  • List — ordered, mutable, allows duplicates. Use for sequences that change.
  • Tuple — ordered, immutable, allows duplicates. Use for fixed data; slightly faster than lists.
  • Set — unordered, mutable, no duplicates. Use for membership testing and removing duplicates.
Example
lst = [1, 2, 2, 3]   # list
tpl = (1, 2, 2, 3)   # tuple
st  = {1, 2, 3}      # set � no duplicates
03

What is the difference between a list and a dictionary?

A list is an ordered sequence accessed by index. A dictionary is an unordered (Python 3.7+ insertion-ordered) key-value store accessed by key. Dictionaries provide O(1) average lookup; lists provide O(n) search.

04

What are Python decorators?

Decorators are functions that wrap another function to extend its behaviour without modifying it. They use the @syntax. Common uses: logging, authentication, caching, timing.

Example
def log(func):
    def wrapper(*args, **kwargs):
        print(f"Calling {func.__name__}")
        return func(*args, **kwargs)
    return wrapper

@log
def greet(name):
    return f"Hello {name}"
05

What are generators in Python?

Generators are functions that use yield to produce values lazily, one at a time. They are memory-efficient for large sequences. A generator function returns a generator object.

Example
def fibonacci():
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b

gen = fibonacci()
print(next(gen))  # 0
print(next(gen))  # 1
06

What is the difference between *args and **kwargs?

*args collects extra positional arguments into a tuple. **kwargs collects extra keyword arguments into a dictionary. Both allow functions to accept variable numbers of arguments.

Example
def func(*args, **kwargs):
    print(args)   # (1, 2, 3)
    print(kwargs) # {"name": "Alice"}

func(1, 2, 3, name="Alice")
07

What is list comprehension?

List comprehension provides a concise way to create lists. It is more readable and often faster than equivalent for loops.

Example
squares = [x**2 for x in range(10)]
evens   = [x for x in range(20) if x % 2 == 0]
matrix  = [[i*j for j in range(3)] for i in range(3)]
08

What is the difference between is and ==?

== checks value equality (are the values the same?). is checks identity (are they the same object in memory?). Use == for value comparison; use is only for None checks (x is None).

09

What are Python's OOP concepts?

  • Encapsulation — bundling data and methods; use _ for protected, __ for private.
  • Inheritance — child class inherits from parent; use super() to call parent methods.
  • Polymorphism — same interface, different implementations.
  • Abstraction — hide implementation details using abstract classes (abc module).
10

What is the difference between @classmethod and @staticmethod?

  • @classmethod — receives the class (cls) as first argument; can access/modify class state.
  • @staticmethod — no implicit first argument; cannot access class or instance state; utility function.
Example
class MyClass:
    count = 0
    @classmethod
    def get_count(cls): return cls.count
    @staticmethod
    def helper(): return "utility"
11

What is the GIL (Global Interpreter Lock)?

The GIL is a mutex in CPython that allows only one thread to execute Python bytecode at a time. It simplifies memory management but limits true multi-threading for CPU-bound tasks. Use multiprocessing for CPU-bound parallelism; threading is fine for I/O-bound tasks.

12

What is the difference between deep copy and shallow copy?

Shallow copy (copy.copy()) creates a new object but references the same nested objects. Deep copy (copy.deepcopy()) creates a completely independent copy of all nested objects.

Example
import copy
original = [[1, 2], [3, 4]]
shallow  = copy.copy(original)
deep     = copy.deepcopy(original)
original[0][0] = 99
print(shallow[0][0])  # 99 (shared reference)
print(deep[0][0])     # 1  (independent)
13

What are Python's built-in data types?

  • Numeric: int, float, complex
  • Sequence: str, list, tuple, range
  • Mapping: dict
  • Set: set, frozenset
  • Boolean: bool
  • Binary: bytes, bytearray, memoryview
  • None: NoneType
14

What is exception handling in Python?

Python uses try/except/else/finally blocks. except catches specific exceptions; else runs if no exception occurred; finally always runs (cleanup).

Example
try:
    result = 10 / x
except ZeroDivisionError as e:
    print(f"Error: {e}")
except (TypeError, ValueError):
    print("Type or value error")
else:
    print(f"Result: {result}")
finally:
    print("Always runs")
15

What is the difference between range() and xrange()?

In Python 3, range() returns a lazy range object (like Python 2's xrange). xrange() does not exist in Python 3. range() is memory-efficient as it generates values on demand.

16

What are lambda functions?

Lambda functions are anonymous, single-expression functions. They are useful for short operations passed as arguments.

Example
square = lambda x: x ** 2
add    = lambda x, y: x + y
nums   = [3, 1, 4, 1, 5]
nums.sort(key=lambda x: -x)  # sort descending
17

What is the difference between map(), filter(), and reduce()?

  • map(func, iterable) — applies func to each element; returns iterator.
  • filter(func, iterable) — returns elements where func returns True.
  • reduce(func, iterable) — accumulates to a single value (from functools).
Example
from functools import reduce
nums = [1, 2, 3, 4, 5]
list(map(lambda x: x*2, nums))          # [2,4,6,8,10]
list(filter(lambda x: x%2==0, nums))    # [2,4]
reduce(lambda a, b: a+b, nums)          # 15
18

What is a context manager and the with statement?

Context managers handle setup and teardown automatically. The with statement calls __enter__ on entry and __exit__ on exit (even if an exception occurs). Used for file handling, database connections, and locks.

Example
with open("file.txt", "r") as f:
    data = f.read()
# file is automatically closed here
19

What is the difference between __str__ and __repr__?

__repr__ returns an unambiguous string representation for developers (used in the REPL). __str__ returns a readable string for end users (used by print()). If __str__ is not defined, Python falls back to __repr__.

20

What are Python's async/await features?

Python supports asynchronous programming with asyncio. async def defines a coroutine; await pauses execution until the awaited coroutine completes. Used for I/O-bound concurrent operations.

Example
import asyncio

async def fetch(url):
    await asyncio.sleep(1)  # simulate I/O
    return f"data from {url}"

async def main():
    results = await asyncio.gather(fetch("url1"), fetch("url2"))
    print(results)

asyncio.run(main())
21

What is the difference between mutable and immutable types?

  • Mutable — can be changed after creation: list, dict, set, bytearray.
  • Immutable — cannot be changed: int, float, str, tuple, frozenset, bytes.
  • Immutable objects are hashable and can be used as dictionary keys.
22

What is Python's MRO (Method Resolution Order)?

MRO determines the order in which base classes are searched when looking up a method. Python uses the C3 linearisation algorithm. Use ClassName.__mro__ or mro() to inspect it.

23

What are Python slots?

__slots__ restricts instance attributes to a fixed set, reducing memory usage by avoiding the per-instance __dict__. Useful for classes with many instances.

Example
class Point:
    __slots__ = ["x", "y"]
    def __init__(self, x, y):
        self.x = x
        self.y = y
24

What is the difference between a module and a package?

A module is a single .py file. A package is a directory containing an __init__.py file and multiple modules. Packages allow organising related modules into a namespace hierarchy.

25

What are Python type hints?

Type hints (PEP 484) add optional static type annotations to Python code. They improve readability and enable static analysis tools like mypy. They do not affect runtime behaviour.

Example
def greet(name: str, age: int) -> str:
    return f"{name} is {age}"

from typing import List, Optional
def process(items: List[int], limit: Optional[int] = None) -> List[int]:
    return items[:limit]

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.