100 Python Interview Questions with Answers for Freshers & Experienced Developers

100 Python Interview Questions with Answers (2026) | Freshers & Experienced | InfoGrain STCS
Updated for 2026 · Freshers & Experienced

100 Python Interview Questions with Answers

A categorized, searchable set of Python interview questions and answers — covering basics, data types, OOP, data structures, exceptions, and advanced topics — built for Python interview preparation whether you're a fresher or an experienced developer.

100Questions
10Categories
58/32/10Beginner / Inter / Advanced

How to use this Python interview question bank

This guide brings together 100 Python interview questions and answers, organized into 10 categories so you can study in order — from basics to advanced — or jump straight to the topic you're weakest on. Each answer is written to be spoken out loud in an actual interview: short, precise, and code-referenced.

Every question is tagged Beginner, Intermediate, or Advanced, so this single list works as Python interview questions for freshers, Python interview questions for experienced developers, and general Python interview preparation.

Use the search box and category chips below to filter instantly — it works like a lightweight Python viva questions and answers flashcard deck.

Python Basics (10 questions)

Q01What is Python and why is it used?Beginner

Python is a high-level, interpreted, general-purpose programming language known for readable syntax and a large ecosystem. It's used for web development, data analysis, automation, and AI/ML because it lets developers build and iterate quickly.

Q02What are the key features of Python?Beginner

Easy-to-read syntax, dynamic typing, interpreted execution, an extensive standard library, cross-platform support, and a strong community-driven package ecosystem (PyPI).

Q03Is Python interpreted or compiled?Beginner

Python source is first compiled to bytecode (.pyc) and then executed by the Python Virtual Machine (PVM) — so it's technically both, though it's commonly described as an interpreted language.

Q04What is PEP 8?Beginner

PEP 8 is Python's official style guide covering naming conventions, indentation, and formatting to keep code consistent and readable across projects.

Q05What's the difference between Python 2 and Python 3?Beginner

Python 3 uses print() as a function, true division by default, and unicode strings by default, and is the actively maintained version; Python 2 reached end-of-life in 2020.

Q06What is the Python Standard Library?Beginner

A collection of built-in modules (like os, sys, math, json) that ship with Python and provide ready-made functionality without needing external installation.

Q07How is memory managed in Python?Intermediate

Python uses automatic memory management via reference counting plus a cyclic garbage collector to reclaim memory from objects with circular references.

Q08What is the PEP process in Python?Beginner

PEPs (Python Enhancement Proposals) are design documents proposing new features or conventions for Python; PEP 8 (style) and PEP 20 (Zen of Python) are among the most referenced.

Q09What is the Zen of Python?Beginner

A set of guiding principles for writing Python code, viewable via import this, emphasizing readability and simplicity — e.g. "Simple is better than complex."

Q10What are Python's common use cases in industry?Beginner

Web development (Django/Flask), data analysis (pandas), machine learning (TensorFlow/PyTorch), automation and scripting, and backend APIs.

Data Types & Variables (10 questions)

Q11What are Python's built-in data types?Beginner

int, float, complex, str, bool, list, tuple, dict, set, frozenset, and NoneType.

Q12What is the difference between mutable and immutable objects?Beginner

Mutable objects (list, dict, set) can be changed after creation; immutable objects (int, str, tuple) cannot — any "change" actually creates a new object.

Q13How do you check the data type of a variable?Beginner

Using the built-in type() function, e.g. type(x).

Q14What is type casting/conversion in Python?Beginner

Explicitly converting one data type to another using functions like int(), str(), float() — e.g. int("5") converts a string to an integer.

Q15What is the difference between == and is?Intermediate

== compares values for equality; is compares object identity — whether two references point to the same object in memory.

Q16What is None in Python?Beginner

A special singleton value representing the absence of a value, similar to null in other languages.

Q17Do Python variables need explicit type declaration?Beginner

No. Variables are names bound to objects in memory, and Python is dynamically typed, so you don't declare a variable's type explicitly.

