Python / Core Python Fundamentals Interview Questions
1. What is Python and what makes it popular for software development?
Python is a high-level, interpreted, general-purpose programming language created by Guido van Rossum and first released in 1991. Its defining feature is readability: the syntax is clean and close to plain English, which dramatically lowers the learning curve compared with languages like C++ or J...
2. How do variables work in Python, and what does dynamic typing mean?
In Python a variable is simply a name that points to an object in memory. You do not declare the type — you just assign a value and Python figures out the type at runtime. That is what dynamic typing means: the type is attached to the object , not to the name . x = 10 # x points to an int object ...
3. How do conditional statements work in Python?
Python uses if , elif , and else to branch execution. Unlike many languages, Python relies on indentation (four spaces by convention) rather than braces to delimit blocks — mixing tabs and spaces causes a TabError . score = 72 if score >= 90 : grade = 'A' elif score >= 80 : grade = 'B' elif score...
4. How does the for loop work in Python, and what is the role of range()?
Python's for loop iterates over any iterable — lists, strings, tuples, dictionaries, files, generators, and more. Unlike C-style for loops with an index counter, Python's loop just hands you each item in turn. fruits = [ 'apple' , 'banana' , 'cherry' ] for fruit in fruits: print ( fruit ) # Itera...
5. When should you use a while loop instead of a for loop in Python?
Use a while loop when the number of iterations is not known upfront and the loop should continue as long as a condition remains true. A for loop is for iterating over a known sequence; a while loop is for repeating until something changes. attempts = 0 max_attempts = 3 while attempts < max_attemp...
6. What is a Python list and what operations are most commonly used?
A list is Python's built-in ordered, mutable sequence. It can hold items of any type — including other lists — and grows or shrinks dynamically. Lists are backed by a C array that doubles in capacity when it runs out of space, so appending is O(1) amortised. # Creation items = [ 10 , 'hello' , 3....
7. What is a tuple in Python and when should you choose it over a list?
A tuple is an ordered, immutable sequence. Once created it cannot be changed — no appending, inserting, or item reassignment. The syntax uses parentheses (optional in many contexts) or just a comma: point = 3, 4 is a tuple. coords = ( 40.7128 , - 74.0060 ) # latitude, longitude x, y = coords # tu...
8. How do Python dictionaries work and what are the most important operations?
A dictionary is Python's hash-map: an unordered (insertion-ordered since Python 3.7) collection of key-value pairs. Keys must be hashable (strings, numbers, tuples of hashable items); values can be anything. Lookup, insertion, and deletion are O(1) average-case. user = { 'name' : 'Alice' , 'age' ...
9. What is a Python set and what makes it useful for membership testing?
A set is an unordered collection of unique, hashable objects. Internally it is a hash table, giving O(1) average-case lookup — far faster than scanning a list for large collections. Duplicates are silently dropped on creation. tags = { 'python' , 'data' , 'python' , 'api' } # {'python', 'data', '...
10. How do you define and call a function in Python?
Functions are defined with the def keyword, a name, parentheses for parameters, a colon, and an indented body. They are first-class objects — you can assign them to variables, pass them as arguments, and return them from other functions. def greet (name, greeting = 'Hello' ): """Return a personal...
11. What is variable scope in Python and how does the LEGB rule work?
Scope determines where in the code a variable name is visible and accessible. Python resolves names using the LEGB rule, checking four scopes in order: Local → Enclosing → Global → Built-in . x = 'global' def outer (): x = 'enclosing' def inner (): x = 'local' print(x) # local inner() print(x) # ...
12. How does exception handling work in Python using try/except?
Python uses a try/except block to catch and handle exceptions rather than crashing the program. Code that might raise an error goes inside try ; the handler goes inside except . try : result = int(input( 'Enter a number: ' )) print( 100 / result) except ValueError : print( 'Not a valid integer.' ...
13. What are the different ways to format strings in Python, and which is preferred?
Python has three main approaches to string formatting, each with different trade-offs. name, score = 'Alice' , 95.5 # 1. % formatting (old-style, C printf-inspired) print( 'Name: %s, Score: %.1f' % (name, score)) # 2. str.format() (Python 2.6+ / 3) print( 'Name: {}, Score: {:.1f}' . format(name, ...
14. What is list comprehension and how does it differ from a regular for loop?
List comprehension is a concise, readable way to build a new list by describing what each element should be, rather than imperatively appending in a loop. It runs faster than an equivalent for loop + append because CPython optimises the comprehension into a single opcode sequence without repeated...
15. What are *args and **kwargs in Python function definitions?
*args and **kwargs are conventions (the names are arbitrary; the stars are what matter) for writing functions that accept a variable number of arguments. def log (level, * messages, separator = '|' , ** meta): joined = separator . join(messages) extra = ', ' . join( f '{ k }={ v }' for k, v in me...
16. What is a lambda function in Python and when is it appropriate to use one?
A lambda is an anonymous, single-expression function defined inline. The syntax is lambda parameters: expression . It returns the value of the expression automatically — no return keyword needed. It can have any number of parameters, including defaults and *args . double = lambda x: x * 2 print(d...
17. What is the mutable default argument trap in Python and how do you fix it?
One of Python's most notorious gotchas: default argument values are evaluated once at function definition time, not each time the function is called. If that default is a mutable object like a list or dict, every call that uses the default shares the same object, producing surprising accumulated ...
18. How do you use dictionary comprehension to transform data payloads in Python?
Dictionary comprehension is the clean, Pythonic way to build or transform a dict in one expression. The syntax mirrors list comprehension: {key_expr: value_expr for variable in iterable if condition} . It is commonly used when processing API response payloads, config maps, or any key-value data t...
19. How does slicing work in Python for lists, strings, and tuples?
Slicing extracts a sub-sequence from any sequence type using the notation sequence[start:stop:step] . All three parts are optional and default to the beginning, end, and a step of 1 respectively. Slicing always returns a new object of the same type — it does not modify the original. data = [ 0 , ...
20. What is tuple unpacking and extended unpacking in Python?
Unpacking assigns the individual elements of a sequence to multiple variables in a single statement. The left side must have the same number of names as the sequence has elements, or you get a ValueError . # Basic unpacking x, y, z = ( 10 , 20 , 30 ) first, second = 'AB' # Swap without a temp var...
21. What do the pass, break, and continue statements do in Python loops?
These three keywords control loop flow in different ways, and confusing them is a common source of bugs. pass : Does absolutely nothing. It is a syntactic placeholder used wherever Python requires a statement but you have nothing to write yet — an empty function body, an empty class, a stub excep...
22. What is None in Python, and when should you use 'is' versus '=='?
None is Python's null value — a singleton object of type NoneType . It represents the absence of a value: default function returns, uninitialised optional variables, missing dict values. There is exactly one None object in any Python process. The key distinction for comparisons: == tests equality...
23. How do you work with nested data structures such as a list of dictionaries?
A list of dictionaries is the most common Python pattern for representing structured data from APIs, CSV rows, database query results, and JSON payloads. Each dictionary is one record; the list is the collection. employees = [ { 'name' : 'Alice' , 'dept' : 'Engineering' , 'salary' : 95000 }, { 'n...
24. What is a generator in Python and how does it differ from a list?
A generator is a function that uses the yield keyword to return values one at a time, pausing execution between yields and resuming from the same point when the next value is requested. It produces an iterator without building the entire result in memory. # List builds everything in memory first ...
25. What is a decorator in Python and how do you write one?
A decorator is a function that takes another function as input, wraps it with extra behaviour, and returns the wrapped version. The @decorator syntax is shorthand for func = decorator(func) . Decorators exploit the fact that Python functions are first-class objects. import time def timer (func): ...
26. How do you define a class in Python, and what is the role of __init__?
A class is a blueprint for objects. Define it with the class keyword. The special method __init__ (the constructor) is called automatically when you create an instance and is where you set up the object's initial state by assigning to self.attribute . class BankAccount : interest_rate = 0.03 # cl...
27. How does inheritance work in Python and what is method resolution order (MRO)?
Inheritance lets a child class reuse and extend behaviour from a parent class. Specify the parent in parentheses after the class name. The child gets all the parent's methods automatically and can override any of them. class Animal : def __init__ (self, name): self . name = name def speak (self):...
28. How do you read from and write to files in Python?
Python's built-in open() function returns a file object. Always use it as a context manager with with — this guarantees the file is closed (and the OS buffer flushed) even if an exception occurs, avoiding resource leaks. # Writing a file with open( 'notes.txt' , 'w' , encoding = 'utf-8' ) as f: f...
29. How do Python modules and imports work?
A module is any .py file. Importing it executes the file (once per interpreter session; subsequent imports reuse the cached version from sys.modules ) and makes its names available in the importing namespace. # Importing the whole module â access via module.name import math print(math . sqrt( 1...
30. Which Python built-in functions are most important to know for coding interviews?
Python's built-in namespace contains roughly 70 functions. The ones that come up constantly in interview problems and real-world code are: Sequence and iteration : len() , range() , enumerate() , zip() , sorted() , reversed() , min() / max() (accept a key= argument), sum() , map() , filter() , an...
31. How does Python determine whether a custom object is truthy or falsy?
Every Python object has a boolean value. In a boolean context (an if condition, a while condition, or passed to bool() ), Python calls the object's __bool__ method first. If that is not defined, it falls back to __len__ and returns False if __len__ returns 0. If neither is defined, the object is ...
32. What is the difference between a shallow copy and a deep copy in Python?
This distinction matters whenever you have nested or mutable objects and want an independent copy. An assignment ( b = a ) creates a second name for the same object — not a copy at all. Mutating b mutates a . A shallow copy creates a new container object but does not copy the objects inside it — ...
33. Which Python string methods are most useful for cleaning and parsing data payloads?
String manipulation is the backbone of text-based data processing. Python strings are immutable, so every method returns a new string. raw = ' Hello, World! ' # Trimming whitespace raw.strip() # 'Hello, World!' â both ends raw.lstrip() # 'Hello, World! ' raw.rstrip() # ' Hello, World!' # Case o...
34. How do enumerate() and zip() make loops more Pythonic?
Both functions are loop helpers that eliminate boilerplate index management and make the intent of the code clearer. enumerate(iterable, start=0) yields (index, value) pairs. Instead of maintaining a counter variable, you unpack it directly in the loop header: # Non-Pythonic i = 0 for name in nam...
35. What is the Python exception class hierarchy and how do you create custom exceptions?
Python exceptions form a class hierarchy rooted at BaseException . Most exceptions you deal with inherit from Exception , which itself inherits from BaseException . The hierarchy determines which except clauses match a raised exception — a handler for a parent class catches instances of all child...
36. What is the walrus operator (:=) and when is it useful?
The walrus operator ( := ), introduced in Python 3.8 (PEP 572), is the assignment expression operator. It assigns a value to a variable as part of a larger expression rather than as a standalone statement. The name comes from its resemblance to a walrus face with tusks. # Without walrus â evalu...
37. How does Python's sort work, and what is the difference between sort() and sorted()?
Python has two primary ways to sort: the list method list.sort() and the built-in function sorted() . Both use the Timsort algorithm (a hybrid of merge sort and insertion sort) with O(n log n) worst-case complexity, and both accept key= and reverse= arguments. nums = [ 5 , 2 , 8 , 1 , 9 ] # sort(...
38. What are Python dataclasses and when should you use them instead of regular classes?
@dataclass (introduced in Python 3.7, PEP 557) is a class decorator that auto-generates boilerplate methods — __init__ , __repr__ , and __eq__ — from class-level field annotations. It removes the tedium of writing identical initialisation code for data-holding classes. from dataclasses import dat...
39. What is a context manager in Python and how do you implement one?
A context manager controls setup and teardown around a block of code via the with statement. The canonical example is file handling, but context managers are used for database transactions, locking, temporary directory creation, patching in tests, and any resource that needs guaranteed cleanup. P...
40. How do Python type hints work and how do you use them in function signatures?
Type hints (PEP 484, Python 3.5+) let you annotate variables, function parameters, and return values with expected types. They are completely ignored at runtime by the interpreter but can be checked statically by tools like mypy , pyright , and IDE analysers, catching type errors before code ever...
41. Can you create a tuple comprehension in Python, and what is a generator expression?
There is no tuple comprehension syntax in Python — (x for x in range(5)) is a generator expression , not a tuple. To get a tuple from a comprehension-like construct, wrap a generator expression in tuple() : # Generator expression â lazy, single-pass, no tuple gen = (x ** 2 for x in range( 5 )) ...
42. How does recursion work in Python and what are its limitations?
A recursive function calls itself to break a problem into smaller sub-problems of the same kind. Every recursive function needs a base case that stops the recursion and a recursive case that moves toward the base case. def factorial (n): if n <= 1 : # base case return 1 return n * factorial(n - 1...
43. How do you parse and build JSON payloads in Python?
Python's built-in json module converts between JSON strings/files and Python objects. The mapping is: JSON object ↔ Python dict, JSON array ↔ Python list, JSON string ↔ Python str, JSON number ↔ Python int/float, JSON true/false ↔ Python True/False, JSON null ↔ Python None. import json # --- Pars...
44. Why should you use Python's logging module instead of print() in production code?
Using print() for diagnostics is fine during quick development, but it has serious limitations in any real-world application: output always goes to stdout, there is no severity level, you cannot turn it off without editing code, and there is no timestamp, file name, or line number. Python's loggi...
45. What is PEP 8 and which conventions does it define for Python code?
PEP 8 is Python's official style guide, written by Guido van Rossum, Barry Warsaw, and Nick Coghlan. It defines conventions for formatting Python code so that all Python code looks consistent and is easier to read and review. The most frequently tested conventions: Indentation : 4 spaces per leve...