Python

100+ Python Interview Questions and Answers for Freshers (2026)

A practical, no-fluff collection of Python interview questions — basics, OOP, exception handling, file handling, decorators, generators, NumPy and Pandas — each with a working code example, output and a plain-English explanation.

Python code editor with functions and data structures on screen

This guide organizes the most frequently asked Python interview questions into 21 topic groups so you can revise in order or jump straight to a weak spot using the table of contents. Every question includes a short answer, a runnable example, its output, and a one-line explanation of why the output is what it is.

Tip: Don't just read the answers — open a terminal, retype every code example yourself, and try to predict the output before running it.

Python Basics

Q1. What is Python and why is it popular for interviews?

Easy

Answer: Python is a high-level, interpreted, dynamically-typed language known for readable syntax and a large standard library. It's popular in interviews because its concise syntax lets candidates focus on logic instead of boilerplate.

Python
print("Hello, Interview!")

Output

Hello, Interview!

Explanation: print() writes the string to standard output followed by a newline.

Q2. Is Python compiled or interpreted?

Easy

Answer: Python source code is first compiled to bytecode (.pyc), which the Python Virtual Machine then interprets line by line. So it's technically both compiled and interpreted, but from a developer's view it behaves like an interpreted language.

Note: This is different from Java, which compiles to bytecode but runs on a separate JVM process explicitly.

Q3. What is PEP 8?

Easy

Answer: PEP 8 is Python's official style guide — it covers naming conventions, indentation (4 spaces), line length, and import ordering, and most teams enforce it with linters like flake8 or ruff.

Variables

Q4. How does variable assignment work in Python?

Easy

Answer: A Python variable is a name bound to an object in memory — it doesn't hold the value directly like in C, it holds a reference to the object.

Python
a = [1, 2, 3]
b = a
b.append(4)
print(a)

Output

[1, 2, 3, 4]

Explanation: b references the same list object as a, so mutating b also changes a.

Q5. What's the difference between local and global variables?

Easy

Answer: A local variable is defined inside a function and only exists during that call; a global variable is defined at module level and accessible everywhere, unless shadowed inside a function scope.

Data Types

Q6. What are Python's built-in data types?

Easy

Answer: The core built-in types are int, float, complex, bool, str, list, tuple, dict, set, and NoneType.

TypeMutable?Example
listYes[1, 2, 3]
tupleNo(1, 2, 3)
dictYes{"a": 1}
setYes{1, 2, 3}

Q7. How do you check the type of a variable?

Easy
Python
x = 3.14
print(type(x))
print(isinstance(x, float))

Output

<class 'float'>
True

Operators

Q8. What's the difference between == and is?

Medium

Answer: == compares values for equality, while is compares object identity (whether both names point to the same object in memory).

Python
a = [1, 2]
b = [1, 2]
print(a == b)
print(a is b)

Output

True
False

Explanation: a and b hold equal values but are two distinct list objects.

Q9. What does the // operator do?

Easy

Answer: It performs floor division, returning the largest integer less than or equal to the result — 7 // 2 gives 3.

Loops

Q10. What's the difference between break, continue and pass?

Easy

Answer: break exits the loop entirely, continue skips to the next iteration, and pass does nothing — it's a syntactic placeholder.

Q11. What does the else clause on a for loop do?

Medium
Python
for i in range(3):
    print(i)
else:
    print("loop finished")

Output

0
1
2
loop finished

Explanation: The else block runs only if the loop completes without hitting a break.

Functions

Q12. What's the difference between *args and **kwargs?

Medium

Answer: *args collects extra positional arguments into a tuple, and **kwargs collects extra keyword arguments into a dictionary.

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

demo(1, 2, name="Ankit")

Output

(1, 2)
{'name': 'Ankit'}

Q13. Why is a mutable default argument dangerous?

Hard
Python
def add_item(item, bucket=[]):
    bucket.append(item)
    return bucket

print(add_item("a"))
print(add_item("b"))

Output

['a']
['a', 'b']

Explanation: The default list is created once at function definition time and reused across calls, so it silently accumulates state. Use bucket=None and create a new list inside the function instead.

Warning: This is one of the most common Python gotchas asked at the intermediate level — always mention the fix, not just the bug.

Strings

Q14. How do you reverse a string in Python?

Easy
Python
s = "ankit"
print(s[::-1])

