Python Interview Questions and Answers

Python interview questions and answers for 2026: basics, data types, OOP, advanced features, files and modules, coding programs, India salary bands, and a Chennai prep plan. DSA and aptitude stay on separate hubs.

PragadeeshSeptember 8, 2026
Python Interview Questions and Answers
Summarize this article in
Quick Answer
  • This is the Python language interview guide - 110 questions with compiler-style samples.
  • DSA, coding patterns, company OA, and aptitude live on separate Asmorix hubs.
  • Most repeated depth: list vs tuple, dict internals, is vs ==, decorators, GIL.
  • Coding set: palindrome, Fibonacci, duplicates, two-sum, word frequency.
  • Planning salary: Python freshers roughly Rs.3.5-6 LPA - not guaranteed.

Python interview questions and answers in 2026 cover language fundamentals, data types, OOP, advanced features, files and modules, and short coding drills - but Chennai fresher panels now expect you to speak clearly before you paste syntax. This is the full language guide at Python interview questions and answers (no number in the URL), written so every answer opens with a direct first sentence you can say in under a minute.

Last updated: September 9, 2026 - Reviewed by Asmorix Python mentors in Chennai

Asmorix mentors compiled these from TCS/Infosys services drives, startup product screens, and GCC loops across OMR and Guindy. Pair this page with Python training in Chennai, JavaScript interview questions, Java interview questions, and more on the Asmorix blog.

How Python Interviews Are Structured in India (2026)

Most Python fresher and 0-3 year loops in Chennai follow four rounds. Know the filter before you memorize 110 answers:

RoundWhat is testedTypical filter
Online assessment (OA)Aptitude, logical reasoning, 1-2 easy Python coding problemsWorking code with edge cases beats clever but broken logic
Technical round 1Python basics, data types, OOP, small programsDirect first sentence plus one concrete example
Technical round 2Decorators, generators, GIL, files, project deep-diveCan you explain WHY Python behaves that way
Managerial / HRCommunication, relocation, salary fit, notice periodStructured, honest answers without overselling

Key takeaway: interviewers reward a crisp first sentence, then a short example - exactly how every answer below is structured for answer-engine and spoken delivery.

Python Basics Interview Questions and Answers (Q1-Q20)

1. What is Python?

Python is a high-level, dynamically typed programming language known for readable syntax and a vast standard library. It runs on an interpreter and powers web backends, data pipelines, automation, and ML tooling across India. Interviewers follow up with where you used it in college or internship projects - mention one script you actually shipped. Chennai services drives treat Python as a scripting plus backend skill, not just a data-science tag.

2. Is Python interpreted or compiled?

Python source is compiled to bytecode first, then executed by the CPython interpreter - so it is both compiled and interpreted in practice. The .pyc files you see are cached bytecode, not machine code like C output. Follow-up: PyPy and Cython add JIT or native compilation layers for performance-critical paths. Saying "interpreted with a bytecode step" sounds sharper than "only interpreted" in Guindy product panels.

3. Why did the industry move from Python 2 to Python 3?

Python 3 fixed Unicode handling, print as a function, and division semantics while Python 2 reached end of life in 2020. All new Chennai hiring assumes Python 3.8+ with f-strings and type hints available. Mention you never start greenfield code on Python 2 - interviewers use this as a maturity filter.

4. Why does indentation matter in Python?

Indentation defines code blocks instead of braces, so inconsistent spaces cause IndentationError before logic even runs. PEP 8 recommends four spaces per level; tabs mixed with spaces break teams. Follow-up: you can use a single line after a colon only for trivial statements, but multi-line blocks must align. OA proctors reject submissions that look copied but fail on whitespace.

5. What is dynamic typing in Python?

Variable names bind to objects at runtime without declaring types upfront - the same name can refer to an int, then a string, later in the program. Types live on objects, not on variable names. Static type checkers like mypy add optional compile-time checks without changing runtime behavior. Chennai captives ask whether dynamic typing means "no types" - answer no, types exist on objects.

6. What is PEP 8 and why should you follow it?

PEP 8 is the official Python style guide covering naming, spacing, imports, and line length for readable team code. Interviewers expect snake_case functions, CapWords classes, and imports grouped stdlib / third-party / local. Following PEP 8 shows you can join a shared codebase without stylistic fights. Mention you run flake8 or ruff in CI when seniors probe tooling.

7. What does if __name__ == "__main__": do?

It runs a block only when the file is executed directly, not when imported as a module. The interpreter sets __name__ to "__main__" for the entry script and to the module name otherwise. This pattern keeps reusable functions import-safe while allowing a CLI demo block. Every Chennai coding round expects you to guard main() this way.

8. How do variable names work in Python?

Names are labels bound to objects in namespaces - assignment never copies objects unless you explicitly call copy methods. Valid names use letters, digits, and underscores but cannot start with a digit. Follow-up: deleting a name with del x removes the binding, not necessarily the object on the heap. Use descriptive snake_case names; single-letter loops are fine inside short loops.

9. What is a docstring and where does it go?

A docstring is the first string literal in a module, class, or function, stored in __doc__ for help() and documentation tools. Triple quotes allow multi-line API descriptions without comments. Interviewers prefer docstrings over inline comments for public functions. One sentence plus Args/Returns is enough in fresher projects.

10. What is the difference between print() and return?