Q18What is variable scope in Python?Intermediate

The region of code where a variable is accessible, governed by the LEGB rule: Local, Enclosing, Global, Built-in.

Q19What's the difference between local and global variables?Beginner

Local variables exist within a function's scope; global variables are defined at module level and accessible throughout, unless a function explicitly declares global.

Q20What is dynamic typing in Python?Beginner

A variable's type is determined at runtime based on the value assigned, and the same variable name can later be rebound to a value of a different type.

Operators & Control Flow (10 questions)

Q21What are Python's comparison operators?Beginner

== != > < >= <= — used to compare two values and return a boolean.

Q22What is the difference between / and //?Beginner

/ performs true (float) division; // performs floor division, returning the largest integer less than or equal to the result.

Q23How does the if-elif-else statement work?Beginner

It evaluates conditions top to bottom and executes the block under the first True condition, falling back to else if none match.

Q24What is the difference between for and while loops?Beginner

for iterates over a sequence or iterable for a known/finite range; while repeats as long as a condition stays True, useful when the number of iterations isn't known upfront.

Q25What do break, continue, and pass do?Beginner

break exits a loop entirely; continue skips to the next iteration; pass is a no-op placeholder used where syntax requires a statement.

Q26What is a ternary (conditional) expression in Python?Intermediate

A one-line conditional: value_if_true if condition else value_if_false.

Q27What is short-circuit evaluation in Python?Intermediate

In and/or expressions, Python stops evaluating as soon as the result is determined, returning the deciding value rather than a plain boolean.

Q28What are Python's logical operators?Beginner

and, or, not — used to combine or invert boolean expressions.

Q29What is the walrus operator (:=)?Intermediate

Introduced in Python 3.8, it lets you assign a value to a variable as part of an expression, e.g. if (n := len(data)) > 10:.

Q30What is the difference between range() in Python 2 and Python 3?Intermediate

Python 3's range() returns a lazy iterable (matching Python 2's xrange); Python 2's range() built a full list in memory upfront.

Functions (10 questions)

Q31How do you define a function in Python?Beginner

Using the def keyword followed by a name, parentheses for parameters, and a colon — e.g. def greet(name):.

Q32What is the difference between arguments and parameters?Beginner

Parameters are the names listed in a function's definition; arguments are the actual values passed when calling the function.

Q33What are default arguments in Python?Beginner

Parameters that take a preset value if no argument is provided at call time, defined as def f(x=10):.

Q34What are *args and **kwargs?Intermediate

*args collects extra positional arguments into a tuple; **kwargs collects extra keyword arguments into a dictionary, letting functions accept a variable number of inputs.

Q35What is a lambda function?Beginner

An anonymous, single-expression function defined with the lambda keyword, e.g. lambda x: x * 2, often used for short throwaway operations.

Q36What is the difference between a function and a method?Beginner

A function is a standalone block of reusable code; a method is a function defined inside and bound to a class or object.

Q37What is recursion?Intermediate

A function calling itself to solve a smaller instance of the same problem, typically requiring a base case to avoid infinite recursion.

Q38What does the return statement do?Beginner

It exits a function and optionally sends a value back to the caller; a function without an explicit return returns None.

Q39What are Python decorators?Advanced

Functions that wrap another function to extend or modify its behavior without changing its source code, applied using the @decorator syntax.

Q40What is the difference between pass-by-value and pass-by-reference in Python?Intermediate

Python uses "pass by object reference": immutable objects behave like pass-by-value since they can't be modified in place, while mutable objects can be modified in place, resembling pass-by-reference.

Object-Oriented Programming (10 questions)

Q41What is a class in Python?Beginner

A blueprint for creating objects, defining attributes and methods shared by all instances created from it.

Q42What is the difference between a class and an object?Beginner

A class is the definition/template; an object is a specific instance created from that class with its own state.

Q43What is __init__ used for?Beginner

It's the constructor method automatically called when a new object is created, typically used to initialize instance attributes.