Output

tikna

Q15. Are Python strings mutable?

Easy

Answer: No, strings are immutable — any operation that appears to modify a string actually creates and returns a new string object.

Lists

Q16. What's the time complexity of common list operations?

Medium
OperationComplexity
Index access lst[i]O(1)
Append lst.append(x)O(1) amortized
Insert at index lst.insert(0, x)O(n)
Search x in lstO(n)

Q17. How do you remove duplicates from a list while keeping order?

Medium
Python
nums = [3, 1, 3, 2, 1, 4]
unique = list(dict.fromkeys(nums))
print(unique)

Output

[3, 1, 2, 4]

Explanation: Dictionaries preserve insertion order in Python 3.7+, so dict.fromkeys() is a clean order-preserving dedupe trick.

Tuples

Q18. Why would you use a tuple instead of a list?

Easy

Answer: Tuples are immutable, so they're hashable (usable as dict keys or set members), slightly faster to iterate, and communicate intent — "this collection shouldn't change."

Q19. How do you unpack a tuple with extra elements?

Medium
Python
first, *middle, last = (1, 2, 3, 4, 5)
print(first, middle, last)

Output

1 [2, 3, 4] 5

Dictionary

Q20. How do you safely get a key that might not exist?

Easy
Python
config = {"debug": True}
print(config.get("timeout", 30))

Output

30

Explanation: .get() avoids a KeyError by returning a default value when the key is missing.

Q21. What is a dictionary comprehension?

Medium
Python
squares = {n: n**2 for n in range(5)}
print(squares)

Output

