Article Summary
This article covers 53 questions spanning Python fundamentals, OOP, data structures, decorators, lambdas, coding challenges, and more.
Key takeaways
- Python interviews commonly cover language fundamentals, data structures, functions, object-oriented programming, and coding exercises.
- Understanding Python 3 features, including dictionary ordering, integer types, and exception handling, is essential.
- Advanced interviews may cover the global interpreter lock (GIL), generators, decorators, inheritance, and concurrency.
- Practicing coding problems and explaining your solutions clearly can help you prepare for your next interview.
Preparing for a Python interview? Whether you’re applying for your first developer role or moving into a more experienced position, you’ll need to demonstrate your understanding of Python fundamentals and practical programming skills.
Python interview questions often cover everything from basic syntax to data structures, functions, object-oriented programming, and coding challenges.
Below are 53 Python interview questions and answers to help you prepare, along with three bonus advanced questions and tips for improving your interview performance.
If you need to strengthen your Python skills, check out the following course on Udemy, created by Dr. Angela Yu.
Recommended Udemy course
1. What type of language is Python?
Python is a high-level, general-purpose programming language. It supports multiple programming styles, including object-oriented, procedural, and functional programming. It’s commonly described as an interpreted language.
2. What are some features of the Python language?
Python has several useful features:
- Interpreted execution: CPython automatically compiles source code into bytecode before executing it.
- Dynamic typing: Variable types are determined at runtime.
- Object-oriented programming: Python supports classes, inheritance, and composition.
- First-class functions: Functions can be passed as arguments, assigned to variables, and returned by other functions.
- Extensive libraries: Python includes a large standard library and supports third-party packages.
- Readable syntax: Python emphasizes clear, concise code.
3. What is PEP 8?
PEP 8 is Python’s official style guide. It provides recommendations for formatting code, naming variables, organizing imports, and improving readability and consistency.
4. What is the difference between a list and a tuple in Python?
A list is mutable, meaning you can add, remove, or replace elements. A tuple is immutable, meaning its elements cannot be reassigned after creation. However, a tuple can contain mutable objects, such as lists.
Here’s how Python’s main collection types compare:
| Type | Ordered | Mutable | Allows duplicates |
| List | Yes | Yes | Yes |
| Tuple | Yes | No | Yes |
| Set | No | Yes | No |
| Dictionary | Yes, by insertion | Yes | Keys must be unique |
Dictionaries have preserved insertion order as a language guarantee since Python 3.7.
5. How does Python manage memory?
Python manages memory automatically. In CPython, reference counting handles most object cleanup, while a garbage collector detects reference cycles. Memory management details can vary between Python implementations.
6. What is a Python namespace?
A namespace maps names to objects. It helps Python organize variables, functions, and classes while preventing naming conflicts. Examples include local, global, and built-in namespaces.
7. What is the purpose of the PYTHONPATH variable?
PYTHONPATH is an environment variable that adds directories to Python’s module search path, allowing Python to find modules during imports.
8. What is the purpose of the PYTHONSTARTUP variable?
PYTHONSTARTUP specifies a Python file to execute before the first prompt in an interactive Python session. It doesn’t run when executing a regular Python script.
9. What is the purpose of the PYTHONCASEOK variable?
PYTHONCASEOK allows case-insensitive module imports on Windows and macOS when set. It doesn’t apply to every platform.
10. What is the purpose of the PYTHONHOME variable?
PYTHONHOME changes the location Python uses to determine its standard-library installation directories. Unlike PYTHONPATH, it doesn’t simply add directories to the module search path.
11. What are Python modules?
A module is a file containing Python code, such as functions, variables, and classes. Modules help organize reusable code and can be imported into other programs.
12. What are some common modules in the Python standard library?
Some commonly used standard-library modules include:
- os: Interacts with operating-system functionality.
- sys: Provides access to interpreter information and settings.
- random: Generates pseudorandom numbers.
- datetime: Works with dates and times.
- json: Encodes and decodes JSON data.
- sqlite3: Works with SQLite databases.
- logging: Records application events.
- email: Parses and generates email messages.
- string: Provides string constants and formatting helpers.
- xml: Provides XML-processing packages.
- traceback: Formats and examines exception tracebacks.
13. What is scope in Python?
Scope determines where a name can be accessed. Python generally follows the LEGB rule when resolving names:
- Local: Names inside the current function.
- Enclosing: Names in enclosing functions.
- Global: Names defined at the module level.
- Built-in: Names provided by Python, such as print().
14. How would you get a user’s home directory (~) in Python?
Use os.path.expanduser():
import os
print(os.path.expanduser('~'))You can also use Path.home() from the pathlib module.
15. What built-in types does Python support?
Python’s built-in types include:
- Numeric: int, float, complex
- Text: str
- Boolean: bool
- Sequences: list, tuple, range
- Mapping: dict
- Sets: set, frozenset
- Binary: bytes, bytearray, memoryview
- Null value: None, an instance of NoneType
Learn everything about Data types in Python: A Guide for Beginners.
16. What is a Python decorator?
A decorator modifies or extends the behavior of a function or class without directly changing its definition.
The @ syntax applies a decorator.
def shout(func):
def wrapper(name):
return func(name).upper()
return wrapper
@shout
def greet(name):
return f"Hello, {name}"
print(greet("Ada")) # HELLO, ADAWriting @shout above greet() is equivalent to assigning greet = shout(greet).
17. What is pickling and unpickling in Python?
Pickling serializes a Python object into bytes. Unpickling reconstructs an object from those bytes.
The pickle module provides dump() and load() for file operations and dumps() and loads() for working directly with bytes. Never unpickle data from untrusted sources, because malicious pickle data can execute code.
18. What is a negative index in Python?
Negative indexing lets you access sequence elements from the end.
For example:
numbers = [10, 20, 30]
print(numbers[-1]) # 30
print(numbers[-2]) # 20An index of -1 refers to the last element.
19. How are global and local variables defined in Python?
Global variables are defined at the module level. Local variables are generally defined inside functions. Use the global keyword when you need to reassign a module-level variable from within a function.
count = 0
def increase():
global count
count += 120. Describe a few ways to generate a random number in Python.
Python’s random module provides several functions:
- random.random(): Returns a float from 0.0 up to, but not including, 1.0.
- random.uniform(a, b): Returns a random floating-point value between the supplied bounds.
- random.randint(a, b): Returns a random integer, including both endpoints.
import random
print(random.randint(1, 10))For security-sensitive randomness, use the secrets module instead.
21. What is a Python dictionary?
A dictionary is a mutable collection of key-value pairs. It provides fast lookups by key and preserves insertion order.
person = {'first': 'Bob', 'last': 'Smith'}
print(person['first']) # BobDictionary keys must be hashable and unique.
22. Is Python case-sensitive?
Yes. Python distinguishes between uppercase and lowercase characters in identifiers.
For example, name, Name, and NAME are three different variable names.
23. What is the output of the following code?
var = 'Hello Everyone!'
print(var)Output:
Hello Everyone!The print() function displays the string stored in var.
24. What is the output of the following code?
var = 'Hello Everyone!'
print(var[0])Output:
HPython uses zero-based indexing, so index 0 represents the first character.
25. What is the output of the following code?
var = 'Hello Everyone!'
print(var[2:5])Output:
lloString slicing includes the starting index but excludes the ending index.
26. How would you get all the keys in a Python dictionary?
Use the keys() method.
person = {'first': 'Bob', 'last': 'Smith'}
all_keys = person.keys()
print(list(all_keys)) # ['first', 'last']The keys() method returns a dynamic view of the dictionary’s keys.
27. How would you get all the values in a Python dictionary?
Use the values() method.
person = {'first': 'Bob', 'last': 'Smith'}
all_values = person.values()
print(list(all_values)) # ['Bob', 'Smith']Like keys(), values() returns a dictionary view.
28. How do you convert a string to an integer in Python?
Use the int() function.
x = '100'
number = int(x)
print(number) # 100You can optionally specify a numeric base, such as int(‘1010’, 2) for binary.
29. How do you convert a string to a large integer in Python?
Python 3 uses int for arbitrary-precision integers, subject to available memory and implementation limits.
x = '10012345678901234567890'
large_number = int(x)
print(large_number)Python 2’s separate long type no longer exists in Python 3.
30. How do you convert a string to a floating-point number in Python?
Use the float() function.
x = '100.12345'
number = float(x)
print(number) # 100.12345Invalid numeric strings raise a ValueError.
31. How do you convert an object to a string in Python?
Use the str() function.
number = 123
text = str(number)
print(text) # 123The str() function creates a human-readable string representation of an object.
32. What does the ** operator do in Python?
The ** operator performs exponentiation.
x = 2 ** 3
print(x) # 8This calculates 2 raised to the power of 3.
33. What does the // operator do in Python?
The // operator performs floor division, rounding the quotient down toward negative infinity.
print(8 // 3) # 2
print(-8 // 3) # -3Unlike truncation, floor division doesn’t always round toward zero.
34. What does the Python is operator do?
The is operator checks whether two references point to the same object.
x = [1, 2]
y = x
z = [1, 2]
print(x is y) # True
print(x is z) # False
print(x == z) # TrueUse is for identity and == for value equality.
35. What does the Python not in operator do?
The not in operator checks whether an item is absent from a collection.
numbers = [1, 2, 3]
print(4 not in numbers) # True
print(2 not in numbers) # FalseIt’s the logical opposite of in.
36. What does the Python break statement do?
The break statement immediately exits the nearest enclosing loop.
for number in range(5):
if number == 3:
break
print(number)Output: 0, 1, and 2, each on a separate line.
37. What does the Python continue statement do?
The continue statement skips the remaining code in the current loop iteration and moves to the next iteration.
for number in range(4):
if number == 2:
continue
print(number)Output: 0, 1, and 3, each on a separate line.
38. What does the Python pass statement do?
The pass statement does nothing. It’s used as a placeholder when Python requires a statement.
def future_function():
pass39. What are Python dictionary and list comprehensions?
Comprehensions provide concise syntax for creating collections from iterables.
A list comprehension creates a list:
numbers = [2, 3, 5]
squares = [x ** 2 for x in numbers]
print(squares) # [4, 9, 25]A dictionary comprehension creates a dictionary:
squared_dict = {x: x ** 2 for x in numbers}
print(squared_dict) # {2: 4, 3: 9, 5: 25}Comprehensions can also include conditions to filter elements.
40. What are Python lambda functions, and why are they used?
Lambda functions are anonymous functions defined using the lambda keyword.
They can accept multiple arguments but contain only one expression.
multiply = lambda x, y: x * y
print(multiply(2, 5)) # 10They’re useful for short operations, although regular functions are often clearer for complex logic.
41. How do you copy an object in Python?
Assignment with = creates another reference to an object rather than copying it. Python’s copy module provides two main copying methods:
- Shallow copy: Creates a new outer object while retaining references to nested objects.
- Deep copy: Recursively copies nested objects, using a memo to preserve appropriate shared references.
from copy import copy, deepcopy
original = [1, 2, [3, 4]]
shallow = copy(original)
deep = deepcopy(original)
original[2].append(5)
print(shallow) # [1, 2, [3, 4, 5]]
print(deep) # [1, 2, [3, 4]]42. What is self in Python?
self refers to the current instance of a class.
It’s conventionally used as the first parameter of instance methods and allows access to instance attributes and methods.
class Car:
def __init__(self, model):
self.model = model
def display(self):
print(self.model)
car = Car('Civic')
car.display() # Civicself is a convention, not a reserved Python keyword.
43. What is __init__ in Python?
The __init__() method initializes a newly created object. It’s commonly used to set instance attributes.
class Car:
def __init__(self, model, color):
self.model = model
self.color = colorThe __new__() method creates the object, while __init__() normally initializes it afterward.
44. What is a generator in Python?
A generator produces values one at a time instead of storing all of them in a list. Generator functions use the yield keyword.
def squares():
for n in range(1, 5):
yield n ** 2
for value in squares():
print(value)Output:
1
4
9
16Generators are useful for processing large datasets because values can be generated on demand.
For example:
squares_list = [n ** 2 for n in range(1_000_000)]
squares_gen = (n ** 2 for n in range(1_000_000))The list stores all its elements, while the generator computes values during iteration, usually reducing memory usage.
45. What does the Python help() function do?
The help() function displays documentation about Python modules, functions, classes, and other objects.
help(str)It displays help information and normally returns None.
46. What does the Python dir() function do?
The dir() function returns a list of names, typically attributes and methods, associated with an object.
print(dir(str))It’s useful for exploring an object’s available functionality.
47. What is the difference between .py and .pyc files?
- .py files: Contain Python source code.
- .pyc files: Contain compiled Python bytecode.
CPython commonly stores cached bytecode files inside a __pycache__ directory to speed up later imports. Bytecode caching isn’t required for Python to execute source code.
48. What is a docstring in Python?
A docstring is a string literal placed at the beginning of a module, class, function, or method to document its purpose.
def greet(name):
"""Return a personalized greeting."""
return f"Hello, {name}"
print(greet.__doc__)Docstrings are accessible through the __doc__ attribute and the help() function.
49. Write Python code to print a file’s contents, handling missing files.
Use open() with a try/except block.
try:
with open('filename.txt', 'r', encoding='utf-8') as file:
print(file.read())
except FileNotFoundError:
print('The file does not exist.')FileNotFoundError is a subclass of OSError. Catching it specifically is useful when you only want to handle missing files.
50. Write Python code to sum all numbers from 25 to 75, inclusive.
Use sum() with range().
total = sum(range(25, 76))
print(total) # 2550The upper limit is 76 because range() excludes its ending value.
51. Write Python code to print each line’s length, ignoring trailing whitespace.
Use rstrip() to remove trailing whitespace before counting characters.
with open('filename.txt', 'r', encoding='utf-8') as file:
for line in file:
print(len(line.rstrip()))The len() function then returns the length of each processed line.
52. Write Python code to remove whitespace from ‘abc def geh ijk’.
Use split() and join() to remove whitespace.
text = 'abc def geh ijk'
result = ''.join(text.split())
print(result) # abcdefgehijkTo remove only ordinary space characters, you can use text.replace(‘ ‘, ”).
53. Write Python code to remove duplicate items from a list.
For hashable items, use dict.fromkeys() to remove duplicates while preserving their original order.
numbers = [1, 2, 2, 3, 1, 4]
unique = list(dict.fromkeys(numbers))
print(unique) # [1, 2, 3, 4]This works because dictionary keys are unique and preserve insertion order.
3 bonus advanced Python interview questions
Experienced Python roles may include questions about concurrency, argument handling, and inheritance.
What is the GIL, and when should you use threading vs. multiprocessing?
The global interpreter lock (GIL) in traditional CPython builds generally allows only one thread at a time to execute Python bytecode within an interpreter.
Threading is useful for I/O-bound tasks, such as network requests. Multiprocessing is often better for CPU-bound tasks because it can use multiple processor cores.
Python 3.13 introduced experimental free-threaded CPython builds that can execute Python threads in parallel without the GIL. Free-threading became officially supported in Python 3.14, although it remains optional and requires attention to thread safety and library compatibility.
What do *args and **kwargs mean in Python?
*args collects extra positional arguments into a tuple.
**kwargs collects extra keyword arguments into a dictionary.
def describe(*args, **kwargs):
print(args)
print(kwargs)
describe(1, 2, language='Python')Output:
(1, 2)
{'language': 'Python'}The names args and kwargs are conventions; the * and ** syntax provides their behavior.
How do inheritance, MRO, and super() work in Python?
Inheritance allows a class to reuse and extend another class’s functionality. Python uses the method resolution order (MRO) to decide where to look for inherited methods.
The super() function follows the MRO to access the next implementation.
class A:
def hello(self):
return "A"
class B(A):
def hello(self):
return "B, " + super().hello()
class C(A):
def hello(self):
return "C, " + super().hello()
class D(B, C):
pass
print(D().hello()) # B, C, AYou can inspect the lookup order using D.__mro__.
How to prepare for Python interview questions
Knowing Python’s syntax is important, but interviewers also want to see how you solve problems.
Use these preparation tips:
- Review the fundamentals. Focus on data types, loops, functions, classes, and error handling.
- Practice writing code. Work through short exercises involving lists, dictionaries, strings, and files.
- Explain your solutions. Practice describing what your code does and why you chose a particular approach.
- Understand the trade-offs. Be ready to compare lists and tuples, generators and lists, or threading and multiprocessing.
- Prepare for the role. Data science positions may emphasize pandas and NumPy, while backend roles may focus on APIs, databases, and concurrency.
- Practice mock interviews. Work through coding questions while explaining your reasoning out loud. The following course on Udemy has over 600 Python interview questions and answers with code and detailed explanations.
Recommended Udemy course
FAQ
What are the top five Python interview questions?
Five useful topics to prioritize are:
- What’s the difference between a list and a tuple?
- What are Python decorators?
- How do generators work?
- What’s the difference between shallow and deep copies?
- What is the global interpreter lock (GIL)?
These topics test both fundamental knowledge and your understanding of Python’s behavior.
What Python concepts do interviewers focus on most?
Common topics include data structures, functions, loops, object-oriented programming, comprehensions, scope, exception handling, and practical coding exercises.
How do Python interview questions differ for junior and experienced developers?
Junior interviews generally focus on syntax, data types, and simple coding problems. Experienced roles may explore software design, performance, concurrency, testing, inheritance, and architectural trade-offs.
How long should you prepare for a Python interview?
If you already use Python regularly, two to four weeks of focused practice can provide a useful review. Beginners may need more time to develop coding fluency and problem-solving skills. The ideal preparation period depends on your experience and the role.
Are Python interview questions different for data science roles?
Yes. Data science interviews often include questions about NumPy, pandas, data cleaning, statistics, and data analysis. However, Python fundamentals remain important across technical roles.