Q44What is self in Python classes?Beginner

A reference to the current instance, used to access its attributes and methods; it's the first parameter of instance methods by convention.

Q45What is inheritance in Python?Intermediate

A mechanism where a child class derives attributes and methods from a parent class, enabling code reuse, defined as class Child(Parent):.

Q46What is method overriding?Intermediate

When a child class provides its own implementation of a method already defined in its parent class.

Q47What is polymorphism in Python?Intermediate

The ability for different classes to implement the same method name in different ways, so the same call behaves differently depending on the object's type.

Q48What is encapsulation, and how is it implemented in Python?Intermediate

Bundling data and methods within a class and restricting direct access to some of them — implemented in Python via naming conventions (_protected, __private) rather than strict access modifiers.

Q49What's the difference between instance, class, and static methods?Advanced

Instance methods take self and operate on an instance; class methods take cls and operate on the class (@classmethod); static methods take neither, behaving like a plain function grouped inside the class (@staticmethod).

Q50What is multiple inheritance, and how does Python resolve conflicts?Advanced

When a class inherits from more than one parent class; Python resolves method lookup order using the C3 linearization algorithm, visible via the class's __mro__.

Data Structures (10 questions)

Q51What is the difference between a list and a tuple?Beginner

Lists are mutable and defined with []; tuples are immutable and defined with (). Tuples are generally faster and used for fixed collections.

Q52What is a dictionary in Python?Beginner

An insertion-ordered collection of key-value pairs, defined with {}, offering fast lookup by key.

Q53What is a set, and how does it differ from a list?Beginner

A set is an unordered collection of unique elements; unlike a list, it automatically removes duplicates and doesn't support indexing.

Q54How do you remove duplicates from a list?Intermediate

A common approach is list(set(my_list)), though it doesn't preserve order; use list(dict.fromkeys(my_list)) to preserve order.

Q55What is list comprehension?Intermediate

A concise syntax for creating a list from an iterable in one line, e.g. [x*2 for x in range(5)].

Q56What is dictionary comprehension?Intermediate

Similar to list comprehension but for dictionaries, e.g. {x: x*2 for x in range(5)}.

Q57What is the difference between append() and extend() for lists?Beginner