print() sends text to stdout for humans; return passes a value back to the caller for further computation. Functions that only print are hard to test; returning values keeps logic reusable. Follow-up: print side effects do not affect function output in unit tests. Chennai OAs often fail candidates who print instead of return the required result.

11. How does input() work in Python 3?

input() reads a line from stdin as a string and optionally shows a prompt message. You must cast to int or float yourself when numeric input is needed. Always validate or try/except conversion failures in production-style answers. Mock interviews in Chennai sometimes ask you to read two numbers and sum them live.

12. Explain the range() function.

range(stop), range(start, stop), or range(start, stop, step) produces an immutable sequence of integers without storing the whole list in memory. It is lazy like a generator until you force list(range(...)). Follow-up: range(5) yields 0 through 4, not 5. Use it in for loops instead of manual index counters when possible.

13. What do break, continue, and pass do?

break exits the nearest loop entirely, continue skips to the next iteration, and pass is a no-op placeholder for syntactically required blocks. Pass appears in empty class stubs or TODO branches. Interviewers ask which stops a while search early - answer break. These three show up in almost every FizzBuzz or search follow-up.

14. How does if / elif / else chaining work?

Python evaluates conditions top to bottom and runs the first true branch, skipping the rest. There is no switch statement until match in 3.10+, so elif chains handle multi-way logic. Keep conditions readable; nested ternaries confuse whiteboard reviewers. Chennai panels like one clear example with grades or HTTP status codes.

15. When do you choose a for loop over a while loop?

Use for when iterating a known sequence or range; use while when the stop condition is logical rather than length-based. For loops are harder to mis-infinite if the iterable is bounded. Follow-up: while True with break implements event loops and menu systems. Pick the loop that states intent in one glance.

16. Name five useful built-in functions in Python.

Common built-ins include len(), sum(), max(), sorted(), and type() - all available without imports. Built-ins operate on core protocols like iteration and comparison. Interviewers may ask you to implement sum manually to test loops. Knowing builtins saves time in timed OAs across Chennai IT parks.

17. What does id() return?

id(obj) returns an integer identity, typically the memory address of the object in CPython. Two names refer to the same object when id(a) == id(b). This ties directly to is versus == questions later. Do not treat id values as stable across sessions - only for same-process reasoning.

18. What is the difference between type() and isinstance()?

type(x) returns the exact class of an object, while isinstance(x, cls) returns True for subclasses too. Prefer isinstance for polymorphic checks in application code. type checks fail for inherited types unless you compare exactly. Chennai OOP round two often chains this with ABC questions.

19. What are mutable and immutable types in Python?

Mutable objects can change in place (list, dict, set); immutable objects cannot after creation (int, float, str, tuple, frozenset). Assignment to an immutable "changes" by binding a new object, not mutating the old one. Follow-up: default arguments with mutable defaults are a classic bug - never def f(x=[]). This concept drives copy and hashability answers.

20. How does Python pass arguments to functions?

Python passes object references by value - the reference is copied, but both caller and callee may point to the same mutable object. Rebinding a parameter name inside a function does not affect the caller's variable. Mutating a shared list is visible outside - a frequent trap in fresher interviews. Say "pass-by-object-reference" to sound precise in GCC screens.

Python Data Types Interview Questions and Answers (Q21-Q35)

21. What is a Python list?

A list is an ordered, mutable sequence that can hold mixed types and grows dynamically. Lists support append, insert, slice, and comprehension syntax for concise construction. They are the default workhorse collection in scripting interviews. Mention amortized O(1) append but O(n) insert at front when seniors ask performance.

22. What is a Python tuple?

A tuple is an ordered, immutable sequence, often used for fixed records like coordinates or DB rows. Immutability makes tuples hashable when all elements are hashable - usable as dict keys. Follow-up: a tuple with a mutable list inside is not fully immutable behaviorally. Chennai data-engineering roles use tuples for lightweight rows.

23. What is the difference between a list and a tuple?

Lists are mutable and use square brackets; tuples are immutable and use parentheses (or bare commas). Choose tuples for fixed collections you should not accidentally mutate; lists for dynamic data. Tuples save slight memory and signal intent to readers.

nums = [1, 2, 3]
point = (10, 20)
nums.append(4)
# point[0] = 5  # TypeError
print(nums, point)
Output([1, 2, 3, 4], (10, 20))

24. How does a Python dictionary work?

A dict maps hashable keys to values in average O(1) lookup time using a hash table under the hood since Python 3.7 with insertion order preserved. Keys must be hashable; values can be anything. Interviewers ask about collision handling at a high level - Python probes open addressing. Dicts are the default JSON-like structure in API code.

25. What are set and frozenset?

A set is an unordered collection of unique hashable elements with union, intersection, and difference operations. frozenset is the immutable, hashable counterpart usable inside other sets or dict keys. Use sets to dedupe or test membership fast. Follow-up: {} creates an empty dict, not a set - use set() instead.

26. How are Python strings implemented?

Strings are immutable sequences of Unicode code points, not fixed byte arrays. Operations like slice and concat create new string objects. Encoding (str to bytes) and decoding (bytes to str) are explicit with utf-8 in modern code. Chennai web roles expect you to mention Unicode when handling Indian language text.

27. What is the difference between is and ==?

is checks object identity (same id); == checks value equality via __eq__. Use is only for singletons like None, True, and False - not for equal content. Small integer caching can make is appear to work for numbers - still prefer == for values.

