Essential Python Functions for Technical Interviews
String split() Method
The split() method breaks a string into a list based on a delimiter. When called without arguments, it splits on whitespace.
>>> phrase = "I love China"
>>> phrase.split()
['I', 'love', 'China']
>>> text = "I love China, and you, you"
>>> text.split(", ")
['I love China', 'and you', 'you']
>>> mixed = "I#love#China#andyou#you"
>>> mixed.split("#")
['I', 'love', 'China', 'andyou', 'you']
>>> mixed.split("#", 1)
['I', 'love#China#andyou#you']
The maxsplit parameter limits the number of splits performed.
>>> sentence = "with great power comes great responsibility"
>>> sentence.split(" ", 3)
['with', 'great', 'power', 'comes great responsibility']
String Reversal with Slice Notation
The slice syntax a[start:end:step] combined with step -1 reverses sequences.
>>> text = 'the sky is blue'
>>> list(text)[::-1]
['e', 'u', 'l', 'b', ' ', 's', 'i', ' ', 'y', 'k', 's', ' ', 'e', 'h', 't']
>>> text.split()[::-1]
['blue', 'is', 'sky', 'the']
>>> text[::-1]
'eulb si yks eht'
>>> chars = ['h', 'e', 'll', 'o']
>>> chars[::-1]
['o', 'll', 'e', 'h']
Note that s[::-1] is equivaletn to s[-1::-1].
Counting Element Frequencies with Counter
The Counter class from collections tallies occurrences of eelments in any iterable, returning a dictionary-like object.
from collections import Counter
data = [1, 1, 1, 6, 6, 6, 7, 8]
frequency = Counter(data)
for key, value in frequency.items():
print(key, value)
print(frequency)
# Output:
# 1 3
# 6 3
# 7 1
# 8 1
# Counter({1: 3, 6: 3, 7: 1, 8: 1})
The most_common(k) method returns the k most frequent elements:
from collections import Counter
data = [1, 1, 1, 6, 6, 6, 7, 8]
frequency = Counter(data)
top_items = frequency.most_common(2)
print(top_items) # [(1, 3), (6, 3)]
result = [item[0] for item in top_items]
print(result) # [1, 6]
Dictionary get() Method
Retrieve values safely from dictionaries using get() with optional default values.
config = {'Name': 'Runoob', 'Age': 27}
print(config.get('Age')) # 27
print(config.get('Sex')) # None
print(config.get('Salary', 0.0)) # 0.0
Syntax: dict.get(key[, default])
Stack Operations
Python lists support stack-like behavior:
stack.append(x)— push element onto topstack.pop()— remove and return top elementstack[-1]— access top element without removal
Matrix Transposition with zip()
The zip() function combines iterables element-wise. Using * unpacking enables matrix transpose.
>>> grid = [[3, 0, 8, 4], [2, 4, 5, 7], [9, 2, 6, 3], [0, 3, 1, 0]]
>>> list(zip(*grid))
[(3, 2, 9, 0), (0, 4, 2, 3), (8, 5, 6, 1), (4, 7, 3, 0)]
>>> list(zip(grid))
[([3, 0, 8, 4],), ([2, 4, 5, 7],), ([9, 2, 6, 3],), ([0, 3, 1, 0],)]
When dimensions differ, zip() uses the shortest length. For handling unequal lengths, use itertools.zip_longest().
Converting to Tuples
The tuple() constructor converts lists, ranges, and other iterables to immutable tuples.
a = [1, 2]
b = {"1": 2, "3": 3}
c = {1, 2, 3, 3}
d = range(2, 10, 2)
print(tuple(a)) # (1, 2)
print(tuple(b)) # ('1', '3')
print(tuple(c)) # (1, 2, 3)
print(tuple(d)) # (2, 4, 6, 8)
Tuples offer immutability advantages over lists when modification should be prevented.
Double-Ended Queue with collections.deque
The deque class provides O(1) operations at both ends, functioning as both stack and queue.
import collections
dq = collections.deque()
dq.append('a') # deque(['a'])
dq.appendleft('b') # deque(['b', 'a'])
dq.extend('c') # deque(['b', 'a', 'c'])
dq.extendleft('d') # deque(['d', 'b', 'a', 'c'])
dq.append(['e', 'f']) # deque(['d', 'b', 'a', 'c', ['e', 'f']])
dq.append(4) # deque(['d', 'b', 'a', 'c', ['e', 'f'], 4])
dq.extend(['g', 'h']) # deque(['d', 'b', 'a', 'c', ['e', 'f'], 4, 'g', 'h'])
Key methods:
pop()/popleft()— remove from right/leftcount()— total element countinsert(index, obj)— insert at positionrotate(n)— shift elements n positions right (negative for left)maxlen— maximum length attribute (None if unbounded)remove(x)— remove first occurrenceclear()— empty the deque
Enumerate Function
enumerate() generates index-value pairs for iterables, useful in for loops.
seasons = ['spring', 'summer', 'fall', 'winter']
print(list(enumerate(seasons)))
# [(0, 'spring'), (1, 'summer'), (2, 'fall'), (3, 'winter')]
for index, value in enumerate(seasons):
print(index, value)
# 0 spring
# 1 summer
# 2 fall
# 3 winter
Syntax: enumerate(sequence, start=0)
letters = 'abcdefg'
print(list(enumerate(letters)))
# [(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'), (4, 'e'), (5, 'f'), (6, 'g')]