HackerRank Python Certification Exam — Questions and Answers
Question 1: What does `any(x > 5 for x in [1, 3, 7, 2])` return?
- 7
- True (Correct answer)
- [7]
- False
Correct answer: True
`any()` returns True if at least one element satisfies the condition — here 7 > 5 is True.
Question 2: What will the following code output? class Dog: def __init__(self, name): self.name = name d = Dog('Rex') print(d.name)
- Rex (Correct answer)
- None
- Dog
- self.name
Correct answer: Rex
d.name accesses the instance attribute 'name' set during __init__, which was given the value 'Rex'.
Question 3: Which of the following describes how HackerRank evaluates Python coding submissions for correctness?
- Manual code review by HackerRank engineers
- Automated test case execution against hidden test inputs (Correct answer)
- Peer review by other certified candidates
- Static analysis of code style only
Correct answer: Automated test case execution against hidden test inputs
Submissions are evaluated automatically by running the code against a set of hidden test cases.
Question 4: What does `inspect.signature(func)` return?
- The function's return type annotation
- A Signature object describing the function's parameters (Correct answer)
- The function's source code as a string
- The number of arguments the function accepts
Correct answer: A Signature object describing the function's parameters
`inspect.signature` returns a `Signature` object that contains information about a function's parameters and annotations.
Question 5: What is the difference between issubclass() and isinstance()?
- They are identical in behavior
- issubclass() checks object type; isinstance() checks class hierarchy
- issubclass() checks class-to-class relationship; isinstance() checks object-to-class relationship (Correct answer)
- issubclass() requires three arguments; isinstance() requires one
Correct answer: issubclass() checks class-to-class relationship; isinstance() checks object-to-class relationship
issubclass(Child, Parent) checks if a class inherits from another; isinstance(obj, Class) checks if an object is an instance of a class (or subclass).
Question 6: What will be the output of the following Python code snippet?
- Canis lupus, Canis lupus
- Canis familiaris, Canis lupus
- Canis lupus, Canis familiaris
- Canis familiaris, Canis familiaris (Correct answer)
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 7: What is the primary characteristic that distinguishes a lambda function from a standard function defined with `def`?
- A lambda function is restricted to a single expression and implicitly returns its result. (Correct answer)
- A lambda function can have default argument values, but a `def` function cannot.
- A lambda function must be assigned to a variable, whereas a `def` function is automatically named.
- A lambda function can be used as an argument to other functions, while a `def` function cannot.
Correct answer: A lambda function is restricted to a single expression and implicitly returns its result.
Lambda functions are syntactically restricted to a single expression. The value of this expression is what the function implicitly returns. In contrast, functions defined with `def` can contain multiple statements, including explicit `return` statements, loops, and assignments.
Question 8: What does `type(3.0)` return?
- <class 'decimal'>
- <class 'float'> (Correct answer)
- <class 'double'>
- <class 'int'>
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 9: What is the output of: ```python for i in range(5): if i == 3: break else: print('no break') print('end') ```
- no break
- no break end
- end (Correct answer)
- Error
Correct answer: end
The break at i==3 prevents the else clause from executing, so only 'end' is printed.
Question 10: What does the `*args` parameter in a Python function allow?
- Passing a variable number of positional arguments (Correct answer)
- Passing a variable number of keyword arguments
- Defining default argument values
- Unpacking a dictionary into function arguments
Correct answer: Passing a variable number of positional arguments
`*args` collects extra positional arguments into a tuple, allowing functions to accept any number of positional inputs.
Question 11: Which standard Python library module is most useful for solving combinatorics problems in HackerRank challenges?
- re
- json
- itertools (Correct answer)
- os
Correct answer: itertools
The itertools module provides functions like combinations(), permutations(), and product() that solve combinatorics problems efficiently.
Question 12: What is the output of `isinstance(True, int)`?
- None
- TypeError
- False
- True (Correct answer)
Correct answer: True
`bool` is a subclass of `int` in Python, so `isinstance(True, int)` returns `True`.
Question 13: What is the output of `bool([])` in Python?
- Error
- True
- False (Correct answer)
- None
Correct answer: False
An empty list is falsy in Python, so `bool([])` returns `False`.
Question 14: What happens when you access a missing key in a `collections.defaultdict(list)`?
- Creates an entry with value 0
- Raises KeyError
- Returns None
- Creates an entry with an empty list (Correct answer)
Correct answer: Creates an entry with an empty list
defaultdict calls its factory function (list) to create a default value for missing keys, inserting an empty list.
Question 15: Which of the following will raise a `TypeError` in Python?
- False * 0
- True + 1
- '5' + 3 (Correct answer)
- 5 + 3.0
Correct answer: '5' + 3
Python does not implicitly convert strings to numbers, so concatenating a string with an int raises a `TypeError`.
Question 16: What is the output of: `from collections import deque; d = deque([1,2,3], maxlen=3); d.append(4); print(list(d))`?
- [1, 2, 4]
- [2, 3, 4] (Correct answer)
- [1, 2, 3, 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 17: What is the result of `sorted([3, 1, 4, 1, 5], reverse=True)`?
- [5, 4, 3, 1, 1] (Correct answer)
- [3, 1, 4, 1, 5]
- [1, 1, 3, 4, 5]
- [5, 1, 4, 1, 3]
Correct answer: [5, 4, 3, 1, 1]
`sorted()` with `reverse=True` returns a new list sorted in descending order.
Question 18: What does `hash('hello')` return in Python?
- Always the same integer across all Python versions
- None
- 'hello'
- An integer that may vary between runs (Correct answer)
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 19: What does `Counter.subtract()` do differently from subtracting two Counters with `-`?
- subtract() removes zero/negative counts; - does not
- subtract() only works with lists, not strings
- They are identical in behavior
- subtract() allows negative counts; - removes non-positive counts (Correct answer)
Correct answer: subtract() allows negative counts; - removes non-positive counts
`subtract()` allows counts to go to zero or negative, while the `-` operator drops non-positive counts.
Question 20: What is the output of: class A: x = 10 a1 = A() A.x = 20 print(a1.x)
- 10
- None
- AttributeError
- 20 (Correct answer)
Correct answer: 20
a1.x resolves to the class attribute A.x because no instance attribute 'x' was set on a1; after A.x = 20, it reads 20.
Question 21: Which of the following correctly creates a package in Python?
- A `.pkg` file in the Python path
- A zip archive of Python files
- A directory containing a file named `__init__.py` (Correct answer)
- A directory with at least one `.py` file
Correct answer: A directory containing a file named `__init__.py`
A Python package is a directory that contains an `__init__.py` file, which marks it as a package to the interpreter.
Question 22: What does 'polymorphism' mean in the context of Python OOP?
- Different classes can define the same method name with different behavior (Correct answer)
- An object can change its class at runtime
- A class can only have one shape of data
- A function can accept only one type of argument
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 23: Given `d = defaultdict(list)`, what happens when you access `d['new_key']`?
- KeyError is raised
- None is returned
- 0 is returned
- An empty list is created and returned (Correct answer)
Correct answer: An empty list is created and returned
defaultdict calls the factory function (list) to create a default value when a missing key is accessed.
Question 24: What is a variable in programming?
- A type of function
- A programming language
- A named storage location for data that can change during program execution (Correct answer)
- A fixed constant
Correct answer: A named storage location for data that can change during program execution
Variables are named containers that store data values in memory, and their contents can be modified during program execution.
Question 25: Which collection type is best suited for implementing a thread-safe FIFO queue in Python?
- list
- tuple
- collections.deque (Correct answer)
- set
Correct answer: collections.deque
deque's append() and popleft() operations are atomic in CPython, making it safe for use as a FIFO queue in single-producer single-consumer scenarios.
Question 26: Which object-oriented principle allows different objects to respond to the same method call in their own unique ways, enabling flexible and reusable code?
- Encapsulation
- Composition
- Inheritance
- Polymorphism (Correct answer)
Correct answer: Polymorphism
Polymorphism, which means 'many forms', is the principle where objects of different classes can be treated as objects of a common superclass. It allows a single interface (like a method name) to be used for different types, with each type providing its own implementation.
Question 27: What happens when you use `pass` inside an `if` block?
- It raises a SyntaxError
- It does nothing and execution continues normally (Correct answer)
- It exits the current function
- It skips the current iteration of the loop
Correct answer: It does nothing and execution continues normally
pass is a null operation — it does nothing and allows the block to be syntactically complete.
Question 28: Which of the following creates an infinite loop?
- while 1 == 1: pass (Correct answer)
- for i in []: pass
- for i in range(0): pass
- while False: pass
Correct answer: while 1 == 1: pass
1 == 1 is always True, creating an infinite loop with no break condition.
Question 29: What is the primary characteristic of a lambda function in Python?
- It can contain multiple expressions.
- It uses the 'def' keyword for creation.
- It must be assigned to a variable.
- It is an anonymous function. (Correct answer)
Correct answer: It is an anonymous function.
Lambda functions in Python are small, anonymous functions defined with the `lambda` keyword. They are restricted to a single expression and do not require a name, which is why they are called anonymous.
Question 30: 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)
- (0, 4)
- (2, 4)
- (4, 0)
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 31: Which of the following correctly converts the string `'42'` to an integer?
- float('42')
- str(42)
- integer('42')
- int('42') (Correct answer)
Correct answer: int('42')
The built-in `int()` function converts a string representation of a whole number to an integer.
Question 32: When using `defaultdict(int)`, what is the default value assigned to a newly accessed missing key?
- None
- 0 (Correct answer)
- []
- ''
Correct answer: 0
int() called with no arguments returns 0, so defaultdict(int) initializes missing keys to 0.
Question 33: What is the result of `~5` in Python?
- 6
- -5
- -6 (Correct answer)
- 5
Correct answer: -6
The bitwise NOT `~n` returns `-(n + 1)` in Python due to two's complement representation; `~5 = -6`.
Question 34: What is the output of `list(filter(lambda x: x % 2 == 0, range(10)))`?
- [0, 1, 2, 3, 4]
- [2, 4, 6, 8, 10]
- [0, 2, 4, 6, 8] (Correct answer)
- [1, 3, 5, 7, 9]
Correct answer: [0, 2, 4, 6, 8]
filter keeps elements where the lambda returns True, selecting even numbers 0 through 8.
Question 35: What will `[x**2 for x in range(4) if x % 2 == 0]` produce?
- [0, 1, 4, 9]
- [0, 4] (Correct answer)
- [1, 9]
- [0, 4, 16]
Correct answer: [0, 4]
The filter keeps only even x (0 and 2), then squares them to give [0, 4].
Question 36: What is the output of: ```python for i in range(3): for j in range(3): if j == 1: break print(i, j) ```
- 0 2, 1 2, 2 2
- 0 1, 1 1, 2 1 (Correct answer)
- Error
- 0 0, 1 0, 2 0
Correct answer: 0 1, 1 1, 2 1
break exits the inner loop when j==1, so after each inner loop j is 1 when it breaks.
Question 37: You need to store a collection of unique, hashable items where the order of elements does not matter, and you need to perform fast membership testing (i.e., checking if an item is in the collection). Which data structure should you use?
- A `tuple`
- A `list`
- A `set` (Correct answer)
- A `dict`
Correct answer: A `set`
A `set` is the ideal data structure for this use case. Sets are unordered collections of unique elements. They are implemented using hash tables, which makes membership testing (e.g., `item in my_set`) a very fast operation, with an average time complexity of O(1).
Question 38: What is the result of `2 ** 3 ** 2` in Python?
- 8
- 36
- 512 (Correct answer)
- 64
Correct answer: 512
Exponentiation is right-associative, so this evaluates as `2 ** (3 ** 2)` = `2 ** 9` = `512`.
Question 39: What does `list(map(str, [1, 2, 3]))` return?
- ['1', '2', '3'] (Correct answer)
- ['1,2,3']
- ('1','2','3')
- [1, 2, 3]
Correct answer: ['1', '2', '3']
map applies str() to each integer, producing a list of string representations.
Question 40: What is a loop used for in programming?
- To store data
- To define variables
- To import libraries
- To repeat a block of code multiple times (Correct answer)
Correct answer: To repeat a block of code multiple times
Loops execute a block of code repeatedly until a condition is met, avoiding the need to write the same code multiple times.
Question 41: How does HackerRank display a candidate's certification on their public profile?
- As a numerical score without any badge
- As a PDF downloadable only by the candidate
- As a badge with a verifiable link accessible to recruiters (Correct answer)
- As a private record visible only to the candidate
Correct answer: As a badge with a verifiable link accessible to recruiters
Earned certifications appear as verifiable badges on the candidate's public HackerRank profile, shareable with recruiters.
Question 42: What is the result of `sum(1 for c in 'hello world' if c == 'l')`?
- 2
- 4
- 3 (Correct answer)
- 1
Correct answer: 3
'hello world' contains 'l' at indices 2, 3, and 9, so the generator yields 1 three times.
Question 43: What is the result of this nested conditional? ```python a, b = 3, 7 if a > b: print('A') elif a == b: print('B') elif a < b: print('C') else: print('D') ```
- D
- A
- C (Correct answer)
- B
Correct answer: C
3 < 7 is True, so the third elif branch executes and prints 'C'.
Question 44: 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)
- 10
- A TypeError because reduce is not a built-in function.
- [1, 2, 6, 24]
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.
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