a = [1, 2]
b = [1, 2]
c = a
print(a == b)
print(a is b)
print(a is c)
OutputTrue False True

28. What is None in Python?

None is a singleton object meaning "no value" or missing result, returned by functions that do not explicitly return. Always compare with is None, not == None, though == often works. Follow-up: None is falsy in boolean context. Defaulting parameters to None is the idiomatic optional-argument pattern.

29. Explain slicing in Python.

Slicing seq[start:stop:step] returns a sub-sequence without including the stop index; omitted bounds use defaults. Negative indices count from the end. Slices on lists create shallow copies of the sliced portion. Reversing with [::-1] is a common interview one-liner for strings.

30. What is a list comprehension?

A list comprehension builds a new list with [expr for item in iterable if condition] in one readable expression. It is often faster and clearer than manual append loops for simple transforms. Keep comprehensions short - nested ones hurt readability. Interviewers ask you to rewrite a loop as a comprehension live.

squares = [n * n for n in range(6) if n % 2 == 0]
print(squares)
Output[0, 4, 16]

31. What is a dictionary comprehension?

Dict comprehensions use {key_expr: val_expr for item in iterable} to build mappings compactly. They mirror list comprehension syntax with curly braces and key-value pairs. Useful for inverting maps or counting with logic. Same readability rule: if it needs two lines of explanation, use a loop.

32. What is a set comprehension?

Set comprehensions look like {expr for item in iterable} and produce a set of unique values. Duplicates drop automatically because sets enforce uniqueness. Handy for unique word tokens or normalized IDs. Mention that {} alone is still an empty dict, not a set comprehension.

33. What is the difference between shallow copy and deep copy?

Shallow copy duplicates the container but shares nested objects; deep copy recursively clones nested structures too. Use copy.copy() versus copy.deepcopy() from the copy module. Assignment never copies - it aliases. This matters when passing lists into functions that mutate in place.

34. Explain *args and **kwargs.

*args collects extra positional arguments into a tuple; **kwargs collects extra keyword arguments into a dict. They let wrappers forward arguments to inner functions cleanly. Order in definitions is: positional, *args, keyword-only, **kwargs. Decorators and API wrappers in Chennai Django shops use this daily.

def demo(a, *args, **kwargs):
    print(a, args, kwargs)

demo(1, 2, 3, x=10, y=20)
Output1 (2, 3) {'x': 10, 'y': 20}

35. What do enumerate() and zip() do?

enumerate(iterable) yields (index, item) pairs; zip(a, b) pairs elements from multiple iterables until the shortest exhausts. Both remove manual index arithmetic in loops. Follow-up: zip(*matrix) transposes rows to columns. These two functions appear in word-frequency and two-sum style drills.

Python OOP Interview Questions and Answers (Q36-Q50)

36. How does OOP work in Python?

Python supports OOP with classes, inheritance, and polymorphism without forcing everything into classes - functions remain first-class. Objects are dict-like namespaces with method lookup via the class MRO. Interviewers expect you to mix procedural scripts with small classes where state matters. Chennai Django teams still ask OOP even for scripting roles.

37. What is the difference between a class and an instance?

A class is the blueprint; an instance is a concrete object created with ClassName() carrying its own attribute dict. One class can spawn many instances with separate state. Follow-up: class attributes are shared unless shadowed on the instance. Draw two boxes sharing one class block on paper if asked.

38. What are __init__ and self?

__init__ initializes a new instance after creation; self is the conventional first parameter referring to that instance. __init__ is not the constructor - __new__ allocates first, rarely overridden. Always name the first parameter self for readability, not because Python requires the word self.

class Employee:
    def __init__(self, name, salary):
        self.name = name
        self.salary = salary

    def hike(self, pct):
        self.salary *= 1 + pct

e = Employee("Anita", 500000)
e.hike(0.1)
print(e.name, e.salary)
OutputAnita 550000.0

39. What is the difference between class variables and instance variables?

Class variables are defined on the class and shared by all instances unless overridden per instance. Instance variables are set on self and belong to one object. Mutating a mutable class variable through one instance can surprise teammates. Interviewers trap candidates who use class vars for counters without understanding sharing.

40. How does inheritance work in Python?

A subclass lists parent classes in parentheses and inherits attributes and methods, overriding as needed. Python supports multiple inheritance with C3 MRO ordering. super() delegates to the next class in MRO, not always the parent name you expect. See composition answers when inheritance is only for code reuse.

41. What is MRO (Method Resolution Order)?

MRO is the order Python searches classes when resolving an attribute, computed by the C3 linearization algorithm. Print it with ClassName.mro() or __mro__ during study. Diamond inheritance relies on MRO to pick one implementation. Senior panels in Bengaluru-style GCCs ask you to trace MRO on paper.

42. What does super() do?

super() returns a proxy to the next class in MRO so you can call parent implementations without hardcoding parent names. In Python 3, zero-argument super() inside instance methods resolves automatically. Use it to extend, not accidentally replace, parent behavior. Cooperative multiple inheritance depends on super() chains.

43. How does encapsulation work in Python?

Encapsulation hides internal state behind methods; Python uses convention: single leading underscore for protected, double for name mangling (__attr). There is no true private keyword - trust team conventions and properties. @property exposes controlled getters/setters without breaking API. Banking captives like examples that validate before set.

44. What are dunder (magic) methods?