append() adds a single element (even if it's a list) as one item; extend() adds each element of an iterable individually to the list.

Q58How do you sort a list in Python?Beginner

Using .sort() to sort in place, or sorted() to return a new sorted list; both accept a key parameter for custom sort logic.

Q59What is a frozenset?Intermediate

An immutable version of a set — once created, its elements can't be changed, added, or removed.

Q60What is slicing in Python?Beginner

Extracting a portion of a sequence (list, string, tuple) using the syntax sequence[start:stop:step].

String Handling (10 questions)

Q61Are strings mutable in Python?Beginner

No. Strings are sequences of characters and are immutable — any operation that "changes" a string actually creates a new string object.

Q62What methods support string formatting in Python?Beginner

f-strings (f"{name}"), the .format() method, and the older % operator.

Q63What is the difference between split() and join()?Beginner

split() breaks a string into a list based on a delimiter; join() combines a list of strings into one string using a specified separator.

Q64How do you reverse a string in Python?Beginner

Using slicing: my_string[::-1].

Q65What is the difference between strip(), lstrip(), and rstrip()?Beginner

strip() removes leading and trailing whitespace (or specified characters); lstrip() removes only from the left; rstrip() removes only from the right.

Q66How do you check if a string contains a substring?Beginner

Using the in keyword, e.g. "sub" in my_string, or the .find()/.index() methods.

Q67What is string interpolation with f-strings?Beginner

A Python 3.6+ feature letting you embed expressions directly inside string literals, e.g. f"Hello {name}".

Q68What is the difference between str() and repr()?Intermediate

str() returns a human-readable representation of an object; repr() returns an unambiguous representation useful for debugging, often valid Python code to recreate the object.

Q69How do you check if a string is a palindrome?Intermediate

Compare the string to its reverse: s == s[::-1].

Q70How do you count occurrences of a character or substring in a string?Beginner

Using the .count() method, e.g. my_string.count("a").

Exception Handling (10 questions)

Q71What is exception handling in Python?Beginner

A mechanism to gracefully handle runtime errors using try, except, else, and finally blocks instead of letting the program crash.

Q72What is the difference between try-except and try-finally?Beginner

except runs only if an exception occurs, to handle it; finally runs regardless of whether an exception occurred, typically for cleanup.

Q73How do you raise a custom exception in Python?Intermediate

Define a class inheriting from Exception, then use raise MyException("message") to trigger it.

Q74What is the difference between Exception and BaseException?Intermediate

BaseException is the root of all exceptions, including system-exiting ones like SystemExit; Exception is the base class for most user-handled errors and doesn't include those.

Q75What are some common built-in exceptions in Python?Beginner

ValueError, TypeError, IndexError, KeyError, ZeroDivisionError, and FileNotFoundError are among the most frequently encountered.

Q76What is the purpose of the else clause in a try block?Intermediate

Code in else runs only if the try block completes without raising an exception, useful for separating "risky" code from code that depends on its success.

Q77How do you catch multiple exceptions in one block?Beginner

By passing a tuple to except, e.g. except (ValueError, TypeError):.

Q78What happens if an exception isn't caught?Beginner

Python prints a traceback and terminates the program (or the current thread) unless the exception is caught somewhere up the call stack.

Q79What is the difference between assert and raise?Intermediate

assert checks a condition and raises AssertionError if it's False, mainly for debugging; raise explicitly triggers a specified exception.

Q80What is exception chaining in Python?Advanced

Using raise NewException("msg") from original_exception to preserve and show the original exception's context alongside the new one.

File Handling & Modules (10 questions)

Q81How do you open and read a file in Python?Beginner

Using open("file.txt", "r") combined with .read(), .readline(), or .readlines(), ideally within a with block for automatic closing.

Q82Why use the with statement when handling files?Beginner

It ensures the file is properly closed automatically once the block finishes, even if an exception occurs, without needing an explicit close() call.

Q83What is the difference between "r", "w", "a", and "rb" file modes?Beginner

"r" reads an existing file, "w" overwrites/creates a file, "a" appends to a file, and "rb" reads a file in binary mode.

Q84What is a Python module?Beginner

A single .py file containing reusable functions, classes, or variables that can be imported into other scripts.

Q85What is the difference between a module and a package?Intermediate

A module is a single file; a package is a directory of modules containing an __init__.py file, allowing hierarchical organization.

Q86How do you import a specific function from a module?Beginner

Using from module_name import function_name, rather than importing the entire module.

Q87What is the __name__ == "__main__" idiom used for?Intermediate

It lets a script detect whether it's being run directly or imported as a module, so code inside that block only executes when run directly.

Q88What is pip, and what is it used for?Beginner

Python's package installer, used to install and manage third-party libraries from the Python Package Index (PyPI).

Q89What is a virtual environment, and why is it used?Intermediate

An isolated Python environment with its own dependencies, used to avoid version conflicts between different projects on the same machine.

Q90How do you handle JSON data in Python?Intermediate

Using the built-in json module — json.load()/json.loads() to parse JSON into Python objects, and json.dump()/json.dumps() to convert Python objects into JSON.

Advanced Python (10 questions)

Q91What is a generator in Python?Intermediate

A function that uses yield instead of return to produce a sequence of values lazily, one at a time, without storing the entire sequence in memory.

Q92What's the difference between a generator and a normal function?Intermediate

A normal function returns once and exits; a generator function pauses at each yield and resumes from that point on the next call, maintaining state between calls.

Q93What is the Global Interpreter Lock (GIL)?Advanced

A mutex in CPython that allows only one thread to execute Python bytecode at a time, which limits true parallelism for CPU-bound multithreaded code.

Q94What's the difference between multithreading and multiprocessing in Python?Advanced

Multithreading runs multiple threads within one process (limited by the GIL for CPU-bound tasks, useful for I/O-bound tasks); multiprocessing runs separate processes with their own memory and interpreter, achieving true parallelism for CPU-bound tasks.

Q95What are iterators, and how do they differ from iterables?Intermediate

An iterable is any object you can loop over (implements __iter__); an iterator is the object that actually produces values one at a time (implements __next__ and maintains state).

Q96What is a context manager in Python?Intermediate

An object implementing __enter__ and __exit__ methods, used with the with statement to manage setup and teardown (like opening/closing files) automatically.

Q97What is the difference between deep copy and shallow copy?Advanced

A shallow copy (copy.copy()) copies the outer object but shares references to nested objects; a deep copy (copy.deepcopy()) recursively copies nested objects too, so changes to one don't affect the other.

Q98What are magic/dunder methods in Python?Advanced

Special methods surrounded by double underscores (like __init__, __str__, __len__) that let custom classes integrate with Python's built-in syntax and functions.

Q99What is monkey patching in Python?Advanced

Dynamically modifying or extending a class or module at runtime, typically used for testing or quick fixes, though it can make code harder to maintain if overused.

Q100What is the relationship between == and __eq__?Advanced

== calls the object's __eq__ method under the hood; overriding __eq__ in a custom class lets you define what "equality" means for instances of that class.

No questions match your search - try a different keyword or clear the filters.

Quick answers (Python interview FAQs)

Short, direct answers to the questions people ask search engines and voice assistants most often about Python interview preparation.

What are the most common Python interview questions?

Most interviews open with Python basics (features, PEP 8, Python 2 vs 3), then move into data types, mutability, functions, OOP concepts like inheritance and polymorphism, and finish with data structures and exception handling. The 100 questions on this page are grouped in that same order.

What Python questions are asked in interviews for freshers?

Freshers are usually tested on fundamentals: variables and data types, loops and conditionals, functions and default arguments, basic OOP (classes, self, __init__), and simple string or list operations rather than internals like the GIL or decorators.

What are the basic Python interview questions?

Basic questions cover what Python is, its key features, mutable vs immutable types, list vs tuple, how loops and functions work, and simple string methods — all included in the Beginner-tagged questions below.

How do I prepare for a Python interview?

Work category by category: fundamentals first, then data structures, OOP, and exception handling, before moving to advanced topics like generators, the GIL, and decorators. Practice explaining each answer out loud in one or two sentences, then write small code snippets to back it up.

What coding questions are asked in Python interviews?

Expect small coding tasks alongside concept questions: reversing a string, removing duplicates from a list, checking a palindrome, writing a list/dictionary comprehension, or implementing a simple generator or custom exception.

What is Python and why is it used?

Python is a high-level, interpreted, general-purpose language used for web development, data analysis, automation, and AI/ML because of its readable syntax and large ecosystem of libraries.

What are the most important Python concepts for interviews?

Mutability, scope, functions and *args/**kwargs, OOP fundamentals (inheritance, polymorphism, encapsulation), list/dictionary comprehensions, exception handling, and — for experienced roles — generators, decorators, and the GIL.

Is Python easy to learn for beginners?

Yes. Python's syntax reads close to plain English, it doesn't require explicit type declarations, and it has extensive documentation and community resources, which is why it's a common first language.

What Python skills are required for a developer job?

Solid grasp of core syntax and data structures, OOP design, file and exception handling, familiarity with the standard library and pip, and comfort with at least one framework or domain library relevant to the role (Django/Flask, pandas, etc.).

What should I study before a Python interview?

Review this question set category by category, re-implement a few answers as actual code, and skim the official Python documentation for any topic (like decorators or the GIL) that still feels fuzzy.

Ready for the next round?

Pair this question bank with our SQL and DSA interview guides for full-stack interview coverage.

Explore the DSA roadmap →
>>> progress0%
0 / 100 opened · drag me

You may also like these