Top Python Interview Questions and Expert Answers Explained
This article compiles over ten essential Python interview questions covering memory management, lambda functions, data structure conversions, duplicate removal, sorting techniques, object copying, exception handling, pass statements, range usage, regex operations, random number generation, static analysis tools, global variables, and string quoting conventions.
1. How does Python manage memory?
Answer: It uses three mechanisms—reference counting, garbage collection, and a memory pool.
Reference Counting
Every object has a reference count. The count increases when a new name is bound to the object or when it is placed in a container (list, tuple, dict). It decreases when del is used, when the reference goes out of scope, or when reassigned. sys.getrefcount() returns the current count. Immutable objects like numbers and strings are often shared to save memory.
Garbage Collection
When an object's reference count drops to zero, it is reclaimed. For reference cycles, Python periodically runs a cyclic detector to break and collect unreachable objects.
Memory Pool (pymalloc)
Python keeps freed memory in its own pools instead of returning it to the OS. Objects smaller than 256 bytes use the pymalloc allocator; larger objects use the system malloc. Separate private pools exist for integers, floats, and lists, so memory freed by one type cannot be reused by another.
2. What is a lambda function and its benefits?
Answer: A lambda expression creates an anonymous (unnamed) function, useful for short callbacks.
Syntax: lambda [arguments]: expression Example:
a = lambda x, y: x + y a(3, 11)3. How to convert between tuple and list in Python?
Answer: Use the built‑in tuple() and list() functions; type() can check the object type.
4. Code to remove duplicate elements from a list
Answer:
Method 1: set(my_list) Method 2 using a dictionary:
a = [1,2,4,2,4,5,6,5,7,8,9,0]
b = {}
b = b.fromkeys(a)
c = list(b.keys())
print(c)5. Sort a list and remove consecutive duplicates from the end
a = [1,2,4,2,4,5,7,10,5,5,7,8,9,0,3]
a.sort()
last = a[-1]
for i in range(len(a)-2, -1, -1):
if last == a[i]:
del a[i]
else:
last = a[i]
print(a)6. How to copy objects in Python (assignment, shallow copy, deep copy)?
Assignment ( =) creates a new reference; changes affect both names.
Shallow copy creates a new container but references the original items. Methods: slicing, list(), copy.copy().
Deep copy recursively copies all nested objects, so modifications are independent. Use copy.deepcopy().
7. Usage and purpose of except
Syntax: try … except … [else …] [finally …]. If an exception occurs in the try block, control jumps to the matching except. The else runs if no exception, and finally always runs.
8. What does the pass statement do?
It does nothing; it serves as a placeholder in empty code blocks.
9. How to use the range() function?
It generates a sequence of numbers, commonly used in for i in range(...) loops.
10. How to search and replace text using Python?
Use the re module’s sub() or subn() functions.
import re
p = re.compile('blue|white|red')
print(p.sub('colour', 'blue socks and red shoes'))
print(p.sub('colour', 'blue socks and red shoes', count=1))
print(p.subn('colour', 'blue socks and red shoes'))11. Difference between match() and search() in re
re.match()checks only at the start of the string; re.search() scans the whole string for the first occurrence.
print(re.match('super', 'superstition').span()) # (0, 5)
print(re.match('super', 'insuperable')) # None
print(re.search('super', 'superstition').span()) # (0, 5)
print(re.search('super', 'insuperable').span()) # (2, 7)12. Greedy vs. non‑greedy matching with <.*> and <.*?>
<.*>is greedy (matches the longest possible string); <.*?> is non‑greedy (matches the shortest).
13. Generating random numbers in Python
Use the random module:
Integers: random.randint(a, b) Range: random.randrange(start, stop, step) Floats: random.random() (0‑1) or
random.uniform(a, b)14. Tools for static code analysis and bug detection
PyChecker and Pylint can analyze code for bugs, complexity, and style.
15. Setting a global variable inside a function
def f():
global x
x = 1016. Differences among single, double, and triple quotes
Single and double quotes are equivalent; use a backslash to escape characters. Triple quotes allow multi‑line strings and can contain both single and double quotes without escaping.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