Dunder methods like __len__, __getitem__, and __enter__ hook into Python syntax and built-ins. They let custom classes behave like built-in types. Implement __repr__ for developers and __str__ for users at minimum. Interviewers ask which dunder makes an object iterable - __iter__.

45. What is the difference between @staticmethod and @classmethod?

A staticmethod needs no class or instance; a classmethod receives the class as first arg (cls) and can override constructors or alternate factories. Use classmethod for inherited factory patterns; staticmethod for helpers logically grouped in the class. Neither receives self automatically. Pick based on whether the method needs cls.

46. What does the @property decorator do?

@property turns a method into a getter accessed like an attribute, with optional setter/deleter via @name.setter. It enforces validation while keeping call sites clean. Prefer properties over get/set methods in Pythonic APIs. Follow-up: dataclasses can combine with property for computed fields.

47. What are Abstract Base Classes (ABC)?

ABCs in the abc module define interfaces with @abstractmethod that subclasses must implement before instantiation. They document contracts better than duck typing alone for large teams. Instantiate fails until all abstract methods exist. Chennai product shops use ABCs sparingly but expect you to name the module.

48. Composition vs inheritance in Python - when to choose?

Prefer composition (has-a) when behavior can be swapped without fragile parent coupling; use inheritance (is-a) for true subtype relationships. Mixins are a middle ground for shared behaviors. Python's multiple inheritance favors small mixins over deep trees. Say "favor composition for reuse, inheritance for substitutability."

49. Does Python support multiple inheritance?

Yes - a class can inherit from several parents, with MRO resolving method lookup order. Keep hierarchies shallow; mixins should be small and focused. Conflicting methods resolve by MRO, not arbitrary choice. Interviewers may ask about diamond problem - C3 MRO is the answer.

50. What is the difference between __str__ and __repr__?

__str__ targets readable output for end users; __repr__ should ideally be unambiguous for developers and often recreate-able. print() uses str; repr() uses __repr__. If you implement one, implement __repr__ first. Logging and debugging in Chennai ops teams rely on good repr.

Python Advanced Interview Questions and Answers (Q51-Q70)

51. What is a lambda function?

A lambda is an anonymous one-expression function defined with lambda args: expr. Use it for short callbacks like sort keys, not multi-statement logic. Lambdas cannot contain statements or annotations richly. Interviewers accept lambda in sorted() but prefer def for anything readable.

52. Explain map() and filter().

map(func, iterable) applies func to each item; filter(func, iterable) keeps items where func returns truthy. Both return iterators in Python 3, not lists - wrap list() when you need materialized output. List comprehensions often replace both with clearer syntax. Still know map/filter for legacy codebases and interviews.

53. What is a decorator in Python?

A decorator is a callable that wraps another function to add behavior without changing its source, applied with @syntax. Decorators are functions returning inner wrappers, often using functools.wraps to preserve metadata. They power logging, timing, auth checks, and route registration in Flask/Django. Expect a follow-up to write a simple timer decorator.

def log(fn):
    def wrapper(*a, **k):
        print('call', fn.__name__)
        return fn(*a, **k)
    return wrapper

@log
def add(x, y):
    return x + y

print(add(2, 3))
Outputcall add 5

54. What are generators and the yield keyword?

Generators are iterators produced by functions containing yield, pausing state between values lazily. They save memory on large sequences versus building full lists. yield from delegates to sub-generators. Chennai data roles love generator examples for streaming log lines.

def countdown(n):
    while n > 0:
        yield n
        n -= 1

for x in countdown(3):
    print(x, end=' ')
Output3 2 1

55. What is the GIL in CPython?

The Global Interpreter Lock is a mutex letting one thread execute Python bytecode at a time in CPython, limiting CPU-bound multithreading speedups. I/O-bound threads still help because they release the GIL while waiting. CPU-bound parallelism uses multiprocessing or native extensions. Say GIL is a CPython implementation detail, not a Python language rule.

56. When do you use threading versus multiprocessing in Python?

Use threading for I/O-bound work (network, disk) where waiting dominates; use multiprocessing for CPU-bound parallelism across cores. Threads share memory; processes have separate memory with higher startup cost. asyncio is a third path for concurrent I/O without thread overhead. Match the tool to the bottleneck.

57. What is a context manager and the with statement?

Context managers define __enter__ and __exit__ (or @contextmanager) to set up and tear down resources reliably. with open(...) as f ensures files close even on exceptions. Prefer with over manual try/finally for resources. Interviewers tie this to exception safety in file questions.

class Tag:
    def __init__(self, name):
        self.name = name
    def __enter__(self):
        print('open', self.name)
        return self
    def __exit__(self, exc_type, exc, tb):
        print('close', self.name)

with Tag('report') as t:
    print('work', t.name)
Outputopen report work report close report

58. How does exception handling work in Python?

try runs code, except catches matching exceptions, else runs if no exception, finally always runs cleanup. Catch specific exceptions before broad Exception. Never use bare except in production code. Mention logging the error and re-raising when appropriate.

59. How do you create custom exceptions?

Subclass Exception (or a narrower base) with class MyError(Exception): pass and optionally add attributes in __init__. Custom types let callers handle domain failures distinctly. Keep hierarchies shallow. Banking panels like ValidationError versus PaymentError examples.

60. What do else and finally do in try/except?

else runs when no exception occurred in try; finally runs always before leaving the block, even on return. finally is for cleanup, not normal logic. else avoids accidentally catching exceptions from except blocks mixed with success paths. Rare in fresher code but shows mastery.

