Python Interview Questions: Complete Guide for Success
AI Insights
Powered by GPT-4o-mini
A complete original Python interview guide covering basics, data structures, functions, recursion, OOP, files, exceptions, iterators, generators, decorators, modules, output tracing, and coding practice.
Quick Summary
Prepare for your Python interview with our complete guide covering key concepts, practice problems, and expert tips for success.
Complete Python Interview Questions and Practice Problems
This guide is a complete interview revision file for the Python Foundations series.
It covers the ideas from the earlier lessons:
- Python basics, variables, input, output, and type conversion
- operators, control flow, loops, and pattern thinking
- strings, lists, tuples, sets, and dictionaries
- functions, recursion, time complexity, and memory behavior
- OOP, encapsulation, inheritance, polymorphism, and abstraction
- file handling, JSON, pickle, exceptions, iterators, generators, namespaces, closures, decorators, modules, imports, and packages
All questions, explanations, examples, and practice problems here are written freshly. Use this as a learning and interview-preparation guide, not as a memorization sheet.
How to Use This Interview Guide
Use three passes:
- Read the question and answer it out loud before looking.
- Compare your answer with the explanation.
- Run or mentally trace the code where shown.
In interviews, the best answers are usually:
- clear
- short at first
- backed by one example
- honest about edge cases
- connected to practical use
Interview Answer Formula
For theory questions, use this structure:
- Define the concept.
- Mention why it matters.
- Give a small example.
- Mention one common mistake or edge case.
Example:
A list is an ordered, mutable collection in Python.
It is useful when we need to store items and update them later.
For example, scores = [10, 20, 30].
A common mistake is copying a nested list with copy(), because nested objects are still shared.Part 1: Core Python Interview Questions
1. What is Python?
Python is a high-level, general-purpose programming language known for readable syntax and a large standard library.
It is used for web development, automation, data analysis, machine learning, scripting, testing, backend services, and many other tasks.
2. Why is Python called high-level?
Python hides many low-level details such as manual memory management and direct CPU instructions.
You write code closer to human-readable logic:
name = "Asha"
print(f"Welcome, {name}")Explanation
- The variable
nameis assigned the string value "Asha". - The
printfunction outputs a formatted string that includes the value ofname. - The f-string syntax (prefixing the string with
f) allows for easy insertion of variable values directly within the string. - The output of this code will be: "Welcome, Asha".
3. Is Python interpreted or compiled?
Python is commonly called interpreted because users usually run source code directly.
In CPython, Python source code is first compiled internally into bytecode, and then that bytecode is executed by the Python virtual machine.
4. What is CPython?
CPython is the reference implementation of Python, written mainly in C.
When most people say "Python", they usually mean CPython unless they mention another implementation such as PyPy or Jython.
5. What is dynamic typing?
Dynamic typing means variable names do not have fixed declared types.
value = 10
value = "ten"
print(value)Explanation
- The variable
valueis initially assigned an integer of 10. - The variable
valueis then reassigned to the string "ten", overriding the previous integer value. - The
printfunction outputs the current value of the variable, which will display "ten". - This snippet illustrates how Python allows dynamic typing, enabling variables to change types during execution.
The name value first points to an integer object and later points to a string object.
6. What is strong typing?
Strong typing means Python does not silently mix incompatible types in unsafe ways.
age = 25
print("Age: " + str(age))Explanation
- The variable
ageis assigned the integer value of 25. - The
printfunction is used to output a string that includes the age. - The integer
ageis converted to a string usingstr(age)to ensure proper concatenation. - The final output will display "Age: 25" in the console.
Without str(age), string concatenation with an integer would fail.
7. What is PEP 8?
PEP 8 is Python's style guide.
It gives naming, formatting, indentation, spacing, and readability conventions. It is not the language grammar, but it helps teams write consistent code.
8. Why is indentation important in Python?
Indentation defines code blocks in Python.
score = 85
if score >= 50:
print("pass")
else:
print("try again")Explanation
- The variable
scoreis initialized with a value of 85. - An
ifstatement checks if thescoreis greater than or equal to 50. - If the condition is true, it prints "pass"; otherwise, it prints "try again".
- This code effectively categorizes the score into a pass/fail outcome based on a threshold.
Wrong indentation can change meaning or raise an error.
9. What are keywords?
Keywords are reserved words with special meaning.
Examples include if, else, for, while, def, class, try, except, return, yield, import, global, and nonlocal.
10. What are identifiers?
Identifiers are names created by programmers for variables, functions, classes, modules, and other objects.
Good identifiers are descriptive:
completed_lessons = 12Explanation
- The variable
completed_lessonsis assigned the integer value of 12. - This could represent the total number of lessons a user has finished in an educational application.
- The variable can be used later in the code for calculations, condition checks, or displaying progress.
- It serves as a simple way to store and manipulate user progress data.
11. What does print() do?
print() writes text representation of objects to standard output.
print("Python", "Interview", sep=" - ", end="!\n")Explanation
- The
printfunction is used to display text output to the console. - The
sepparameter specifies the string inserted between multiple arguments, here it is set to " - ". - The
endparameter defines what is printed at the end of the output; in this case, it adds an exclamation mark followed by a newline. - The output of this code will be:
Python - Interview!
Output:
Python - Interview!12. What does input() return?
input() always returns a string.
raw_age = input("Age: ")
age = int(raw_age)Explanation
- The
input()function prompts the user to enter their age as a string. - The entered value is stored in the variable
raw_age. - The
int()function converts the string value ofraw_ageinto an integer and assigns it to the variableage. - This conversion allows for numerical operations to be performed on the age value later in the program.
Convert it when you need a number.
13. What is type conversion?
Type conversion changes a value from one type to another.
price = "199"
quantity = 3
print(int(price) * quantity)Explanation
- The variable
priceis initialized as a string containing the value "199". - The variable
quantityis set to an integer value of 3. - The
int(price)function converts the stringpriceto an integer for mathematical operations. - The
printfunction outputs the result of multiplying the integer value ofpricebyquantity, which is 597.
14. What is implicit type conversion?
Implicit conversion happens when Python safely converts one type during an expression.
result = 10 + 2.5
print(result)Explanation
- The variable
resultis assigned the sum of an integer (10) and a float (2.5). - Python automatically handles the addition of different numeric types, resulting in a float.
- The
printfunction outputs the value ofresultto the console, which will be 12.5. - This snippet illustrates how Python can perform arithmetic operations seamlessly.
Output:
12.515. What is explicit type conversion?
Explicit conversion is done manually with functions such as int(), float(), str(), list(), tuple(), set(), and dict().
16. What does a Python variable store?
A Python variable stores a reference to an object, not the object directly.
first = [1, 2]
second = first
second.append(3)
print(first)Explanation
- The variable
firstis initialized as a list containing two integers: 1 and 2. - The variable
secondis assigned to reference the same list object asfirst, not a copy. - When
3is appended tosecond, it modifies the original list that bothfirstandsecondreference. - The
print(first)statement outputs the modified list, which now includes the appended value, resulting in[1, 2, 3]. - This demonstrates how mutable objects like lists in Python can be affected by changes through multiple references.
Output:
[1, 2, 3]Both names point to the same list.
17. What is object identity?
Object identity is the unique identity of an object during its lifetime.
Use id() to inspect it:
items = ["python"]
print(id(items))Explanation
- The code initializes a list named
itemscontaining a single string element "python". - The
id()function is called withitemsas an argument, which returns the unique memory address of the list object. - The
print()function outputs this memory address to the console, allowing you to see where the list is stored in memory. - This can be useful for understanding object identity and memory management in Python.
18. What is the difference between == and is?
== compares values.
is compares object identity.
a = [1, 2]
b = [1, 2]
c = a
print(a == b)
print(a is b)
print(a is c)Explanation
- The code initializes two lists,
aandb, with identical contents, and assignscto reference the same list asa. - The expression
a == bchecks for value equality, returningTruesince both lists contain the same elements. - The expression
a is bchecks for identity, returningFalsebecauseaandbare two distinct objects in memory. - The expression
a is cchecks for identity, returningTruesincecreferences the same object asa.
Output:
True
False
True19. What are mutable objects?
Mutable objects can be changed after creation.
Examples include lists, dictionaries, and sets.
20. What are immutable objects?
Immutable objects cannot be changed after creation.
Examples include integers, floats, strings, tuples, booleans, and frozensets.
21. Why are strings immutable?
When you "modify" a string, Python creates a new string.
title = "python"
updated = title.upper()
print(title)
print(updated)Explanation
- The variable
titleis initialized with the string "python". - The
upper()method is called ontitle, converting it to uppercase and storing the result in the variableupdated. - The original string
titleis printed, displaying "python". - The uppercase version stored in
updatedis printed, displaying "PYTHON".
Output:
python
PYTHON22. What is truthy and falsy?
Python treats some values as false in conditions.
Falsy examples:
FalseNone00.0""[]{}set()
Non-empty containers and non-zero numbers are usually truthy.
23. What is None?
None represents absence of a value.
It is not the same as 0, False, or an empty string.
result = None
if result is None:
print("No result yet")Explanation
- Initializes a variable
resultwith a value ofNone. - Uses an
ifstatement to check ifresultis stillNone. - If the condition is true, it prints "No result yet" to the console.
- This code can be useful for debugging or handling cases where a result is expected but not yet available.
24. What is the difference between type() and isinstance()?
type() gives the exact class of an object.
isinstance() checks whether an object belongs to a class or subclass.
print(type(True))
print(isinstance(True, int))Explanation
- The
print(type(True))statement outputs the type of the Boolean valueTrue, which is<class 'bool'>. - The
print(isinstance(True, int))statement checks ifTrueis an instance of theintclass, returningTruesince in Python,Trueis treated as1. - This code demonstrates the dual nature of Boolean values in Python, where they are subclasses of integers.
- It highlights how Boolean values can be used interchangeably with integers in certain contexts, such as arithmetic operations.
Output:
<class 'bool'>
True25. What is floor division?
Floor division uses // and returns the floor of the division result.
print(7 // 2)
print(-7 // 2)Explanation
- The
//operator performs floor division, which returns the largest integer less than or equal to the division result. - The first line
print(7 // 2)calculates the floor division of 7 by 2, resulting in 3. - The second line
print(-7 // 2)calculates the floor division of -7 by 2, resulting in -4, demonstrating how floor division rounds down towards negative infinity. - This behavior is important for understanding how Python handles division with negative numbers compared to other programming languages.
Output:
3
-426. What is the modulo operator?
% returns the remainder after division.
print(17 % 5)Explanation
- The
printfunction outputs the result of the expression inside it to the console. - The expression
17 % 5uses the modulus operator%, which returns the remainder of the division of 17 by 5. - In this case, 17 divided by 5 equals 3 with a remainder of 2, so the output will be
2. - This operation is useful for determining if a number is even or odd, or for cyclic calculations.
Output:
227. What is operator precedence?
Operator precedence decides which part of an expression is evaluated first.
print(2 + 3 * 4)
print((2 + 3) * 4)Explanation
- The first print statement calculates
2 + 3 * 4, where multiplication has higher precedence than addition, resulting in2 + 12, which equals14. - The second print statement calculates
(2 + 3) * 4, where the parentheses force the addition to be performed first, resulting in5 * 4, which equals20. - This snippet demonstrates how operator precedence and parentheses can affect the outcome of arithmetic operations in Python.
- It highlights the importance of understanding the order of operations to avoid unexpected results in calculations.
Output:
14
2028. What is short-circuit evaluation?
Python may stop evaluating a logical expression once the result is already known.
name = ""
if name and name[0] == "A":
print("Starts with A")
else:
print("No usable name")Explanation
- Initializes an empty string variable
name. - Uses a conditional statement to check if
nameis non-empty and if its first character is 'A'. - If both conditions are true, it prints "Starts with A".
- If either condition is false, it prints "No usable name".
Because name is empty, name[0] is not evaluated.
29. What is a conditional expression?
It is Python's compact if-else expression.
score = 72
status = "pass" if score >= 50 else "fail"
print(status)Explanation
- A variable
scoreis initialized with a value of 72. - A conditional expression assigns "pass" to the variable
statusifscoreis 50 or higher; otherwise, it assigns "fail". - The
printfunction outputs the value ofstatus, which will be "pass" in this case.
30. What is the difference between for and while loops?
Use for when you are iterating over a known iterable.
Use while when the loop depends on a condition that may change.
31. What are break, continue, and pass?
break exits the loop.
continue skips to the next iteration.
pass does nothing and is used as a placeholder.
32. What does range() produce?
range() produces an immutable sequence-like object that generates numbers lazily.
for number in range(2, 7, 2):
print(number)Explanation
- The
range(2, 7, 2)function generates a sequence of numbers starting from 2 up to, but not including, 7, with a step of 2. - The loop iterates through the generated numbers, which are 2, 4, and 6.
- The
print(number)statement outputs each number in the sequence to the console. - This code effectively showcases how to work with ranges and control the increment in a loop.
Output:
2
4
633. What is loop else?
A loop else block runs when the loop finishes normally, without break.
target = 7
numbers = [2, 4, 6]
for number in numbers:
if number == target:
print("found")
break
else:
print("not found")Explanation
- The variable
targetis set to 7, which is the number the code will search for in the listnumbers. - The list
numberscontains three integers: 2, 4, and 6. - A
forloop iterates through eachnumberin thenumberslist. - If a
numbermatches thetarget, it prints "found" and exits the loop usingbreak. - If the loop completes without finding the target, the
elseblock executes, printing "not found".
34. What are membership operators?
in and not in test membership.
tags = ["python", "oop", "files"]
print("oop" in tags)Explanation
- A list named
tagsis created containing three string elements: "python", "oop", and "files". - The
printfunction is used to output the result of the expression"oop" in tags. - The expression evaluates to
Trueif "oop" is found in thetagslist, andFalseotherwise. - This demonstrates the use of the
inkeyword for membership testing in Python lists.
35. What are bitwise operators?
Bitwise operators work on integer bits.
Common examples are &, |, ^, ~, <<, and >>.
They are useful in flags, masks, permissions, and low-level tasks.
36. How does string indexing work?
Strings are indexed from 0.
Negative indexes count from the end.
word = "python"
print(word[0])
print(word[-1])Explanation
- The variable
wordis assigned the string value "python". print(word[0])outputs the first character of the string, which is 'p'.print(word[-1])outputs the last character of the string, which is 'n'.- This code demonstrates how to use positive and negative indexing to access string elements.
Output:
p
n37. How does slicing work?
Slicing uses start:stop:step.
word = "interview"
print(word[0:5])
print(word[::-1])Explanation
- The variable
wordis initialized with the string "interview". - The first
printstatement outputs the first five characters of the string, resulting in "inter". - The second
printstatement uses slicing with a step of -1 to reverse the string, producing "weivretni".
Output:
inter
weivretni38. Why should you prefer join() for combining many strings?
Repeated string concatenation can create many intermediate strings.
join() is clearer and usually more efficient for many pieces.
parts = ["python", "is", "clear"]
sentence = " ".join(parts)
print(sentence)Explanation
- A list named
partsis created containing three string elements: "python", "is", and "clear". - The
join()method is used on a space character to concatenate the elements of the list into a single string, with spaces in between. - The resulting string is stored in the variable
sentence. - Finally, the
print()function outputs the concatenated sentence to the console.
39. What is the difference between find() and index() on strings?
find() returns -1 if the substring is missing.
index() raises ValueError if the substring is missing.
40. What do split() and strip() do?
strip() removes surrounding whitespace or selected characters.
split() breaks a string into a list.
line = " python,oop,files "
print(line.strip().split(","))Explanation
- The
linevariable contains a string with leading and trailing spaces and comma-separated values. - The
strip()method removes any whitespace from the beginning and end of the string. - The
split(",")method then divides the cleaned string into a list using the comma as a delimiter. - The final output is a list of strings:
['python', 'oop', 'files'], with no extra spaces.
41. What is a list?
A list is an ordered, mutable collection.
scores = [90, 75, 88]
scores.append(92)
print(scores)Explanation
- A list named
scoresis initialized with three integer values representing scores. - The
appendmethod is used to add a new score,92, to the end of thescoreslist. - The
printfunction outputs the updated list, which now contains four scores:[90, 75, 88, 92].
42. What is the difference between append() and extend()?
append() adds one object as a single item.
extend() adds each item from an iterable.
items = [1, 2]
items.append([3, 4])
print(items)
items = [1, 2]
items.extend([3, 4])
print(items)Explanation
- The
appendmethod adds its argument as a single element to the end of the list, resulting in a nested list when a list is appended. - In the first case,
items.append([3, 4])results initemsbeing[1, 2, [3, 4]]. - The
extendmethod, on the other hand, iterates over its argument and adds each element to the list, effectively flattening the input. - In the second case,
items.extend([3, 4])results initemsbeing[1, 2, 3, 4]. - This distinction is crucial when manipulating lists in Python, as it affects the structure of the resulting list.
43. What is list aliasing?
Aliasing happens when two names refer to the same list.
primary = ["draft"]
alias = primary
alias.append("review")
print(primary)Explanation
- The variable
primaryis initialized as a list containing a single string element "draft". - The variable
aliasis assigned to reference the same list object asprimary, meaning both variables point to the same memory location. - When "review" is appended to
alias, it modifies the list that bothprimaryandaliasreference. - The
print(primary)statement outputs the modified list, which now contains both "draft" and "review".
44. How do you copy a list?
For a shallow copy, use copy(), slicing, or list().
original = ["a", "b"]
clone = original.copy()Explanation
- The variable
originalis initialized as a list containing two string elements: "a" and "b". - The
copy()method is called on theoriginallist to create a new list,clone, which contains the same elements. - The
clonelist is a shallow copy, meaning changes toclonewill not affectoriginal, and vice versa. - This method is useful for preserving the original list while allowing modifications to the copy.
For nested mutable objects, use copy.deepcopy() when you need independent nested data.
45. What is a tuple?
A tuple is an ordered, immutable collection.
It is useful for fixed records, multiple return values, and dictionary keys when all items are hashable.
46. Why does a one-item tuple need a comma?
The comma creates the tuple, not the parentheses.
not_tuple = (10)
one_item_tuple = (10,)
print(type(not_tuple))
print(type(one_item_tuple))Explanation
- The variable
not_tupleis assigned a single integer value, which does not create a tuple. - The variable
one_item_tupleis correctly defined as a tuple containing one item by including a trailing comma. - The
type()function is used to check the data types of both variables. - The output will show that
not_tupleis of typeint, whileone_item_tupleis of typetuple. - This snippet highlights the importance of the comma in tuple creation when defining single-item tuples in Python.
47. What is tuple unpacking?
Tuple unpacking assigns values from a tuple-like iterable to names.
name, score = ("Neha", 91)
print(name)
print(score)Explanation
- A tuple containing a name and a score is created and assigned to the variables
nameandscoresimultaneously. - The first element of the tuple, "Neha", is assigned to the variable
name. - The second element, 91, is assigned to the variable
score. - The
printstatements output the values ofnameandscoreto the console.
48. What is a set?
A set is an unordered collection of unique hashable items.
topics = {"python", "oop", "python"}
print(topics)Explanation
- A set named
topicsis initialized with three elements: "python", "oop", and "python". - Sets in Python automatically eliminate duplicate entries, so "python" appears only once in the final set.
- The
printfunction outputs the contents of thetopicsset to the console. - The order of elements in a set is not guaranteed, as sets are unordered collections.
49. Why are lists not allowed inside sets?
Set elements must be hashable.
Lists are mutable and unhashable, so they cannot be set elements.
50. What is a dictionary?
A dictionary maps keys to values.
Keys must be hashable. Values can be almost any object.
profile = {"name": "Ira", "score": 88}
print(profile["name"])Explanation
- A dictionary named
profileis created with two key-value pairs: "name" and "score". - The value associated with the key "name" is accessed using
profile["name"]. - The
printfunction outputs the value of "name", which is "Ira", to the console.
51. Why does dictionary membership check keys?
in checks dictionary keys because keys are the lookup mechanism.
profile = {"name": "Ira", "score": 88}
print("name" in profile)
print("Ira" in profile)Explanation
- A dictionary named
profileis created with two key-value pairs: "name" and "score". - The first print statement checks if the key "name" exists in the
profiledictionary, returningTrue. - The second print statement checks if the value "Ira" exists in the
profiledictionary, returningFalsesince it is not a key.
52. What are dictionary views?
keys(), values(), and items() return dynamic view objects.
They reflect dictionary changes.
53. When should you use a list, tuple, set, or dictionary?
Use a list for ordered mutable sequences.
Use a tuple for fixed records.
Use a set for uniqueness and membership tests.
Use a dictionary for key-value lookup.
54. What is a function?
A function is a reusable block of code that can receive inputs and return output.
def add_bonus(score, bonus):
return score + bonusExplanation
- The function
add_bonustakes two parameters:scoreandbonus. - It returns the sum of
scoreandbonus, effectively increasing the score by the specified bonus amount. - This function can be used in scoring systems where additional points are awarded, such as in games or assessments.
- It is a simple and reusable function that promotes code clarity and modularity.
55. What is the difference between parameter and argument?
A parameter is the name in the function definition.
An argument is the value passed during the function call.
56. What is the difference between print and return?
print displays a value.
return sends a value back to the caller.
def double(number):
return number * 2
result = double(5)
print(result)Explanation
- The
doublefunction takes a single parameter,number. - It returns the value of
numbermultiplied by 2. - The function is called with the argument
5, and the result is stored in the variableresult. - Finally, the value of
resultis printed, which outputs10.
57. What does a function return if there is no return statement?
It returns None.
def greet():
print("hello")
value = greet()
print(value)Explanation
- The
greetfunction is defined to print the string "hello" when called. - The function is invoked with
value = greet(), which executes the print statement inside the function. - The return value of the
greetfunction isNonesince it does not explicitly return anything, which is stored in the variablevalue. - The final print statement outputs the value of
value, which will beNone.
58. What are default arguments?
Default arguments are used when the caller does not provide a value.
def create_title(text, prefix="Lesson"):
return f"{prefix}: {text}"Explanation
- The function
create_titletakes two parameters:text(the main title) andprefix(defaulting to "Lesson"). - It uses an f-string to concatenate the prefix and the text, ensuring a consistent format.
- The return value is a string that combines the prefix and the text, separated by a colon.
- This function can be useful for creating standardized titles in educational or instructional content.
59. Why are mutable default arguments risky?
The default object is created once when the function is defined, not each time it is called.
Safer version:
def add_tag(tag, tags=None):
if tags is None:
tags = []
tags.append(tag)
return tagsExplanation
- The function
add_tagtakes two parameters:tag(the tag to be added) andtags(an optional list of existing tags). - If
tagsis not provided (i.e., it isNone), a new empty list is created to hold the tags. - The specified
tagis appended to thetagslist. - The updated list of tags is returned, allowing for easy accumulation of tags over multiple function calls.
- This approach ensures that each call to
add_tagcan either modify an existing list or create a new one if none is provided.
60. What are *args and **kwargs?
*args collects extra positional arguments.
**kwargs collects extra keyword arguments.
def describe_event(*labels, **details):
return labels, details
print(describe_event("python", "live", speaker="Maya"))Explanation
- The function
describe_eventaccepts a variable number of positional arguments (*labels) and keyword arguments (**details). - Positional arguments are collected into a tuple named
labels, while keyword arguments are stored in a dictionary nameddetails. - The function returns both
labelsanddetails, allowing for flexible input regarding event characteristics. - In the provided print statement, the function is called with two positional arguments ("python", "live") and one keyword argument (speaker="Maya").
61. What is a lambda function?
A lambda is a small anonymous function expression.
scores = [3, 10, 2]
print(sorted(scores, key=lambda value: value % 3))Explanation
- The list
scorescontains three integer values: 3, 10, and 2. - The
sorted()function is used to sort the list, with a custom sorting key defined by a lambda function. - The lambda function calculates the remainder of each score when divided by 3 (
value % 3). - The sorting will arrange the scores in ascending order based on these remainders.
- The output will be a new list of scores sorted according to their remainders: [3, 10, 2] becomes [3, 2, 10].
Use normal def when logic needs a name, documentation, or multiple statements.
62. What are first-class functions?
Functions are first-class objects in Python.
You can assign them to variables, pass them as arguments, return them from functions, and store them in containers.
63. What is scope?
Scope decides where a name can be accessed.
Python follows LEGB lookup:
- Local
- Enclosing
- Global
- Built-in
64. What is the global keyword?
global tells Python that assignment should target a module-level name.
Use it carefully because it can make code harder to reason about.
65. What is the nonlocal keyword?
nonlocal lets a nested function assign to a name from an enclosing function scope.
def make_counter():
count = 0
def next_count():
nonlocal count
count += 1
return count
return next_countExplanation
Unlock the Full Article
You're reading a free 30% preview. The rest of this article is available to premium members.
Already a premium member? Sign in here
