Guides › Python Programming
Python Interview Questions and Answers: Complete Guide
Prepare for Python interviews with beginner and advanced questions on data types, functions, OOP, exceptions, iterators, generators, and coding problems.
Python Interview Questions and Answers: Complete Guide
This guide covers common Python interview topics, from basic syntax and data types to object-oriented programming, generators, exception handling, and coding exercises.
Use it to revise concepts, practise writing code, and explain the reasoning behind your answers.
1. What Is Python?
Python is a high-level, general-purpose programming language known for readable syntax. It is used in web development, automation, testing, data analysis, and AI.
2. Is Python Compiled or Interpreted?
Python is commonly described as an interpreted language. In CPython, source code is compiled to bytecode and then executed by the Python virtual machine. Other implementations may work differently.
3. What Are Mutable and Immutable Types?
Mutable objects can be modified after creation. Lists, dictionaries, and sets are common examples.
Immutable objects cannot be modified in place. Integers, strings, and tuples are common examples, although a tuple may contain a mutable object.
4. What Is the Difference Between a List and a Tuple?
A list is mutable, while a tuple is immutable at the container level. Lists are useful for collections that change; tuples are useful for fixed groups of values.
5. What Is a Dictionary?
A dictionary stores key-value pairs and supports efficient average-case lookups by key.
student = {"name": "Shubham", "marks": 90}
print(student["name"])
6. What Is a Set?
A set stores unique hashable elements. It is useful for removing duplicates and performing union, intersection, and difference operations.
7. What Is the Difference Between == and is?
== checks value equality. is checks object identity.
Use is None to test whether a value is None. Do not use is as a general replacement for equality.
8. What Are *args and **kwargs?
*args collects extra positional arguments into a tuple. **kwargs collects extra keyword arguments into a dictionary.
def show(*args, **kwargs):
print(args)
print(kwargs)
show(1, 2, name="Sam")
9. What Is a Lambda Function?
A lambda expression creates a small anonymous function containing a single expression.
square = lambda x: x * x
print(square(5))
Use a regular function when logic needs more explanation or multiple statements.
10. What Is a List Comprehension?
A list comprehension builds a list from an iterable.
squares = [x * x for x in range(5)]
It can make transformations concise, but ordinary loops are sometimes more readable.
11. What Is a Generator?
A generator produces values lazily, one at a time, instead of creating the complete result immediately.
def count_up_to(limit):
number = 1
while number <= limit:
yield number
number += 1
for value in count_up_to(3):
print(value)
Generators can reduce memory use when processing large sequences.
12. What Is an Iterator?
An iterator provides values one at a time through the iterator protocol, using __iter__() and __next__(). Generators are a convenient way to create iterators.
13. What Is a Decorator?
A decorator wraps or modifies a function or class without requiring the original definition to be rewritten.
def announce(func):
def wrapper():
print("Starting")
return func()
return wrapper
@announce
def greet():
print("Hello")
greet()
This simplified example demonstrates the concept. Production decorators often preserve metadata with functools.wraps and support arguments.
14. What Is a Context Manager?
A context manager handles setup and cleanup around a block of code.
with open("notes.txt", "r", encoding="utf-8") as file:
contents = file.read()
The file is closed appropriately when the block exits.
15. Explain Exception Handling
Use try and except to handle expected exceptions. The else block runs if no exception occurs, while finally runs during cleanup.
Catch specific exceptions where possible, and avoid silently swallowing unexpected errors.
16. What Is OOP?
Object-oriented programming organises software around classes and objects. Important concepts include encapsulation, abstraction, inheritance, and polymorphism.
17. What Is Inheritance?
Inheritance allows a class to derive behaviour from another class. Use it for meaningful subtype relationships, and consider composition when objects merely contain other objects.
18. What Is the Difference Between Shallow and Deep Copy?
A shallow copy creates a new outer container but keeps references to nested objects. A deep copy recursively copies nested objects where supported.
The copy module provides copy() and deepcopy().
19. What Is a Virtual Environment?
A virtual environment isolates a project's Python packages from other projects.
A common setup is:
python -m venv .venv
Activate it using the instructions for your operating system, then install the project's required dependencies.
20. What Is PEP 8?
PEP 8 is Python's style guide. It recommends consistent naming, indentation, whitespace, and other conventions that improve readability.
21. How Does Python Manage Memory?
Python implementations manage object memory automatically. CPython primarily uses reference counting and also has a cyclic garbage collector for reference cycles. Exact behaviour can vary between implementations.
22. What Is the GIL?
In traditional CPython builds, the Global Interpreter Lock (GIL) limits how multiple threads execute Python bytecode simultaneously. I/O-bound tasks can still benefit from threading. Multiprocessing or suitable native libraries may help CPU-bound work. Modern Python also offers optional free-threaded builds, so the exact answer depends on the implementation and build.
23. Coding Problem: Reverse a String
def reverse_string(text):
return text[::-1]
print(reverse_string("python"))
This uses slicing to create a reversed string.
24. Coding Problem: Check a Palindrome
def is_palindrome(text):
cleaned = text.lower().replace(" ", "")
return cleaned == cleaned[::-1]
print(is_palindrome("level"))
For more complex text, decide explicitly how to handle punctuation and Unicode characters.
25. Coding Problem: Count Character Frequencies
from collections import Counter
text = "programming"
print(Counter(text))
This counts occurrences of each character.
26. Coding Problem: Remove Duplicates
def unique_items(items):
return list(dict.fromkeys(items))
print(unique_items([1, 2, 2, 3, 1]))
This preserves the first occurrence order in modern Python.
27. Coding Problem: Find the Largest Number
def largest_number(numbers):
if not numbers:
raise ValueError("List must not be empty")
return max(numbers)
print(largest_number([10, 5, 27, 14]))
The built-in max() is appropriate for this task. Be prepared to explain a loop-based solution as well.
28. Coding Problem: FizzBuzz
for number in range(1, 16):
if number % 15 == 0:
print("FizzBuzz")
elif number % 3 == 0:
print("Fizz")
elif number % 5 == 0:
print("Buzz")
else:
print(number)
Check divisibility by both 3 and 5 before checking either condition individually.
29. How to Prepare for Python Interviews
- Review language fundamentals.
- Practise writing code without relying on autocomplete.
- Explain time and space complexity where relevant.
- Solve problems involving strings, lists, dictionaries, and sets.
- Build at least one practical project.
- Learn basic testing, debugging, and Git.
- Practise explaining trade-offs and edge cases.
Conclusion
Strong interview preparation requires both conceptual understanding and hands-on practice. Learn why Python behaves as it does, write small programs regularly, and explain your solutions clearly.
Practice task: Solve the coding questions above independently, test edge cases, and then try solving each problem using a different approach.
More guides
- How to Use Codify: A 7-Day Start Plan — New here? Pick a roadmap, make a study plan, start the DSA sheet, revise with notes, practise for placements and test yourself — one step a day, then a daily routine.
- Infosys Preparation Guide: Online Test, Pseudocode and Interview — Roles (SE, DSE, SP), what each section of the Infosys online test checks, how to crack pseudocode and reasoning, a 4-week plan and the interview.
- Wipro Elite NLTH Preparation: Aptitude, Essay and Coding — The Wipro fresher test round by round — quant, logical and verbal, the written essay, two coding problems — plus a 3-week plan and interview tips.
- Accenture Preparation Guide: Cognitive, Technical, Coding and Communication — Every Accenture round explained — cognitive, MS Office/networking/cloud technical MCQs, pseudocode, coding and the spoken-English test — with a 4-week plan.