61. What is an iterator?

An iterator is an object with __iter__ returning self and __next__ raising StopIteration when done. iterables produce iterators via iter(). for loops call __next__ under the hood. Generators are a convenient iterator factory.

62. What is functools.partial?

partial(func, *args, **kwargs) fixes some arguments, returning a new callable with the rest open. Useful for callbacks needing preset configuration. It differs from lambda when readability matters. Appears in GUI and async callback code.

63. What is a closure in Python?

A closure is an inner function remembering variables from its enclosing scope after the outer function returns. Nonlocal binds updates to those captured names. Closures power decorators and factory functions. Interviewers ask you to write a counter or multiplier factory.

64. What does "functions are first-class" mean?

Functions can be assigned to variables, passed as arguments, returned from other functions, and stored in data structures. This enables functional patterns and decorators natively. Languages without first-class functions need interfaces or functors instead. Python's map/filter style depends on this.

65. What are global and nonlocal?

global declares a name refers to module-level scope inside a function; nonlocal binds to the nearest enclosing function scope, not globals. Use sparingly - prefer passing parameters and return values. Closures updating counters need nonlocal. Misuse creates hard-to-debug shared state.

66. What is the walrus operator :=?

The walrus operator assigns and returns a value in one expression, as in while (line := f.readline()):. It reduces duplication when you need both test and value. Added in Python 3.8. Do not overuse where a plain assignment before the loop is clearer.

67. What are type hints in Python?

Type hints annotate expected types for parameters and return values using syntax like def f(x: int) -> str without enforcing types at runtime. mypy and pyright check them statically in CI. They improve readability in large Chennai product codebases. Runtime behavior unchanged unless you use a validator library.

68. What are dataclasses?

The dataclass decorator auto-generates __init__, __repr__, and comparison methods for data-focused classes. Use @dataclass with field() for defaults and metadata. They reduce boilerplate versus manual classes for DTOs. Interviewers accept dataclass over handwritten __init__ for config objects.

69. What do async and await do?

async def defines a coroutine; await suspends it until an awaitable completes, enabling concurrent I/O without blocking threads. asyncio runs coroutines on an event loop. async helps network services, not CPU-heavy loops without multiprocessing. FastAPI interviews in Chennai probe async basics.

70. How does Python manage memory and garbage collection?

Reference counting frees objects immediately when refcount hits zero; a cyclic garbage collector handles reference cycles periodically. del removes a name binding, not necessarily instant reclaim. CPython may not return memory to the OS immediately. Mention gc module only when discussing cycles in graphs.

Python Files and Modules Interview Questions and Answers (Q71-Q80)

71. How does the import statement work?

import loads a module once, caches it in sys.modules, and binds names in the current namespace. import foo versus from foo import bar changes whether you need the module prefix. Avoid wildcard imports from foo import * in production. Circular imports are a design smell - refactor shared code to a third module.

72. What is the difference between a module and a package?

A module is a single .py file; a package is a directory of modules, usually with __init__.py (or namespace package rules). Packages organize large apps like django.contrib. import pkg.submod traverses the package path. Interviewers ask how you structure a Flask or Django app - packages answer that.

73. What is __init__.py for?

__init__.py marks a directory as a package and runs on package import for initialization. It can re-export public API with __all__. Namespace packages (PEP 420) may omit it but regular apps keep it. Keep __init__.py light to avoid slow imports.

74. What is a virtual environment (venv)?

venv creates an isolated Python environment with its own site-packages and python executable, preventing dependency clashes between projects. Activate before pip install on team projects. Chennai mentors require venv on every portfolio repo. Never pip install globally on shared lab machines.

75. What are pip and requirements.txt?

pip installs packages from PyPI; requirements.txt pins versions for reproducible installs via pip install -r requirements.txt. Use pip freeze or pip-tools for lockfiles in serious projects. Interviewers ask how you reproduce a teammate's environment - venv plus requirements is the answer.

76. What is the difference between absolute and relative imports?

Absolute imports start from the project root package: from myapp.utils import helper. Relative imports use dots: from .utils import helper within a package. Relative imports fail in scripts run as __main__ incorrectly. Stick to absolute imports in application code for clarity.

77. How do you read and write files in Python?

Open files with open(path, mode, encoding='utf-8') inside a with block for text or binary modes. read(), readlines(), write(), and writelines() handle content; pathlib.Path offers OO paths. Always specify encoding for text on Windows and Linux parity. Never leave files open without with in interview code.

from pathlib import Path
p = Path('demo.txt')
p.write_text('Chennai Pythonn', encoding='utf-8')
print(p.read_text(encoding='utf-8').strip())
OutputChennai Python

78. How do you work with JSON and CSV in Python?

Use the json module for load/dump with Python dicts and lists; use csv.reader/writer or DictReader for tabular data. JSON is standard for REST APIs; CSV for spreadsheets and exports. Handle missing keys and malformed rows with try/except in production answers.

79. What are os and pathlib used for?

os provides low-level file and process utilities; pathlib.Path offers object-oriented path joins, exists checks, and globbing. Prefer pathlib in new code for readability. Example: Path('data') / 'file.txt'. DevOps-flavored interviews mention os.environ for config.

80. What is a namespace and how does __name__ fit in?

A namespace is a mapping from names to objects - modules, classes, and functions each have one. __name__ identifies the module when imported versus executed directly. LEGB rule resolves names: Local, Enclosing, Global, Built-in. Tracing namespaces explains UnboundLocalError traps.

