Python Interview Questions
1: What are the different data types in Python? Ans: int, float, complex, bool, str, list, tuple, dict, set, bytes, bytearray, NoneType.
2: How does Python implement dynamic typing? Ans: Variables are not bound to types; objects carry type information. The type is checked at runtime.
3: What is casting in Python? Ans: Converting one data type into another using functions like int(), float(), str(), list(), etc.
4: What is slicing in Python? Ans: Extracting a portion of a sequence using syntax seq[start🔚step].
5: How are strings immutable in Python, and what does that mean? Ans: Once created, a string's value cannot change. Any modification creates a new string object.
6: How to check if a string contains only digits? Ans: Use the string method: s.isdigit().
7: What are mutable and immutable data types in Python? Ans: Mutable: list, dict, set, bytearray. Immutable: int, float, bool, str, tuple, frozenset, bytes.
8: What is the difference between is and == in Python? Ans: is checks identity (same object). == checks value equality.
9: How does Python handle memory management? Ans: Through automatic garbage collection, reference counting, and a private heap.
10: What is the difference between shallow copy and deep copy? Ans: Shallow copy copies only references. Deep copy recursively copies all nested objects.
11: What is the purpose of id() function in Python? Ans: Returns the memory identity (address-like unique identifier) of an object.
12: How does garbage collection work in Python? Ans: Through reference counting and a cyclic garbage collector to clean circular references.
13: What are the key differences between Python 2 and Python 3? Ans: Python 3 uses Unicode by default, print() is a function, improved division, better libraries, and Python 2 is deprecated.
14: How does Python's import system work? Ans: Searches modules in sys.path, loads bytecode, executes module, caches in sys.modules.
15: What are Python's built-in functions that you use frequently? Ans: print(), len(), type(), range(), input(), sum(), max(), min(), sorted().
16: How do you check the type of a variable in Python? Ans: Using type(variable) or isinstance(variable, type).
17: What is the difference between str and repr? Ans: str is user-friendly representation; repr is developer-focused and unambiguous.
18: How does Python's print() function work internally? Ans: Converts objects to string via str(), writes to sys.stdout.
19: What are Python's naming conventions (PEP 8)? Ans: snake_case for variables/functions, PascalCase for classes, UPPER_CASE for constants.
20: How do you document Python code properly? Ans: Using docstrings (""" """) and comments (#).
21: What is the purpose of if name == "main"? Ans: Ensures code runs only when executed directly, not when imported.
22: How does Python handle integer overflow? Ans: Uses arbitrary-precision integers; no overflow occurs.
23: What are Python's basic arithmetic operations? Ans: +, -, *, /, //, %, **.
24: How do you format strings in Python? Ans: Using f-strings, format(), or % formatting.
25: What are raw strings and when to use them? Ans: Prefix r"". They treat backslashes literally—useful for regex and file paths.
26: How does Python's boolean evaluation work? Ans: Non-zero numbers, non-empty containers → True. Zero, empty containers, None → False.
27: What is short-circuit evaluation in Python? Ans: In and/or expressions, evaluation stops once the result is known.
28: How do you work with complex numbers in Python? Ans: Using complex type: 3+5j; operations supported natively.
29: What are Python's identity operators? Ans: is and is not.
30: How does membership testing work with in operator? Ans: Checks if element exists in sequences, sets, dict keys.
31: What is the ternary operator in Python? Ans: result = a if condition else b.
32: How do you handle large numbers in Python? Ans: Python integers automatically expand in size (arbitrary precision).
33: What is the difference between / and // operators? Ans: / is floating-point division; // is floor (integer) division.
34: How does exponentiation work in Python? Ans: Using ** operator or pow().
35: What are bitwise operators in Python? Ans: &, |, ^, ~, <<, >>.
36: How do you convert between different number systems? Ans: bin(), oct(), hex(), int(value, base).
37: What is the purpose of sys.getsizeof()? Ans: Returns memory size (in bytes) occupied by an object.
38: How does Python's interpreter work? Ans: Parses code → compiles to bytecode → executes in CPython's virtual machine.
39: What are Python's key language features? Ans: Dynamic typing, interpreted, high-level, OOP + functional support, rich libraries.
40: How does Python compare to other programming languages? Ans: Easier syntax, slower execution, huge ecosystem, flexible, great for rapid development.
41: What is duck typing in Python? Ans: "If it looks like a duck and quacks like a duck, it's a duck." Type determined by behavior.
42: How does Python's dynamic nature affect performance? Ans: Slower execution due to runtime type checks and dynamic dispatch.
43: What are some built-in constants in Python? Ans: True, False, None, NotImplemented, Ellipsis.
44: How do you use help() and dir() functions? Ans: help(obj) shows documentation; dir(obj) lists attributes/methods.
45: What is the Pythonic way of writing code? Ans: Clean, readable, follows PEP 8, uses idioms, prefers simplicity.
46: How does Python handle floating point precision? Ans: Uses IEEE 754 double-precision; may produce rounding errors.
47: What are some common Python idioms? Ans: List comprehensions, unpacking, with statements, EAFP (easier to ask forgiveness).
48: How do you measure execution time in Python? Ans: Using time.time(), time.perf_counter(), or timeit module.
49: What is the purpose of sys.argv? Ans: Provides command-line arguments passed to the script.
50: How does Python’s interactive shell work? Ans: Reads input → evaluates → prints result (REPL loop).
51: What are the main differences between lists and tuples? Ans: Lists are mutable, slower, and use more memory; tuples are immutable, faster, and used for fixed data.
52: How do you remove duplicates from a list? Ans: Use list(set(my_list)) or use dict.fromkeys(my_list) to preserve order.
53: How can you reverse a list in Python? Ans: my_list.reverse() or my_list[::-1].
54: What are list comprehensions and when to use them? Ans: Compact syntax for creating lists. Use them for clean, readable transformations or filtering.
55: What is the difference between append() and extend() methods? Ans: append() adds one element; extend() adds multiple elements from an iterable.
56: How do you sort a list of dictionaries by a specific key? Ans: sorted(list, key=lambda x: x["key"]).
57: How can you merge two dictionaries in Python 3.9+? Ans: Use dict1 | dict2.
58: How do you access dictionary keys safely without raising an error? Ans: Use dict.get(key, default).
59: What is a set in Python and when would you use it? Ans: Unordered collection of unique elements; great for membership and duplicate removal.
60: How do you find the intersection and union of two sets? Ans: Intersection: a & b. Union: a | b.
61: How do you create a dictionary comprehension? Ans: {key: value for key, value in iterable}.
62: What is the difference between dict.keys(), dict.values(), and dict.items()? Ans: keys() → keys; values() → values; items() → key-value pairs.
63: How do you handle missing keys in dictionaries? Ans: Use get(), setdefault(), or try-except.
64: What are defaultdict and Counter from collections? Ans: defaultdict provides default values; Counter counts element frequency.
65: How do you use enumerate() with lists? Ans: enumerate(list) returns index-value pairs.
66: What is the difference between zip() and enumerate()? Ans: zip() pairs elements; enumerate() attaches indexes.
67: How do you flatten a nested list? Ans: [x for sub in nested for x in sub] or itertools.chain.
68: What are the performance characteristics of list operations? Ans: Index O(1), append O(1), insert/pop middle O(n), search O(n).
69: How do you find the most common elements in a list? Ans: collections.Counter(list).most_common().
70: What is the difference between remove(), pop(), and del? Ans: remove() deletes by value; pop() deletes by index; del deletes by index or slice.
71: How do you copy a list properly? Ans: list.copy(), slicing [:], or list().
72: What are namedtuples and when to use them? Ans: Lightweight immutable structures for readable, structured data.
73: How do you concatenate strings efficiently? Ans: Use join() or f-strings; avoid + in loops.
74: What are f-strings and how do they work? Ans: f"{var}" — evaluate expressions inside {}.
75: How do you split and join strings? Ans: split() → list; join() → string from list.
76: What are string methods you use frequently? Ans: strip(), replace(), split(), join(), lower(), upper(), find().
77: How do you handle multiline strings? Ans: Use triple quotes """...""" or implicit concatenation.
78: What is the difference between capitalize(), title(), and upper()? Ans: capitalize → first letter; title → each word; upper → all uppercase.
79: How do you check if a string starts/ends with a substring? Ans: startswith(), endswith().
80: What are regular expressions in Python? Ans: Patterns for matching/manipulating text using re.
81: How do you use re module for pattern matching? Ans: re.search(), re.match(), re.findall(), re.sub().
82: What are raw strings and why are they useful with regex? Ans: r"string" treats backslashes literally, reduces escape bugs.
83: How do you format numbers in strings? Ans: f"{num:.2f}" or format(num, ".2f").
84: What is the difference between sort() and sorted()? Ans: sort() modifies list; sorted() returns a new sorted list.
85: How do you implement a stack using lists? Ans: append() to push; pop() to pop.
86: How do you implement a queue using deque? Ans: Use collections.deque with append() and popleft().
87: What are the time complexities of common list operations? Ans: Append O(1); insert/delete middle O(n); lookup O(1).
88: How do you use bisect module for binary search? Ans: bisect_left(), bisect_right() to find insert positions in sorted lists.
89: What are dictionary views and how are they useful? Ans: keys(), values(), items() — dynamic, reflect changes in dict.
90: How do you invert a dictionary? Ans: {v: k for k, v in dict.items()}.
91: What are frozensets and when to use them? Ans: Immutable sets, usable as dictionary keys or set elements.
92: How do you compare two lists for equality? Ans: Use == which checks element-wise equality.
93: What is the difference between == and is for collections? Ans: == checks value; is checks identity.
94: How do you create a list of unique elements while preserving order? Ans: Use dict.fromkeys() or a seen-set loop.
95: What are some common string encoding issues? Ans: UnicodeDecodeError, UnicodeEncodeError, mixing bytes and str.
96: How do you handle Unicode strings properly? Ans: Use UTF-8 and avoid mixing bytes/str types.
97: What is the purpose of str.encode() and bytes.decode()? Ans: encode → str to bytes; decode → bytes to str.
98: How do you use collections.ChainMap? Ans: Combine multiple dicts for hierarchical lookup.
99: What are the advantages of tuples over lists? Ans: Faster, immutable, hashable, safer for constant data.
100: How do you use itertools for advanced iteration? Ans: chain(), combinations(), permutations(), product(), cycle(), etc.
Last updated