Essential Python Functions for Technical Interviews
String Slicing with Step
Extracting characters at even indices from a string demonstrates Python's powerful slicing mechanism.
s = 'abcdef'
result = s[1::2] # Starting from index 1, step by 2
print(result) # Output: 'bdf'
Converting Sequences to Lists
The list() constructor transforms various sequence types into mutable lists.
# String to list of characters
text = 'hello'
char_list = list(text)
print(char_list) # ['h', 'e', 'l', 'l', 'o']
# Tuple to list
coordinates = ('x', 'y', 'z')
coord_list = list(coordinates)
print(coord_list) # ['x', 'y', 'z']
Increment Operations
Python lacks ++ and -- operators found in other languages. Use compound assignment instead.
counter = 5
counter += 1 # Equivalent to counter++
counter -= 1 # Equivalent to counter--
String Splitting
Divide strings into components using specified delimiters.
sentence = "data science machine learning"
words = sentence.split() # Default whitespace delimiter
print(words) # ['data', 'science', 'machine', 'learning']
path = "usr/bin/python/scripts"
directories = path.split('/', 2) # Limit splits to 2
print(directories) # ['usr', 'bin', 'python/scripts']
Reversing Sequences
The slice notation [::-1] efficiently reverses any sequence.
phrase = 'hello world'
reversed_chars = phrase[::-1]
print(reversed_chars) # dlrow olleh
word_list = phrase.split()
reversed_words = word_list[::-1]
print(reversed_words) # ['world', 'hello']
Frequency Counting with Counter
Track element occurrences using collections.Counter.
from collections import Counter
values = [1, 2, 2, 3, 3, 3, 4]
frequency = Counter(values)
print(frequency) # Counter({3: 3, 2: 2, 1: 1, 4: 1})
# Find most common elements
top_two = frequency.most_common(2)
print(top_two) # [(3, 3), (2, 2)]
Dictionary Value Retrieval
Safely access dictionary values with default fallbacks.
record = {'name': 'Alice', 'score': 95}
age = record.get('age', 0) # Returns 0 if 'age' missing
print(age) # 0
score = record.get('score') # Returns actual value
print(score) # 95
Stack Operations
Implement stack behavior using list methods.
stack = []
stack.append(10) # Push element
stack.append(20)
element = stack.pop() # Pop last element
print(element) # 20
top = stack[-1] # Peek at top element
print(top) # 10
Matrix Transposition with Zip
Transform rows to columns using unpacking with zip().
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
transposed = list(zip(*matrix))
print(transposed) # [(1, 4, 7), (2, 5, 8), (3, 6, 9)]
Creating Immutable Sequences
Convert mutable sequences to immutable tuples.
numbers = [1, 2, 3]
fixed_numbers = tuple(numbers)
print(fixed_numbers) # (1, 2, 3)
range_values = range(5, 15, 2)
tuple_range = tuple(range_values)
print(tuple_range) # (5, 7, 9, 11, 13)
Double-Ended Queues
Efficient insertion and deletino at both ends using collections.deque.
import collections
queue = collections.deque([2, 3])
queue.appendleft(1) # Add to left
queue.append(4) # Add to right
print(queue) # deque([1, 2, 3, 4])
first = queue.popleft() # Remove from left
last = queue.pop() # Remove from right
print(first, last) # 1 4
Indexed Iteration
Access both index and value during iteration with enumerate().
data = ['alpha', 'beta', 'gamma']
for index, value in enumerate(data):
print(f"{index}: {value}")
# Output:
# 0: alpha
# 1: beta
# 2: gamma