Python Interview Questions and Answers: Memory Management, Lambda, List Operations, Exceptions, and More
This article presents a collection of common Python interview questions covering memory management mechanisms, lambda functions, tuple/list conversion, duplicate removal techniques, sorting tricks, object copying methods, exception handling, the pass statement, range usage, regex operations, match vs search differences, and random number generation, each accompanied by clear explanations and code examples.
1. How does Python manage memory? Python uses three mechanisms: (a) reference counting – every object has a count of references; the count increases when a new name is bound or the object is placed in a container and decreases when references are deleted or go out of scope. The built‑in sys.getrefcount() can inspect the count. (b) garbage collection – when an object's reference count drops to zero it is reclaimed, and a cyclic‑gc detector periodically breaks reference cycles that would otherwise leak memory. (c) memory pool (pymalloc) – small objects (<256 bytes) are allocated from private pools for speed, while larger objects use the system malloc .
2. What is a lambda function and its benefits? A lambda is an anonymous, inline function useful for short callbacks. Syntax: lambda arguments: expression . Example:
add = lambda x, y: x + y
print(add(2, 3)) # 53. Converting between tuple and list – simply use the built‑in tuple() and list() constructors; type() can check the result.
4. Removing duplicate elements from a list – three common methods:
Method 1: use a set and restore original order.
info = [1, 2, 4, 1, 5, 6, 5, 0, 9, 0, 7, 7]
result = list(set(info))
result.sort(key=info.index)
print(result)Method 2: use dict.fromkeys() to preserve order.
result = dict.fromkeys(info)
result_list = list(result.keys())
print(result_list)Method 3: list comprehension.
lst = []
[ lst.append(i) for i in info if i not in lst ]
print(lst)5. Sorting a list and processing from the last element – after list.sort() , iterate backwards with range(len(a)-2, -1, -1) and delete duplicates of the last element.
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. Copying objects – assignment creates a new reference; shallow copy duplicates the container but keeps references to inner objects (e.g., copy.copy() or slicing); deep copy recursively copies everything ( copy.deepcopy() ).
7. Using except – the try…except…else…finally block catches specific exceptions, executes the else block only when no exception occurs, and always runs finally for cleanup.
8. The pass statement does nothing and serves as a placeholder where syntactically a statement is required.
9. The range() function creates an immutable sequence of integers: range(start, stop[, step]) . Example parameters are explained.
10. Searching and replacing strings – use the re module’s sub() (or subn() ) function.
import re
p = re.compile('蓝色|白色|红色')
print(p.sub('彩色', '蓝色袜子和红色鞋子'))
print(p.sub('彩色', '蓝色袜子和红色鞋子', count=1))11. Difference between match() and search() – match() checks only at the start of the string, while search() scans the entire string for the first occurrence.
12. Generating random numbers – the random module provides random() , uniform(a,b) , randint(a,b) , randrange(a,b,step) , and choice(seq) for various random values.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
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.