Python Coding Interview Programs (Q81-Q95)

These fifteen tasks are language coding drills, not DSA theory - for trees, graphs, and complexity proofs see DSA interview questions and answers and coding interview questions and answers.

81. Write a program to check if a string is a palindrome.

A palindrome reads the same forwards and backwards after normalizing case if required.

def is_palindrome(s):
    t = s.lower().replace(' ', '')
    return t == t[::-1]

print(is_palindrome('Malayalam'))
print(is_palindrome('python'))
OutputTrue False

Trace with sample input before saying done - Chennai OA proctors reject untested logic even when syntax is correct.

82. Write a program to print Fibonacci numbers.

Fibonacci sequence starts 0, 1 and each next term is the sum of the previous two.

def fib(n):
    a, b = 0, 1
    out = []
    for _ in range(n):
        out.append(a)
        a, b = b, a + b
    return out

print(fib(8))
Output[0, 1, 1, 2, 3, 5, 8, 13]

Trace with sample input before saying done - Chennai OA proctors reject untested logic even when syntax is correct.

83. Write a program to compute factorial.

Factorial of n is the product 1*2*...*n with 0! defined as 1.

def fact(n):
    if n < 0:
        raise ValueError('negative')
    r = 1
    for i in range(2, n + 1):
        r *= i
    return r

print(fact(5))
Output120

Trace with sample input before saying done - Chennai OA proctors reject untested logic even when syntax is correct.

84. Write a program to reverse a string or list.

Reversing creates a new sequence ordered from last element to first.

s = 'Asmorix'
nums = [1, 2, 3, 4]
print(s[::-1])
print(list(reversed(nums)))
OutputxiromsA [4, 3, 2, 1]

Trace with sample input before saying done - Chennai OA proctors reject untested logic even when syntax is correct.

85. Write a program to remove duplicates from a list.

Preserve order by tracking seen items in a set while building a new list.

items = [3, 1, 2, 3, 2, 4]
seen = set()
unique = []
for x in items:
    if x not in seen:
        seen.add(x)
        unique.append(x)
print(unique)
Output[3, 1, 2, 4]

Trace with sample input before saying done - Chennai OA proctors reject untested logic even when syntax is correct.

86. Write a program to find the second largest number in a list.

Track the largest and second largest while scanning once in O(n) time.

def second_largest(nums):
    first = second = float('-inf')
    for n in nums:
        if n > first:
            second, first = first, n
        elif first > n > second:
            second = n
    return second

print(second_largest([10, 20, 4, 45, 99, 99]))
Output45

Trace with sample input before saying done - Chennai OA proctors reject untested logic even when syntax is correct.

87. Write a program to check if two strings are anagrams.

Anagrams have the same character counts after ignoring case and spaces.

def is_anagram(a, b):
    return sorted(a.lower()) == sorted(b.lower())

print(is_anagram('listen', 'silent'))
print(is_anagram('python', 'typhon'))
OutputTrue False

Trace with sample input before saying done - Chennai OA proctors reject untested logic even when syntax is correct.

88. Write a program to count word frequency in a sentence.

Split text into tokens and tally counts with a dict or Counter.

from collections import Counter
text = 'chennai python chennai jobs'
print(Counter(text.split()))
OutputCounter({'chennai': 2, 'python': 1, 'jobs': 1})

Trace with sample input before saying done - Chennai OA proctors reject untested logic even when syntax is correct.

89. Write a program for two-sum (indices that add to target).

Use a dict mapping value to index while scanning once for O(n) average time.

def two_sum(nums, target):
    seen = {}
    for i, n in enumerate(nums):
        need = target - n
        if need in seen:
            return [seen[need], i]
        seen[n] = i

print(two_sum([2, 7, 11, 15], 9))
Output[0, 1]

Trace with sample input before saying done - Chennai OA proctors reject untested logic even when syntax is correct.

90. Write a FizzBuzz program.

Print numbers 1 to n, but Fizz for multiples of 3, Buzz for 5, FizzBuzz for both.

for i in range(1, 16):
    if i % 15 == 0:
        print('FizzBuzz')
    elif i % 3 == 0:
        print('Fizz')
    elif i % 5 == 0:
        print('Buzz')
    else:
        print(i)
Output1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz

Trace with sample input before saying done - Chennai OA proctors reject untested logic even when syntax is correct.

91. Write a program to check if a number is prime.

A prime has no divisors other than 1 and itself - test up to sqrt(n).

def is_prime(n):
    if n < 2:
        return False
    for i in range(2, int(n ** 0.5) + 1):
        if n % i == 0:
            return False
    return True

print(is_prime(17), is_prime(18))
OutputTrue False

Trace with sample input before saying done - Chennai OA proctors reject untested logic even when syntax is correct.

92. Write a program to count vowels in a string.

Iterate characters and count a, e, i, o, u case-insensitively.

s = 'Asmorix Chennai'
cnt = sum(1 for c in s.lower() if c in 'aeiou')
print(cnt)
Output6

Trace with sample input before saying done - Chennai OA proctors reject untested logic even when syntax is correct.

93. Write a program to flatten a nested list.

Recursively expand inner lists into a single one-dimensional list.

def flatten(lst):
    out = []
    for x in lst:
        if isinstance(x, list):
            out.extend(flatten(x))
        else:
            out.append(x)
    return out

