HackerRank Python Certification Exam — Questions and Answers
Question 1: Which of the following creates a set in Python?
- []
- ()
- set() (Correct answer)
- {}
Correct answer: set()
`{}` creates an empty dict, so `set()` is the correct way to create an empty set.
Question 2: What does the 'self' parameter in an instance method refer to?
- A global variable
- The parent class
- The class itself
- The current instance of the class (Correct answer)
Correct answer: The current instance of the class
'self' refers to the current instance of the class, allowing access to instance attributes and methods.
Question 3: During the HackerRank Python certification, which of the following is permitted?
- Using the HackerRank built-in documentation panel (Correct answer)
- Consulting external websites
- Installing third-party Python packages
- Collaborating with another person
Correct answer: Using the HackerRank built-in documentation panel
Candidates may use HackerRank's built-in language reference, but external resources and collaboration are prohibited.
Question 4: What is the space complexity of a recursive Fibonacci function without memoization?
- O(2^n)
- O(log n)
- O(n) (Correct answer)
- O(1)
Correct answer: O(n)
The call stack depth reaches O(n) since each call adds one frame before returning.
Question 5: How do you define a class method (not an instance method) in Python?
- Use @classmethod decorator with 'self' as first parameter
- Use @classmethod decorator with 'cls' as first parameter (Correct answer)
- Define the method outside the class body
- Use @staticmethod decorator with 'cls' as first parameter
Correct answer: Use @classmethod decorator with 'cls' as first parameter
@classmethod receives the class as the first argument (conventionally named 'cls') and can access or modify class state.
Question 6: Which method removes and returns the last element of a list?
- pop() (Correct answer)
- delete()
- remove()
- discard()
Correct answer: pop()
`list.pop()` without arguments removes and returns the last element of the list.
Question 7: A developer needs to create a new list where each number from an original list is tripled. Which of the following is the most idiomatic use of a built-in function with a lambda to achieve this?
- reduce(lambda x: x * 3, original_list)
- list(filter(lambda x: x * 3, original_list))
- [x * 3 for x in original_list using lambda]
- list(map(lambda x: x * 3, original_list)) (Correct answer)
Correct answer: list(map(lambda x: x * 3, original_list))
The `map()` function applies a given function to each item of an iterable and returns an iterator of the results. The lambda `lambda x: x * 3` is the function that triples a number. `map()` applies this to every element, creating the desired transformed list. `filter()` is for selection, not transformation.
Question 8: How do you call a function stored in a variable `fn` with arguments unpacked from a list `args`?
- fn(*args) (Correct answer)
- fn.call(args)
- fn.apply(*args)
- fn[args]
Correct answer: fn(*args)
The `*` operator unpacks a list (or tuple) into positional arguments when calling a function.
Question 9: What will be the output of the following Python code snippet? ```python from functools import reduce items = result = reduce(lambda x, y: x * y, items) print(result) ```
- 24 (Correct answer)
- [1, 2, 6, 24]
- A TypeError because reduce is not a built-in function.
- 10
Correct answer: 24
The `reduce` function from the `functools` module applies a function of two arguments cumulatively to the items of an iterable. In this case, `lambda x, y: x * y` multiplies the elements. The process is: 1*2=2, then 2*3=6, then 6*4=24. The final accumulated value is 24.
Question 10: What does `type(3.0)` return?
- <class 'float'> (Correct answer)
- <class 'int'>
- <class 'decimal'>
- <class 'double'>
Correct answer: <class 'float'>
Any number written with a decimal point is treated as a `float` in Python, and `type()` returns the class object.
Question 11: What is the type of the result of dividing two integers with `/` in Python 3?
- complex
- float (Correct answer)
- int
- Fraction
Correct answer: float
In Python 3, the `/` operator always returns a `float` even when both operands are integers.
Question 12: What is the correct way to define a function that accepts positional-only arguments in Python 3.8+?
- Use `*` before the parameters
- Use `/` after the positional-only parameters (Correct answer)
- Prefix parameter names with `_`
- Use `@positional` decorator
Correct answer: Use `/` after the positional-only parameters
A `/` in the function signature marks all parameters before it as positional-only, preventing them from being passed as keyword arguments.
Question 13: What does `hash('hello')` return in Python?
- None
- An integer that may vary between runs (Correct answer)
- Always the same integer across all Python versions
- 'hello'
Correct answer: An integer that may vary between runs
hash() returns an integer, but Python randomizes string hashes by default, so the value may differ between runs.
Question 14: How does `collections.ChainMap` handle key lookups when the same key exists in multiple maps?
- Returns the value from the first map where the key is found (Correct answer)
- Returns the value from the last map
- Returns a list of all values
- Raises a DuplicateKeyError
Correct answer: Returns the value from the first map where the key is found
ChainMap searches through the maps in order and returns the first match found.
Question 15: Which exception is raised when dividing by zero in Python?
- ZeroDivisionError (Correct answer)
- ArithmeticError
- OverflowError
- ValueError
Correct answer: ZeroDivisionError
Python raises `ZeroDivisionError` specifically when the divisor is zero.
Question 16: What type does Python assign to the literal `1_000_000`?
- int (Correct answer)
- long
- str
- float
Correct answer: int
Python allows underscores as visual separators in numeric literals; `1_000_000` is simply the integer `1000000`.
Question 17: A HackerRank Python Basic problem asks you to implement a function. Which approach earns the highest score?
- A solution that passes all visible and hidden test cases within the time and memory limits (Correct answer)
- A solution that uses the fewest lines of code regardless of correctness
- A solution that passes all visible test cases but none of the hidden ones
- A solution that outputs partial results with explanatory comments
Correct answer: A solution that passes all visible and hidden test cases within the time and memory limits
Full credit requires passing all test cases—both visible samples and hidden edge cases—within resource constraints.
Question 18: What is the result of `5 & 3` in Python?
- 3
- 7
- 1 (Correct answer)
- 5
Correct answer: 1
Bitwise AND: `5` is `101` and `3` is `011`; AND gives `001` which equals `1`.
Question 19: What does ' hello '.strip() return?
- ' hello'
- 'hello' (Correct answer)
- 'hello '
- ' hello '
Correct answer: 'hello'
str.strip() removes leading and trailing whitespace (spaces, tabs, newlines) from both ends of the string, returning 'hello'.
Question 20: What will `[x**2 for x in range(4) if x % 2 == 0]` produce?
- [1, 9]
- [0, 4, 16]
- [0, 1, 4, 9]
- [0, 4] (Correct answer)
Correct answer: [0, 4]
The filter keeps only even x (0 and 2), then squares them to give [0, 4].
Question 21: What does __repr__ return compared to __str__?
- They return identical strings in all cases
- __repr__ returns a formatted display string; __str__ returns the raw memory address
- __repr__ is called by print(); __str__ is called by repr()
- __repr__ returns an unambiguous developer-oriented string; __str__ returns a user-friendly string (Correct answer)
Correct answer: __repr__ returns an unambiguous developer-oriented string; __str__ returns a user-friendly string
__repr__ should return an unambiguous string useful for debugging; __str__ should return a readable string for end users.
Question 22: What is an abstract class in Python, and how is it created?
- A class that can only be used inside another class; created with a nested class definition
- A class with no methods; created with class Empty: pass
- A class whose attributes are all class-level; created with @classmethod on every method
- A class that cannot be instantiated and may define abstract methods; created using abc.ABC (Correct answer)
Correct answer: A class that cannot be instantiated and may define abstract methods; created using abc.ABC
Abstract classes (from the abc module) cannot be instantiated directly and use @abstractmethod to enforce method implementation in subclasses.
Question 23: 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 24: 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 25: Which control flow statement immediately terminates the current function and optionally returns a value?
- return (Correct answer)
- pass
- break
- continue
Correct answer: return
return exits the current function, optionally passing a value back to the caller.
Question 26: Which statement about `while True:` loops is correct?
- They run indefinitely unless broken by a break or return (Correct answer)
- They are syntax errors in Python
- They automatically stop after 100 iterations
- They always run exactly once
Correct answer: They run indefinitely unless broken by a break or return
while True creates an infinite loop that only exits via break, return, or an exception.
Question 27: A developer is processing a large log file where each line contains a user's action. They need to count the occurrences of each unique action to identify the most common ones. Which Python collection is the most efficient and idiomatic for this task?
- A `collections.Counter` object. (Correct answer)
- A set to store the unique actions, then iterating through it to count them in the original file.
- A dictionary, manually incrementing counts for each action.
- A list of tuples, where each tuple stores an action and its count.
Correct answer: A `collections.Counter` object.
The `collections.Counter` is a specialized dictionary subclass designed specifically for counting hashable objects. It simplifies the process of tallying counts from an iterable, providing a more efficient and readable solution than manually implementing the logic with a standard dictionary.
Question 28: What is the result of: `Counter([1,1,2,3]) + Counter([1,2,2])`?
- Counter({1: 2, 2: 1, 3: 1})
- Counter({2: 2, 1: 1})
- Counter({1: 1, 2: 2, 3: 1})
- Counter({1: 3, 2: 3, 3: 1}) (Correct answer)
Correct answer: Counter({1: 3, 2: 3, 3: 1})
Counter addition combines counts for each element: 1 appears 2+1=3 times, 2 appears 1+2=3 times, 3 appears 1 time.
Question 29: Which of the following is NOT a valid Python integer literal?
- 0b1010
- 0o77
- 0xFF
- 0d255 (Correct answer)
Correct answer: 0d255
Python supports hex (`0x`), octal (`0o`), and binary (`0b`) literals, but there is no decimal prefix `0d`.
Question 30: In a Python class, what is the primary role of the special method `__init__`?
- To define the string representation of an object for end-users.
- To initialize the state of a newly created object with its starting attributes. (Correct answer)
- To destroy an object and free up memory when it is no longer in use.
- To create a new instance of the class before it is initialized.
Correct answer: To initialize the state of a newly created object with its starting attributes.
The `__init__` method is a special method, often called a constructor or initializer, that Python calls automatically when a new instance of a class is created. Its primary purpose is to set up the initial state of the object by assigning values to its instance attributes.
Question 31: What is the output? ```python def f(*args, **kwargs): return len(args), len(kwargs) print(f(1, 2, x=3, y=4)) ```
- (2, 2) (Correct answer)
- (2, 4)
- (4, 0)
- (0, 4)
Correct answer: (2, 2)
Positional arguments 1 and 2 go into `args` (length 2), and keyword arguments x and y go into `kwargs` (length 2).
Question 32: 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, 6, 7, 8] (Correct answer)
- [1, 2, 3]
- [4, 5]
- [1, 2, 3, 4, 5, 6, 7, 8]
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.
Question 33: What is the result of `2 ** 3 ** 2` in Python?
- 64
- 36
- 512 (Correct answer)
- 8
Correct answer: 512
Exponentiation is right-associative, so this evaluates as `2 ** (3 ** 2)` = `2 ** 9` = `512`.
Question 34: How does HackerRank verify the identity of candidates taking a Python certification exam?
- No identity verification is required
- Email confirmation only
- Video proctoring via webcam (Correct answer)
- Government ID upload before the exam
Correct answer: Video proctoring via webcam
HackerRank uses webcam-based video proctoring to verify candidate identity during the certification exam.
Question 35: What is the result of `3 ** 2` in Python?
- 9 (Correct answer)
- 8
- None
- 6
Correct answer: 9
The `**` operator is Python's exponentiation operator, so `3 ** 2` equals 9.
Question 36: What is the output of this code? ```python x = 5 result = 'positive' if x > 0 else 'negative' if x < 0 else 'zero' print(result) ```
- zero
- positive (Correct answer)
- Error
- negative
Correct answer: positive
The chained ternary evaluates left-to-right: x > 0 is True so result is 'positive'.
Question 37: What does `__name__ == '__main__'` check for in a Python module?
- Whether the module has a main() function
- Whether the module name is 'main'
- Whether the script is being run directly (not imported) (Correct answer)
- Whether the Python interpreter is in interactive mode
Correct answer: Whether the script is being run directly (not imported)
When a script is run directly, Python sets `__name__` to `'__main__'`; when imported, it's set to the module's name.
Question 38: What is the output of: ```python for char in 'abc': if char == 'b': continue print(char) ```
- b
- a c (Correct answer)
- a b
- a b c
Correct answer: a c
continue skips 'b', so only 'a' and 'c' are printed.
Question 39: What is the output of: ```python for x in range(1, 6, 2): print(x, end=' ') ```
- 1 3 5 7
- 2 4
- 1 2 3 4 5
- 1 3 5 (Correct answer)
Correct answer: 1 3 5
range(1, 6, 2) generates 1, 3, 5 (start=1, stop=6 exclusive, step=2).
Question 40: What does `Counter & Counter` (intersection) compute?
- Concatenation of both counters
- Symmetric difference of keys
- Union of all counts
- Minimum counts (keeps only shared elements with min count) (Correct answer)
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 41: Which built-in function returns the largest item in an iterable?
- peak()
- largest()
- max() (Correct answer)
- top()
Correct answer: max()
max() returns the largest item from an iterable or the largest of two or more arguments.
Question 42: What is the result of `max([1,2,3], key=lambda x: -x)`?
- -3
- 3
- -1
- 1 (Correct answer)
Correct answer: 1
key=lambda x: -x negates each value, so max finds the element with the least negative value, which is 1.
Question 43: What is the result of the following code? python words = ['py', 'thon', 'rocks'] print('-'.join(words))
- py thon rocks
- pythonn-rocks
- ['py', 'thon', 'rocks']
- py-thon-rocks (Correct answer)
Correct answer: py-thon-rocks
str.join(iterable) concatenates all items in the iterable using the string as the separator. '-'.join(['py','thon','rocks']) produces 'py-thon-rocks'.
Question 44: What is method overriding in Python?
- Defining multiple methods with the same name but different parameter counts
- Deleting a method from the parent class
- A child class provides its own implementation of a method inherited from the parent (Correct answer)
- Adding parameters to a method at runtime
Correct answer: A child class provides its own implementation of a method inherited from the parent
Method overriding lets a subclass redefine an inherited method, replacing the parent's behavior with its own.
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