Prepare for technical interviews with questions by technology, clear explanations, step-by-step solutions and code you can run.
You can read Python code and roughly understand it even if you've never coded. That low barrier, plus libraries for almost everything (websites, data, automation, AI), is why students and big companies both use it.
Both, behind the scenes. Python translates your code into bytecode first, then a virtual machine runs it. You never see the translation step, which is why people call it interpreted.
A mutable object can be edited after it's created, like a shopping list you keep crossing things off. An immutable one is like a printed receipt: to "change" it, you have to print a new one. Lists, dicts and sets are mutable. Strings, numbers and tuples are not.
When the values are a fixed record that shouldn't be altered, like a (latitude, longitude) pair. Tuples can also be dictionary keys, and lists can't.
A dictionary connects keys to values, like a contact list. A set only remembers which items exist, and it ignores duplicates. Both check membership very quickly.
It's the style guide most Python developers follow: 4 spaces for indentation, snake_case for variables and functions, CamelCase for classes. It makes a team's code feel like it was written by one person.
They let a function accept a flexible number of inputs. *args collects extra positional values into a tuple, and **kwargs collects extra named values into a dictionary.
It's a function that wraps another function to add behavior, like a phone case adding protection without changing the phone. You attach it with @name above the function. Logging and timing are common uses.
It gives you one value at a time and pauses in between, so you never hold the full data set in memory. That matters when you're processing a huge file or an endless stream.
A shallow copy makes a new outer container, but inner objects are still shared with the original. A deep copy duplicates everything, so changes to one never leak into the other.
== compares values. is asks whether both names point to the very same object. Two separate lists holding [1, 2] are == but not is.
The Global Interpreter Lock in CPython lets only one thread run Python bytecode at any moment. Threads still help for waiting tasks like downloads, but for heavy calculations you'd use multiprocessing.
It's how Python looks up a name: Local scope first, then Enclosing functions, then Global, then Built-ins. The first match wins.
Encapsulation keeps data and behavior together. Inheritance lets one class reuse another. Polymorphism lets different classes answer the same method call in their own way. Abstraction hides complicated internals behind a simple interface.
__init__ runs as soon as an object is created and sets up its starting data. self is the object referring to itself, which is how each instance keeps its own values.
With multiple inheritance, Python needs a fixed order to search parent classes for a method. That order is the Method Resolution Order, and ClassName.mro() shows it.
try holds code that might fail, except handles the failure, else runs only if nothing went wrong, and finally always runs, which makes it the place for cleanup.
A module is a single .py file. A package is a folder that groups several modules under one name.
It's a one-line way to build a new list from another sequence, like [len(w) for w in words]. It's neat for simple cases, but switch to a regular loop if it gets hard to read.
An unnamed one-expression function, such as lambda x: x * 3. It's useful for quick jobs like the key argument of sorted().
Every object counts how many references point to it, and when that hits zero the memory is released. A garbage collector also handles reference cycles that counting alone can't clear.
It wraps a block of code with automatic setup and teardown, using with. Opening a file this way guarantees it gets closed, even if an error happens halfway through.
An iterable is something you can loop over, like a list. An iterator is the object that tracks your position and hands out the next item. Calling iter() on an iterable gives you one.
They give each project its own separate set of installed packages, so two projects that need different library versions don't fight each other.
Python cares about behavior, not the declared type. If an object has the methods your code calls, it works, whatever class it belongs to.
Iterate through adjacent character pairs using zip() and track contiguous character frequencies.
def compress(text):
if not text:
return ""
out = []
count = 1
for prev, cur in zip(text, text[1:]):
if cur == prev:
count += 1
else:
out.append(f"{prev}{count}")
count = 1
out.append(f"{text[-1]}{count}")
return "".join(out)
print(compress("aaabbc")) # a3b2c1
Use a stack data structure to match opening brackets with their corresponding closing brackets.
def balanced(s):
pairs = {")": "(", "]": "[", "}": "{"}
stack = []
for ch in s:
if ch in "([{":
stack.append(ch)
elif ch in pairs:
if not stack or stack.pop() != pairs[ch]:
return False
return not stack
print(balanced("{[()]}"), balanced("(]")) # True False
Compute the Greatest Common Divisor using Euclid's algorithm with modulo arithmetic.
def gcd(a, b):
while b:
a, b = b, a % b
return a
print(gcd(48, 18)) # 6
Use dictionary comprehension over a specified range of Celsius temperatures.
table = {c: c * 9 / 5 + 32 for c in range(0, 41, 10)}
print(table) # {0: 32.0, 10: 50.0, 20: 68.0, 30: 86.0, 40: 104.0}
Calculate the expected mathematical sum of numbers 1..n and subtract the actual array sum.
def missing(nums):
n = len(nums) + 1
return n * (n + 1) // 2 - sum(nums)
print(missing([1, 2, 4, 5, 6])) # 3
Use collections.Counter to tally character occurrences and extract the most common element.
from collections import Counter
print(Counter("banana").most_common(1)) # [('a', 3)]
Parse CSV text stream using csv.DictReader and compute the mean of numerical values.
import csv, io
data = "name,marks\nAsha,80\nDev,70\nIsha,90\n"
rows = csv.DictReader(io.StringIO(data))
marks = [int(r["marks"]) for r in rows]
print(sum(marks) / len(marks)) # 80.0
Convert lists to sets, compute their intersection using &, and sort the resulting elements.
a = [1, 2, 3, 4]
b = [3, 4, 5]
print(sorted(set(a) & set(b))) # [3, 4]
Filter out non-zero elements into a list and append a list of zero padding.
def zeros_last(nums):
return [n for n in nums if n != 0] + [0] * nums.count(0)
print(zeros_last([0, 1, 0, 3, 12])) # [1, 3, 12, 0, 0]
Shift alphabetical characters by k positions preserving original case.
def shift(text, k):
out = []
for ch in text:
if ch.isalpha():
base = ord("A") if ch.isupper() else ord("a")
out.append(chr((ord(ch) - base + k) % 26 + base))
else:
out.append(ch)
return "".join(out)
print(shift("Hello, World", 3)) # Khoor, Zruog
Reverse rows order and transpose using zip(*matrix[::-1]).
m = [[1, 2], [3, 4]]
rotated = [list(row) for row in zip(*m[::-1])]
print(rotated) # [[3, 1], [4, 2]]
Use pathlib.Path for clean file I/O operations without manual stream opening/closing.
from pathlib import Path
p = Path("todo.txt")
p.write_text("buy milk\ncall mom\n")
print(p.read_text().splitlines()) # ['buy milk', 'call mom']
Implement LIFO (Last In First Out) behavior using underlying list append and pop methods.
class Stack:
def __init__(self):
self._items = []
def push(self, x):
self._items.append(x)
def pop(self):
if not self._items:
raise IndexError("stack is empty")
return self._items.pop()
def __len__(self):
return len(self._items)
s = Stack()
s.push(1)
s.push(2)
print(s.pop(), len(s)) # 2 1
Cache function evaluation results inside a dictionary closure to optimize recursive calls.
def remember(func):
cache = {}
def wrapper(n):
if n not in cache:
cache[n] = func(n)
return cache[n]
return wrapper
@remember
def fib(n):
return n if n < 2 else fib(n - 1) + fib(n - 2)
print(fib(50)) # 12586269025
Use a generator function with yield to generate odd squares on demand with minimal memory footprint.
def odd_squares(limit):
for n in range(1, limit + 1, 2):
yield n * n
print(list(odd_squares(9))) # [1, 9, 25, 49, 81]
Use dictionary comprehension to swap key-value pairs.
d = {"a": 1, "b": 2}
print({v: k for k, v in d.items()}) # {1: 'a', 2: 'b'}
Pass a tuple key (len(w), w) to sorted() for multi-criteria sorting.
words = ["pear", "fig", "apple", "kiwi"]
print(sorted(words, key=lambda w: (len(w), w)))
# ['fig', 'kiwi', 'pear', 'apple']
Combine string length checks with generator expressions checking any() digits and uppercase letters.
def strong(pw):
return (len(pw) >= 8
and any(c.isdigit() for c in pw)
and any(c.isupper() for c in pw))
print(strong("Secret123"), strong("weak")) # True False
Count frequencies with Counter and return the first character whose count equals 1.
from collections import Counter
def first_unique(s):
counts = Counter(s)
for ch in s:
if counts[ch] == 1:
return ch
return None
print(first_unique("swiss")) # w
Catch ValueError and TypeError exceptions and return a fallback default value.
def to_int(text, default=0):
try:
return int(text)
except (ValueError, TypeError):
return default
print(to_int("42"), to_int("abc")) # 42 0
Repeatedly find minimum element from unsorted portion and swap it to current index.
def selection_sort(a):
for i in range(len(a)):
m = min(range(i, len(a)), key=a.__getitem__)
a[i], a[m] = a[m], a[i]
return a
print(selection_sort([29, 10, 14, 37, 13])) # [10, 13, 14, 29, 37]
Use regular expression regex re.findall(r"\w+", text) to extract alphanumeric word tokens.
import re
print(len(re.findall(r"\w+", "Hi, there! Hi."))) # 3
Construct consecutive rows by summing adjacent element pairs from preceding row.
def pascal(n):
row = [1]
for _ in range(n):
print(row)
row = [1] + [a + b for a, b in zip(row, row[1:])] + [1]
pascal(4)
# [1]
# [1, 1]
# [1, 2, 1]
# [1, 3, 3, 1]
Define clean data containers with type annotations using @dataclass decorator.
from dataclasses import dataclass
@dataclass
class Book:
title: str
pages: int
def is_long(self):
return self.pages > 300
b = Book("Dune", 612)
print(b, b.is_long()) # Book(title='Dune', pages=612) True
Use two pointers to compare elements from both sorted lists and assemble a merged sorted list in O(n + m) time.
def merge_sorted(a, b):
i = j = 0
out = []
while i < len(a) and j < len(b):
if a[i] <= b[j]:
out.append(a[i])
i += 1
else:
out.append(b[j])
j += 1
return out + a[i:] + b[j:]
print(merge_sorted([1, 4, 9], [2, 3, 10])) # [1, 2, 3, 4, 9, 10]
Try searching for keywords like "JWT", "Express", "useEffect", "PDO", "GIL", or "schema".
Connect with DigitalXNode expert interviewers for technical mock interviews, domain assessment, and enterprise job placement.