HackerRank Python Certification Exam — Questions and Answers
Question 1: What is the Pythonic way to loop a fixed number of times without needing the loop variable?
- while n > 0: n -= 1
- for _ in range(n): ... (Correct answer)
- for i in range(n): ...
- for i in [0]*n: ...
Correct answer: for _ in range(n): ...
Using _ as the loop variable signals that the variable is intentionally unused, which is the Python convention.
Question 2: What is a mixin in Python OOP?
- A decorator that adds multiple methods to a class at once
- A method that mixes class and instance attributes
- A class that cannot be used as a standalone object and provides reusable methods via multiple inheritance (Correct answer)
- A special __init__ that accepts unlimited keyword arguments
Correct answer: A class that cannot be used as a standalone object and provides reusable methods via multiple inheritance
A mixin is a class designed to provide methods to other classes through multiple inheritance without being used as a standalone base class.
Question 3: What will `'hello'[1:4]` evaluate to?
- 'ello'
- 'hell'
- 'ell' (Correct answer)
- 'hel'
Correct answer: 'ell'
Slicing `[1:4]` extracts characters at indices 1, 2, and 3, yielding `'ell'`.
Question 4: What does 'polymorphism' mean in the context of Python OOP?
- A function can accept only one type of argument
- A class can only have one shape of data
- An object can change its class at runtime
- Different classes can define the same method name with different behavior (Correct answer)
Correct answer: Different classes can define the same method name with different behavior
Polymorphism allows different classes to implement the same interface (method name), with each class providing its own behavior.
Question 5: What is the difference between `import module` and `from module import *`?
- `import module` keeps names in the module's namespace; `from module import *` dumps all public names into the current namespace (Correct answer)
- They are identical in behavior
- `from module import *` is faster at runtime
- `from module import *` only imports classes, not functions
Correct answer: `import module` keeps names in the module's namespace; `from module import *` dumps all public names into the current namespace
`import module` requires `module.name` access, while `from module import *` pulls all public names directly into the current namespace, risking name collisions.
Question 6: What does `any([False, False, True, False])` return?
- True (Correct answer)
- False
- Error
- None
Correct answer: True
any() returns True if at least one element is truthy — here True is present in the list.
Question 7: A function is defined with some parameters having default values. Which rule must be followed regarding the order of these parameters in the function definition?
- Parameters with default values must be placed at the very end, after all non-default parameters. (Correct answer)
- All parameters must have default values if at least one does.
- The order does not matter; default and non-default parameters can be mixed.
- Parameters with default values must be placed at the beginning, before all non-default parameters.
Correct answer: Parameters with default values must be placed at the very end, after all non-default parameters.
In Python function definitions, all parameters with default values must come after all parameters that do not have default values. Attempting to place a non-default parameter after a default parameter will result in a `SyntaxError`.
Question 8: What is the output of `pow(2, 10)`?
- 1024 (Correct answer)
- 512
- 20
- 2048
Correct answer: 1024
pow(2, 10) computes 2 raised to the power 10, which is 1024.
Question 9: What is the output of `list(filter(lambda x: x % 2 == 0, range(10)))`?
- [0, 2, 4, 6, 8] (Correct answer)
- [2, 4, 6, 8, 10]
- [1, 3, 5, 7, 9]
- [0, 1, 2, 3, 4]
Correct answer: [0, 2, 4, 6, 8]
filter keeps elements where the lambda returns True, selecting even numbers 0 through 8.
Question 10: What will be the output of the following Python code snippet?
- Canis lupus, Canis lupus
- Canis lupus, Canis familiaris
- Canis familiaris, Canis familiaris (Correct answer)
- Canis familiaris, Canis lupus
Correct answer: Canis familiaris, Canis familiaris
The line `dog1.species = "Canis lupus"` creates a new *instance attribute* for `dog1` that shadows the class attribute. It does not change the `species` attribute of the `Dog` class itself. Therefore, `Dog.species` remains "Canis familiaris", and `dog2.species` also refers to the original class attribute.
Question 11: Which dunder method allows objects to be compared with == ?
- __compare__
- __is__
- __cmp__
- __eq__ (Correct answer)
Correct answer: __eq__
__eq__ is called when == is used; if not defined, Python defaults to identity comparison (same as 'is').
Question 12: What study resource does HackerRank itself recommend for candidates preparing for Python certification?
- Studying Java to understand OOP first
- Only reading the Python official docs
- Buying third-party courses exclusively
- Competing in HackerRank contests and solving the Python domain challenges (Correct answer)
Correct answer: Competing in HackerRank contests and solving the Python domain challenges
HackerRank's own Python domain and contests are the most aligned practice material since they use the same judge, format, and question style.
Question 13: What does `3 << 2` evaluate to?
- 1
- 9
- 6
- 12 (Correct answer)
Correct answer: 12
Left shift by 2 multiplies by `2²`; `3 * 4 = 12`.
Question 14: Which re function returns a match object only if the pattern matches at the BEGINNING of the string?
- re.findall()
- re.search()
- re.match() (Correct answer)
- re.fullmatch()
Correct answer: re.match()
re.match() anchors the pattern to the start of the string. re.search() scans the entire string for a match anywhere. re.fullmatch() requires the pattern to cover the entire string.
Question 15: What is the output of: `from collections import deque; d = deque([1,2,3], maxlen=3); d.append(4); print(list(d))`?
- [2, 3, 4] (Correct answer)
- [1, 2, 3, 4]
- [1, 2, 4]
- [4, 1, 2]
Correct answer: [2, 3, 4]
With maxlen=3, appending a 4th element discards the oldest element (1) from the left, leaving [2, 3, 4].
Question 16: What does the `*args` syntax in a function definition allow?
- Keyword-only arguments
- A fixed number of positional arguments
- Default argument values
- Any number of positional arguments (Correct answer)
Correct answer: Any number of positional arguments
`*args` collects any number of extra positional arguments into a tuple inside the function.
Question 17: What is the output of the following Python code snippet? x = 15 y = 4 result = x // y + (x % y) print(result)
- A TypeError occurs
- 6 (Correct answer)
- 3.75
- 7
Correct answer: 6
The floor division operator `//` calculates the quotient, discarding the remainder. `15 // 4` results in `3`. The modulo operator `%` calculates the remainder of the division. `15 % 4` results in `3`. The expression then becomes `3 + 3`, which equals `6`.
Question 18: What is the primary use case for `collections.ChainMap` compared to merging dicts with `{**d1, **d2}`?
- ChainMap allows duplicate keys
- ChainMap always produces a sorted result
- ChainMap is faster for large dicts
- ChainMap creates a live view that reflects changes to the underlying dicts (Correct answer)
Correct answer: ChainMap creates a live view that reflects changes to the underlying dicts
ChainMap holds references to the original dicts, so mutations to them are reflected in the ChainMap, unlike a merged copy.
Question 19: What does `Counter & Counter` (intersection) compute?
- Concatenation of both counters
- Minimum counts (keeps only shared elements with min count) (Correct answer)
- Symmetric difference of keys
- Union of all counts
Correct answer: Minimum counts (keeps only shared elements with min count)
Counter intersection keeps elements present in both counters, taking the minimum count for each.
Question 20: When using `defaultdict(int)`, what is the default value assigned to a newly accessed missing key?
- []
- 0 (Correct answer)
- ''
- None
Correct answer: 0
int() called with no arguments returns 0, so defaultdict(int) initializes missing keys to 0.
Question 21: A product manager wants to learn Python to collaborate better with engineering teams. How does a HackerRank certification benefit this non-engineering career path?
- It qualifies them to replace software engineers
- It signals technical literacy to leadership and enables more credible participation in engineering discussions and planning (Correct answer)
- It is irrelevant for non-engineering roles
- It provides a direct path to a data science title
Correct answer: It signals technical literacy to leadership and enables more credible participation in engineering discussions and planning
Technical certifications for non-engineers demonstrate cross-functional capability and improve credibility with engineering stakeholders and leadership.
Question 22: What is the value of `0.1 + 0.2 == 0.3` in Python?
- True
- False (Correct answer)
- None
- TypeError
Correct answer: False
Floating-point arithmetic is inexact; `0.1 + 0.2` evaluates to `0.30000000000000004`, not exactly `0.3`.
Question 23: What is multiple inheritance in Python?
- An instance can belong to multiple classes simultaneously
- A class derives from more than one parent class (Correct answer)
- A method is defined multiple times in the same class
- A class can have multiple __init__ methods
Correct answer: A class derives from more than one parent class
Python supports multiple inheritance with class Child(Parent1, Parent2):, and uses the MRO to resolve method lookups.
Question 24: What does `any([False, False, True, False])` return?
- 1
- False
- None
- True (Correct answer)
Correct answer: True
any() returns True if at least one element in the iterable is truthy.
Question 25: A developer wants to add logging functionality to several functions without modifying their original code. This logging should occur every time the function is called. Which Python feature is most suitable for this scenario?
- Lambda Functions
- Decorators (Correct answer)
- Conditional Statements
- List Comprehensions
Correct answer: Decorators
Decorators are designed to modify or enhance the behavior of functions or methods without permanently changing their source code. A decorator can wrap a function, allowing you to execute code before and after the wrapped function runs, which is ideal for tasks like logging, timing, or access control.
Question 26: What is the output of `divmod(17, 5)`?
- (3, 5)
- (3.4, 2)
- (3, 2) (Correct answer)
- (2, 3)
Correct answer: (3, 2)
`divmod(a, b)` returns a tuple `(a // b, a % b)`; for `17` and `5` that is `(3, 2)`.
Question 27: Which decorator marks a function to be called with no arguments and caches its result after the first call?
- @staticmethod
- @property
- @functools.lru_cache (Correct answer)
- @classmethod
Correct answer: @functools.lru_cache
`@functools.lru_cache` memoizes function results based on arguments, returning cached values on subsequent identical calls.
Question 28: Which of the following creates an infinite loop?
- for i in range(0): pass
- while False: pass
- while 1 == 1: pass (Correct answer)
- for i in []: pass
Correct answer: while 1 == 1: pass
1 == 1 is always True, creating an infinite loop with no break condition.
Question 29: A developer needs to ensure a function is only called if a list is not empty to avoid an `IndexError`. Which code snippet uses short-circuiting to achieve this safely? `my_list = []` `def process_list(data): print(data[0])`
- `if not my_list and process_list(my_list): pass`
- `if len(my_list) > 0 or process_list(my_list): pass`
- `if process_list(my_list) and my_list: pass`
- `if my_list and process_list(my_list): pass` (Correct answer)
Correct answer: `if my_list and process_list(my_list): pass`
The `and` operator in Python uses short-circuit evaluation. It evaluates the expression from left to right. If the first operand (`my_list`) is falsy (an empty list is falsy), it stops and does not evaluate the second operand (`process_list(my_list)`), thus preventing the `IndexError`. The other options would either still call the function or use incorrect logic.
Question 30: What is the output of `list(map(lambda x: x*2, [1, 2, 3]))`?
- [1, 4, 9]
- [1, 2, 3]
- [2, 3, 4]
- [2, 4, 6] (Correct answer)
Correct answer: [2, 4, 6]
`map` applies the lambda to each element, doubling 1, 2, 3 to produce [2, 4, 6].
Question 31: What is the output of the following code? ```python def f(x, y=10): return x + y print(f(5)) ```
- 10
- 15 (Correct answer)
- 5
- Error
Correct answer: 15
Since `y` defaults to 10 and only `x=5` is passed, the function returns 5 + 10 = 15.
Question 32: What is the output of this code? ```python x = 0 while x < 5: x += 1 if x == 3: continue print(x) ```
- 1 2 3 4
- 1 2 3 4 5
- 1 2 4 5 (Correct answer)
- 0 1 2 4 5
Correct answer: 1 2 4 5
continue skips the print when x == 3, so 3 is not printed but all other values 1-5 are.
Question 33: Which function returns the number of bits required to represent an integer in binary?
- int.bit_count()
- int.bit_length() (Correct answer)
- sys.getsizeof()
- bin()
Correct answer: int.bit_length()
`int.bit_length()` returns the number of bits needed, excluding the sign and leading zeros.
Question 34: Which of the following correctly uses `all()` to check that every number in a list is positive?
- all(x > 0 for x in nums) (Correct answer)
- all([x for x in nums if x > 0])
- sum(x > 0 for x in nums) > 0
- any(x > 0 for x in nums)
Correct answer: all(x > 0 for x in nums)
all() with a generator expression returns True only if every element satisfies the condition.
Question 35: How do you add a new child scope to an existing `ChainMap` for temporary overrides?
- chainmap.prepend(new_dict)
- chainmap.push(new_dict)
- ChainMap(new_dict, chainmap)
- chainmap.new_child(new_dict) (Correct answer)
Correct answer: chainmap.new_child(new_dict)
`new_child(m)` creates a new ChainMap with m as the first map, making it the highest-priority scope.
Question 36: At what levels is the HackerRank Python Certification offered?
- Intermediate and Advanced only.
- Advanced only.
- Beginner and Intermediate only.
- Basic, Intermediate, and Advanced. (Correct answer)
Correct answer: Basic, Intermediate, and Advanced.
The HackerRank Python Certification is structured to accommodate various levels of expertise. It is offered at Basic, Intermediate, and Advanced levels, allowing individuals to certify their Python programming skills as they progress. This tiered approach ensures that the certification accurately reflects a developer's current proficiency.
Question 37: What will the following code output? class Dog: def __init__(self, name): self.name = name d = Dog('Rex') print(d.name)
- Rex (Correct answer)
- self.name
- Dog
- None
Correct answer: Rex
d.name accesses the instance attribute 'name' set during __init__, which was given the value 'Rex'.
Question 38: What is the difference between these two expressions? A: [x**2 for x in range(1000)] B: (x**2 for x in range(1000))
- A is a tuple comprehension; B is a generator
- A builds the full list in memory; B is a lazy generator that yields one value at a time (Correct answer)
- They are identical in behavior and memory use
- Both build lists but B is faster
Correct answer: A builds the full list in memory; B is a lazy generator that yields one value at a time
Square brackets produce a list comprehension, computing and storing all 1000 values immediately. Parentheses produce a generator expression, computing each value on demand without storing the whole sequence.
Question 39: What is the result of `list(map(lambda x: x.upper(), ['a', 'b', 'c']))`?
- ['A,B,C']
- ['ABC']
- ['a', 'b', 'c']
- ['A', 'B', 'C'] (Correct answer)
Correct answer: ['A', 'B', 'C']
map applies str.upper() via the lambda to each character, producing uppercase strings.
Question 40: What is the difference between `append()` and `extend()` on a list?
- `append()` creates a copy while `extend()` modifies in place
- They are identical
- `extend()` adds one element; `append()` adds each element
- `append()` adds one element; `extend()` adds each element of an iterable (Correct answer)
Correct answer: `append()` adds one element; `extend()` adds each element of an iterable
`append()` inserts its argument as a single element; `extend()` iterates over the argument and adds each item.
Question 41: What is the correct way to raise a custom exception with a message in Python?
- raise Exception('msg') (Correct answer)
- raise Exception.new('msg')
- throw Exception('msg')
- error Exception('msg')
Correct answer: raise Exception('msg')
In Python, you use `raise ExceptionClass(args)` to raise an exception with a message.
Question 42: What does `list(map(lambda x: x ** 2, [1, 2, 3, 4]))` return?
- [1, 4, 9, 16] (Correct answer)
- [1, 8, 27, 64]
- [2, 4, 6, 8]
- [1, 2, 3, 4]
Correct answer: [1, 4, 9, 16]
map applies the lambda squaring function to each element, producing [1, 4, 9, 16].
Question 43: Which of these is an immutable data type in Python?
- list
- tuple (Correct answer)
- dict
- set
Correct answer: tuple
Tuples are immutable; their elements cannot be changed after creation.
Question 44: What is the output of the following Python code snippet? ```python set_a = {1, 2, 3, 4, 5} set_b = {4, 5, 6, 7, 8} result = set_a.symmetric_difference(set_b) print(sorted(list(result))) ```
- [1, 2, 3, 4, 5, 6, 7, 8]
- [1, 2, 3]
- [4, 5]
- [1, 2, 3, 6, 7, 8] (Correct answer)
Correct answer: [1, 2, 3, 6, 7, 8]
The `symmetric_difference()` method returns a new set containing elements that are in either `set_a` or `set_b`, but not in both. The elements {1, 2, 3} are unique to `set_a`, and {6, 7, 8} are unique to `set_b`. The combination of these is {1, 2, 3, 6, 7, 8}. The code then converts this set to a list and sorts it.
HackerRank Python Certification Exam
The HackerRank Python Certification Exam tests Python programming proficiency across scalar types, control flow, collections, functions, object-oriented programming, built-in functions, data structures and algorithms, and Python basics.
Exam Rules
- You can skip questions and return to them later
- Flag questions for review before submitting
- No feedback shown until you submit the entire exam
- Unanswered questions count as wrong — answer everything
- 10 pretest questions are mixed in and don't affect your score
- Timer auto-submits when time runs out
- Your progress is auto-saved every 30 seconds