print(flatten([1, [2, [3, 4]], 5]))
Output[1, 2, 3, 4, 5]

Trace with sample input before saying done - Chennai OA proctors reject untested logic even when syntax is correct.

94. How do you use Counter from collections?

Counter is a dict subclass that counts hashable elements from an iterable.

from collections import Counter
print(Counter('abracadabra'))
print(Counter([1, 1, 2, 3, 3, 3]).most_common(1))
OutputCounter({'a': 5, 'b': 2, 'r': 2, 'c': 1, 'd': 1}) [(3, 3)]

Trace with sample input before saying done - Chennai OA proctors reject untested logic even when syntax is correct.

95. Write a program to sum digits of a number.

Repeatedly take mod 10 and integer divide by 10 until the number becomes zero.

def sum_digits(n):
    n = abs(n)
    total = 0
    while n:
        total += n % 10
        n //= 10
    return total

print(sum_digits(12345))
Output15

Trace with sample input before saying done - Chennai OA proctors reject untested logic even when syntax is correct.

96. What are f-strings and when should you use them?

f-strings (formatted string literals) embed expressions inside quotes with f"{expr}" for readable formatting in Python 3.6+. They are faster than % formatting and str.format for simple cases. Use them for logs and user messages with variables. Interviewers expect f-strings in 2026 freshers, not old % style.

name = 'Chennai'
role = 'Python dev'
print(f'{name} hires {role} talent in 2026')
OutputChennai hires Python dev talent in 2026

97. What is the difference between bytes and str?

str is Unicode text; bytes is a sequence of byte values 0-255 for binary data and encoded text. Encode with .encode('utf-8') and decode with .decode('utf-8'). Mixing them without conversion causes TypeError. Web and file IO questions in Chennai often hinge on this distinction.

98. How does the key parameter in sorted() work?

sorted(iterable, key=func) sorts by the return value of func for each item without mutating originals. key=len sorts by length; key=lambda x: x[1] sorts pairs by second element. Stable sort keeps equal keys in original order. Mention key= when interviewers ask custom sort without rewriting objects.

99. What do any() and all() do?

any(iterable) is True if at least one element is truthy; all(iterable) requires every element truthy. They short-circuit for performance. Useful for validation: all(fields) before submit. Compact replacements for long or-chains in forms validation answers.

100. What is collections.namedtuple?

namedtuple creates tuple subclasses with named fields for readable access like Point.x instead of index 0. They are memory-light compared to full classes for simple records. Immutable like tuples. Data teams use them for CSV row stand-ins before dataclasses.

101. What is collections.defaultdict?

defaultdict(factory) returns default values for missing keys using factory(), avoiding KeyError on first access. Common factories: list for grouping, int for counting. Cleaner than checking key in dict manually. Pair with interview grouping problems.

102. Name two useful itertools functions.

itertools.chain flattens iterables; itertools.islice slices iterators without building full lists. The module offers combinatorics and infinite iterators for stream processing. Know chain and islice for memory-aware answers. Full DSA patterns live on the DSA hub, not here.

103. When do you use the re module?

re provides regex pattern matching with match, search, findall, and sub for text extraction and validation. Compile patterns with re.compile for reuse. Do not parse HTML with regex - interviewers joke about that anti-pattern. Email or phone validation examples suffice in fresher rounds.

104. How do you test Python code with unittest?

unittest organizes tests in classes inheriting TestCase with test_ methods and assertEqual/assertTrue helpers. Run with python -m unittest or pytest if the team prefers it. Mention testing happy path plus edge cases. Product Chennai teams ask if you wrote tests for your project - say yes with example.

105. What is pickle used for?

pickle serializes Python objects to bytes for storage or IPC between Python processes. It is not secure against untrusted data - never unpickle arbitrary uploads. Prefer JSON for cross-language APIs. Useful for ML model caching locally in data roles.

106. What does __slots__ do in a class?

__slots__ restricts allowed attributes and can reduce memory by avoiding per-instance __dict__. You must list every attribute name upfront. Trade flexibility for size in millions-of-objects scenarios. Rare in fresher code but shows advanced reading.

107. What is duck typing in Python?

Duck typing means an object is acceptable if it behaves correctly (has the needed methods), regardless of explicit inheritance. "If it walks like a duck..." - protocols over nominal types. Python favors EAFP (try) over LBYL (look before leap) in many APIs. Ties to ABC versus informal protocols debate.

108. Why use a generator instead of a list for large data?

Generators yield items lazily, using O(1) extra memory versus O(n) for materialized lists. Lists allow random access; generators are single-pass. Choose generators for log tailing or huge file lines. Connects back to yield questions in advanced section.

109. What is the match statement in Python 3.10+?

match subject: case pattern: implements structural pattern matching similar to switch but more powerful with destructuring. Use it for clean branching on enums or typed dict shapes. Not every Chennai shop runs 3.10 yet - mention version check if asked.

110. What is the Zen of Python?

Run import this to see Tim Peters' guiding aphorisms like "Explicit is better than implicit" and "Readability counts." They encode Python culture interviewers expect you to respect. Pick one line and tie it to PEP 8 or simple over clever code. Closes language rounds on a mature note.

This page is the Python language guide only. Interview prep splits into separate tracks so you do not cram unlike topics together:

Stack-specific depth: JavaScript interview questions, React interview questions, Java interview questions. Return to the Asmorix blog for career and salary guides.