{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

Sets

Q22. How do you find common elements between two lists efficiently?

Medium
Python
a = [1, 2, 3, 4]
b = [3, 4, 5, 6]
print(set(a) & set(b))

Output

{3, 4}

Explanation: Converting to sets and using & (intersection) is O(min(len(a), len(b))) — much faster than a nested loop for large inputs.

OOP

Q23. What are the four pillars of OOP in Python?

Medium

Answer: Encapsulation (bundling data and methods), Abstraction (hiding implementation detail), Inheritance (reusing behaviour from a parent class), and Polymorphism (one interface, many implementations).

Q24. What's the difference between a class method, a static method and an instance method?

Medium
Python
class Demo:
    def instance_method(self):
        return "uses self"

    @classmethod
    def class_method(cls):
        return "uses cls"

    @staticmethod
    def static_method():
        return "uses neither"

Explanation: Instance methods access object state via self, class methods access class state via cls, and static methods are just namespaced functions with no automatic first argument.

Inheritance

Q25. How does super() work in single inheritance?

Medium
Python
class Animal:
    def __init__(self, name):
        self.name = name

class Dog(Animal):
    def __init__(self, name, breed):
        super().__init__(name)
        self.breed = breed

d = Dog("Bruno", "Labrador")
print(d.name, d.breed)

Output

Bruno Labrador

Q26. What is the Method Resolution Order (MRO)?

Hard

Answer: MRO is the order Python follows to look up a method across a chain of parent classes in multiple inheritance, computed using the C3 linearization algorithm and inspectable via ClassName.__mro__.

Polymorphism

Q27. What is duck typing?

Medium

Answer: "If it walks like a duck and quacks like a duck, it's a duck" — Python doesn't check an object's type before calling a method, only whether the method exists, which enables polymorphism without shared inheritance.

Python
class Cat:
    def speak(self): return "Meow"

class Duck:
    def speak(self): return "Quack"

for animal in [Cat(), Duck()]:
    print(animal.speak())

Output

Meow
Quack

Exception Handling

Q28. What's the difference between except Exception and a bare except:?

Medium

Answer: A bare except: catches everything, including KeyboardInterrupt and SystemExit, which can hide bugs and block clean shutdowns. except Exception catches normal errors only and is the safer default.

Q29. What does the finally block guarantee?

Easy
Python
try:
    1 / 0
except ZeroDivisionError:
    print("caught it")
finally:
    print("always runs")

Output

caught it
always runs

File Handling

Q30. Why should you use with open(...) instead of open() directly?

Easy
Python
with open("notes.txt", "w") as f:
    f.write("Interview prep")

Explanation: The with statement uses a context manager that automatically closes the file — even if an exception is raised inside the block — preventing file-handle leaks.

Modules

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

Medium

Answer: __name__ equals "__main__" only when the file is run directly, not when it's imported as a module — this guard lets you write both a reusable module and a runnable script in the same file.

Decorators

Q32. How do you write a simple timing decorator?

Hard
Python
import time
from functools import wraps

def timer(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        start = time.perf_counter()
        result = func(*args, **kwargs)
        print(f"{func.__name__} took {time.perf_counter()-start:.4f}s")
        return result
    return wrapper

@timer
def slow_add(a, b):
    return a + b

slow_add(2, 3)

Explanation: A decorator is a function that wraps another function to add behaviour without changing its source code; @wraps preserves the original function's name and docstring.

Generators

Q33. Why use a generator instead of returning a list?

Medium
Python
def even_numbers(limit):
    for n in range(limit):
        if n % 2 == 0:
            yield n

for num in even_numbers(6):
    print(num)

Output

0
2
4

Explanation: yield pauses the function and returns one value at a time, so the whole sequence is never held in memory at once — critical for very large or infinite sequences.

Iterators

Q34. What's the difference between an iterable and an iterator?

Medium

Answer: An iterable implements __iter__() and can produce an iterator (e.g. a list); an iterator implements both __iter__() and __next__() and tracks its own iteration state.

NumPy

Q35. Why are NumPy arrays faster than Python lists?

Medium

Answer: NumPy arrays store elements in contiguous memory with a single fixed type and push loops down into optimized C code (vectorization), avoiding the per-element overhead of Python's dynamic typing.

Python
import numpy as np
arr = np.array([1, 2, 3, 4])
print(arr * 2)

Output

[2 4 6 8]

Pandas

Q36. What's the difference between loc and iloc?

Medium

Answer: .loc[] selects rows and columns by label, while .iloc[] selects by integer position — mixing them up is one of the most common Pandas interview traps.

Python
import pandas as pd
df = pd.DataFrame({"name": ["A", "B"], "score": [90, 85]})
print(df.loc[0, "name"])
print(df.iloc[0, 1])

Output

A
90

Q37. How do you handle missing values in a DataFrame?

Medium

Answer: Use df.isnull().sum() to find them, then either drop rows/columns with df.dropna() or fill values with df.fillna(value) depending on whether the missingness is random.

Interview Tips

  • Think out loud — interviewers grade your reasoning, not just the final answer.
  • Start with the brute-force solution, then optimize once it works.
  • Always mention time and space complexity, even if not asked directly.
  • If you're stuck, ask a clarifying question instead of guessing silently.
  • Re-read the question after coding to catch edge cases like empty input.
Previous SQL Interview Questions Back to Blog Next Machine Learning Interview Questions
Ankit Verma

Ankit Verma

Aspiring Data Analyst and Python developer, writing practical tutorials on Python, SQL, Power BI and Machine Learning at ankitiqcode.

Python SQL Power BI Machine Learning

Keep learning

Common questions

Frequently Asked Questions

Python alone can get you roles in automation, backend and data analytics, but pairing it with SQL and a framework like Django, Flask or Pandas/NumPy significantly widens your options.

For a fresher role, covering 60 to 100 core questions across basics, OOP, exceptions, file handling and data structures is usually sufficient for most first and second round interviews.

No. Freshers are mostly tested on syntax, data structures and OOP basics, while experienced developers face deeper questions on memory management, decorators, generators, concurrency and design patterns.

You should be comfortable writing correct syntax from memory for common patterns, but interviewers usually care more about your logic and problem-solving approach than perfect syntax recall.

Lists are mutable and slightly slower, while tuples are immutable, hashable and faster, which makes tuples suitable as dictionary keys and for fixed collections of data.

If you are applying for data analyst, data science or ML roles, yes — NumPy and Pandas questions are almost always included alongside core Python basics.

Expect questions on classes vs objects, the four pillars of OOP, method overloading vs overriding, constructors, and the difference between class, static and instance methods.

They are common at the intermediate to experienced level because they test your understanding of Python internals like iterators, closures and memory efficiency, so they're worth practicing even as a fresher.

Most core language questions apply across Python 3.x versions, but it helps to mention you're using Python 3.10+ features like structural pattern matching if you bring them up.

Practice writing the code examples yourself without copying, then try explaining each answer out loud in under a minute, since interviews reward clear explanation as much as correct code.

💬 Comments coming soon