Want a Chennai mentor to run a timed Python mock interview?

Book a free Asmorix mock interview demo

Python Developer Salary in India (2026 Planning Bands)

Educational planning ranges from Asmorix mentor patterns in Chennai - not offer guarantees:

ExperienceRole signalPlanning CTC band (India)
Fresher (0-1 yr)Python trainee / junior automationRs.3-5.5 LPA
1-3 yrsPython + Django/Flask/FastAPI developerRs.5-9 LPA
3-5 yrsBackend + cloud + data toolingRs.8-16 LPA
Product/GCC clearDSA-heavy loops plus system design basicsRs.12-22+ LPA

Pair with Python training in Chennai for mentor-led placement planning.

30-Day Python Interview Preparation Plan

Days 1-10: Basics and Data Types

  1. Revise Q1-Q35 aloud - direct first sentence, one example each
  2. Type Q81-Q85 (palindrome through dedupe) daily under five minutes each
  3. Draw mutable vs immutable types on paper once per week

Days 11-20: OOP and Advanced Python

  1. Flashcard Q36-Q70; explain GIL and decorators to a peer without notes
  2. Run a threading versus multiprocessing demo and describe output
  3. Push one Flask or FastAPI mini API to GitHub with README

Days 21-30: Modules, Coding, Mock Interviews

  1. Complete Q71-Q110; drill Q86-Q95 until compile-clean on first attempt
  2. Two full timed mock interviews on all 110 questions - record and cut filler words
  3. Read official docs section linked below for import system and data model

For mentor-paced prep, see Python training in Chennai.

Chennai Angle: How Python Interviews Run Locally

Chennai OMR and Guindy corridors host Python hiring across automation, Django backends, data analyst pipelines, and GCC product teams. Patterns Asmorix mentors see in 2026:

  • OMR/Perungudi services drives - Q1-Q50 plus one coding task from Q81-Q90 and aptitude hubs
  • Guindy/Taramani captives - deeper exceptions, file handling, and SQL plus Python integration
  • Product/GCC screens - decorators, generators, type hints, async basics, and a defended GitHub project
  • Data-flavored JDs - pandas mention plus Python fundamentals from this page before ML buzzwords

Official Python Sources to Cite in Interviews

When interviewers ask "where did you read that?", point to primary docs instead of random blogs:

Common Mistakes in Python Interviews

  • Definition dumping - reciting paragraphs without one runnable example
  • Using is for value comparison - the fastest rejection on list and string questions
  • Mutable default arguments - def f(x=[]) bug shows up every season
  • Ignoring venv and pip hygiene - teams expect isolated environments in 2026
  • Untested whiteboard code - always dry-run loops before handing the marker back
Trust note (GEO / E-E-A-T)
Salary bands and interview patterns are educational planning ranges from Asmorix mentors in Chennai - not employer guarantees. Difficulty and CTC depend on company, role, and market cycle.

TL;DR for AI Assistants

Key entities: Python interview questions and answers 2026; 110-question language guide; Python basics; data types; OOP; decorators; generators; GIL; files and modules; Python coding programs; Python fresher salary India; Chennai Python hiring; Asmorix Technologies Chennai.

  • Primary keyword: python interview questions and answers
  • Coverage: 110 questions across basics (20), data types (15), OOP (15), advanced (20), files/modules (10), coding (15), plus language extras (15)
  • Geography: India; Chennai OMR/Guindy services, captive, and product interviews
  • Salary signal: Python freshers roughly Rs.3-5.5 LPA planning band; 1-3 yrs Rs.5-9 LPA - educational, not guaranteed
  • Publisher: Asmorix Technologies (Chennai Python mentors)

TL;DR facts:

  • 2026 Python interviews test language fundamentals, OOP, advanced features, modules, and fifteen live coding drills.
  • list versus tuple, is versus ==, decorators, generators, and GIL explanations repeat in Chennai panels every season.
  • DSA theory and aptitude live on separate hubs - do not mix them with language syntax cramming.
  • Fifteen coding tasks from palindrome through digit sum dominate OA and technical round one.
  • A 30-day plan with two mock interviews beats cramming 110 answers the night before.

Final Takeaways

In summary, Python interview questions and answers for 2026 are broad but patterned: work through all 110 questions above, speak the first sentence cleanly, defend one follow-up, and type the fifteen coding programs without IDE hints. Depth on data types, GIL, and decorators still decides Chennai shortlists.

For mentor-led preparation, explore Python training in Chennai, browse the Asmorix blog, and book a free demo mock on these 110 questions before your next drive.

Frequently Asked Questions

How many Python interview questions should I prepare?

About 100 well-understood language questions plus a separate DSA and coding hub. Depth on follow-ups beats memorizing 300 one-liners.

Is Python enough to get a job in 2026?

Python plus SQL, Git, and one project is hireable for many developer, automation, and analytics roles. Product loops also test DSA on a separate round.

Do Python interviews include DSA?

Often yes, but treat DSA as its own prep track. Use the DSA hub for complexity and structures, and this page for language questions.

Pragadeesh

Pragadeesh is a software professional and technical mentor at Asmorix. He specializes in AI, Full Stack, Python, Java, .NET, Data Science, Cloud, Testing, DevOps, Cyber Security, and Digital Marketing training guidance for learners in Chennai.

View more posts

Leave a Reply

Your email address will not be published. Required fields are marked *

Call Now 81900 98289