HackerRank Python Certification Exam — Questions and Answers
Question 1: What is the value of the variable `z` after this code executes? `z = 10 + 4 * 2 ** 3 / 8 - 1`
- 13.0 (Correct answer)
- 5.0
- 14.0
- 27.0
Correct answer: 13.0
Python follows the PEMDAS/BODMAS order of operations. The exponentiation `2 ** 3` is calculated first (8). Then, multiplication and division are performed from left to right: `4 * 8` is 32, and `32 / 8` is 4.0. Finally, addition and subtraction are performed: `10 + 4.0` is 14.0, and `14.0 - 1` is 13.0.
Question 2: Which method is automatically called when an object is created from a class?
- __new__
- __create__
- __start__
- __init__ (Correct answer)
Correct answer: __init__
__init__ is the initializer method called automatically after object creation to set up instance attributes.
Question 3: What does this code print? ```python found = False for n in [4, 8, 15, 16]: if n > 10: found = True break print(found, n) ```
- True 16
- True 10
- False 16
- True 15 (Correct answer)
Correct answer: True 15
The first n > 10 is 15, which sets found=True and breaks, leaving n as 15.
Question 4: What is the result of `2 ** 3 ** 2` in Python?
- 512 (Correct answer)
- 8
- 36
- 64
Correct answer: 512
Exponentiation is right-associative, so this evaluates as `2 ** (3 ** 2)` = `2 ** 9` = `512`.
Question 5: What is the correct way to open a file for writing in Python?
- open('file.txt', 'x')
- open('file.txt', 'w') (Correct answer)
- open('file.txt', 'a')
- open('file.txt', 'r')
Correct answer: open('file.txt', 'w')
Mode `'w'` opens a file for writing, creating it if it doesn't exist and truncating it if it does.
Question 6: What does `namedtuple._fields` return for `Point = namedtuple('Point', 'x y')`?
- (0, 1)
- {'x': 0, 'y': 1}
- ['x', 'y']
- ('x', 'y') (Correct answer)
Correct answer: ('x', 'y')
`_fields` is a tuple of strings listing the field names of the named tuple.
Question 7: Which algorithm does Python's built-in `sort()` use?
- Timsort (Correct answer)
- Quicksort
- Mergesort
- Heapsort
Correct answer: Timsort
Python uses Timsort, a hybrid of merge sort and insertion sort, with O(n log n) worst case.
Question 8: 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: 3, 2: 3, 3: 1}) (Correct answer)
- Counter({1: 1, 2: 2, 3: 1})
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 9: What is the primary characteristic of a lambda function in Python?
- It can contain multiple expressions.
- It uses the 'def' keyword for creation.
- It is an anonymous function. (Correct answer)
- It must be assigned to a variable.
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 10: What does `help(module)` display in Python?
- A list of the module's dependencies
- The file path of the module
- The module's source code
- The module's documentation including docstrings of its contents (Correct answer)
Correct answer: The module's documentation including docstrings of its contents
`help()` uses the `pydoc` system to display a module's docstring and the docstrings of its functions, classes, and methods.
Question 11: What is the value of `abs(-7.5)`?
- 7
- -7.5
- 8
- 7.5 (Correct answer)
Correct answer: 7.5
`abs()` returns the absolute (non-negative) value of its argument, preserving the float type.
Question 12: Which exception is raised when dividing by zero in Python?
- ZeroDivisionError (Correct answer)
- OverflowError
- ArithmeticError
- ValueError
Correct answer: ZeroDivisionError
Python raises `ZeroDivisionError` specifically when the divisor is zero.
Question 13: What is the result of `list(map(lambda x: x.upper(), ['a', 'b', 'c']))`?
- ['ABC']
- ['A', 'B', 'C'] (Correct answer)
- ['A,B,C']
- ['a', 'b', 'c']
Correct answer: ['A', 'B', 'C']
map applies str.upper() via the lambda to each character, producing uppercase strings.
Question 14: What is the output of the following Python code snippet? ```python for i in range(5): if i == 3: continue print(i, end=' ') else: print('Loop finished', end='') ```
- 0 1 2
- 0 1 2 3 4 Loop finished
- 0 1 2 4
- 0 1 2 4 Loop finished (Correct answer)
Correct answer: 0 1 2 4 Loop finished
The `for` loop iterates from 0 to 4. The `continue` statement is triggered when `i` is 3, which skips the `print(i)` statement for that iteration and proceeds to the next one. The `else` block of a `for` loop executes only when the loop completes its iterations without being terminated by a `break` statement. Since no `break` occurs, 'Loop finished' is printed after the loop concludes.
Question 15: How do you convert the string `'42'` to an integer in Python?
- int('42') (Correct answer)
- parse('42')
- integer('42')
- str.to_int('42')
Correct answer: int('42')
The built-in `int()` function converts a numeric string to an integer.
Question 16: What makes the HackerRank Python Certification valuable in job applications?
- It demonstrates verified Python skills. (Correct answer)
- It guarantees a job at HackerRank.
- It ranks candidates as the best Python programmers worldwide.
- It is recognized as an official university qualification.
Correct answer: It demonstrates verified Python skills.
The HackerRank Python Certification is highly valued in job applications because it demonstrates verified Python skills. Employers recognize HackerRank as a credible platform for technical assessment, and a certification from them provides objective proof that a candidate possesses practical coding abilities. This helps candidates stand out by offering tangible evidence of their programming expertise.
Question 17: What does `type(lambda x: x)` return?
- <class 'lambda'>
- <class 'type'>
- <class 'builtin_function'>
- <class 'function'> (Correct answer)
Correct answer: <class 'function'>
A lambda expression creates an anonymous function object, so its type is 'function'.
Question 18: What does the built-in iter() function do when called on a list?
- Returns a copy of the list
- Returns a list_iterator object that supports __next__ (Correct answer)
- Raises TypeError because lists are not iterable
- Converts the list to a generator function
Correct answer: Returns a list_iterator object that supports __next__
iter(obj) calls obj.__iter__() and returns the resulting iterator. For a list, it returns a list_iterator object. The list itself is iterable, but not an iterator — calling next() on the list directly would fail.
Question 19: What is the result of `round(2.675, 2)` in Python 3?
- 2.67 (Correct answer)
- 2.6
- 2.7
- 2.68
Correct answer: 2.67
Due to floating-point representation, `2.675` is stored as slightly less than `2.675`, so `round()` returns `2.67`.
Question 20: What does the `*args` parameter allow in a Python function definition?
- Accepting a variable number of positional arguments as a tuple (Correct answer)
- Creating a list of return values
- Accepting only keyword arguments
- Limiting the function to exactly one argument
Correct answer: Accepting a variable number of positional arguments as a tuple
*args collects any number of positional arguments into a tuple, allowing the function to be called with varying numbers of arguments. Similarly, **kwargs collects keyword arguments into a dictionary.
Question 21: What is the Pythonic way to loop a fixed number of times without needing the loop variable?
- for i in range(n): ...
- for _ in range(n): ... (Correct answer)
- while n > 0: n -= 1
- 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 22: What is the output of `list(zip([1,2,3], ['a','b','c']))`?
- [(1,'a'), (2,'b'), (3,'c')] (Correct answer)
- {'1':'a','2':'b','3':'c'}
- [1,2,3,'a','b','c']
- [[1,'a'], [2,'b'], [3,'c']]
Correct answer: [(1,'a'), (2,'b'), (3,'c')]
zip pairs elements from each iterable at the same index into tuples.
Question 23: Which of the following scenarios is the most appropriate use case for a `for` loop with an `else` block in Python?
- Executing a block of code a fixed number of times.
- Creating an infinite loop that waits for user input.
- Iterating through a list to perform an action on every element.
- Searching for an item in a list and performing an action only if the item is not found. (Correct answer)
Correct answer: Searching for an item in a list and performing an action only if the item is not found.
The `else` block of a `for` loop is executed if and only if the loop completes its entire sequence of iterations without encountering a `break` statement. This makes it ideal for search operations. You can use the `for` loop to look for an item, `break` if it's found, and the `else` block will then only run if the entire list was searched and the item was not found.
Question 24: 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)
- Use `@positional` decorator
- Prefix parameter names with `_`
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 25: You are creating a data structure to hold the configuration settings for an application. These settings are defined once at startup and should never be changed during the program's execution to prevent accidental modification. Which of the following data structures is the most appropriate choice?
- A frozenset, because it is immutable.
- A dictionary, because it allows for named settings.
- A list, because it maintains the order of settings.
- A tuple, because it is immutable and ordered. (Correct answer)
Correct answer: A tuple, because it is immutable and ordered.
A tuple is the best choice because it is both immutable and ordered. Immutability prevents the settings from being changed after they are created, which is a key requirement. Its ordered nature ensures that the settings remain in a consistent sequence, which can be important for configuration.
Question 26: What does `3 << 2` evaluate to?
- 6
- 1
- 9
- 12 (Correct answer)
Correct answer: 12
Left shift by 2 multiplies by `2²`; `3 * 4 = 12`.
Question 27: Which keyword is used to inherit from a parent class in Python?
- The parent class is passed in parentheses (Correct answer)
- inherits
- implements
- extends
Correct answer: The parent class is passed in parentheses
Python uses class ChildClass(ParentClass): syntax — the parent class name is placed in parentheses after the child class name.
Question 28: 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
- Polymorphism (Correct answer)
- Composition
- Inheritance
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 29: What is the output of `pow(2, 10)`?
- 2048
- 1024 (Correct answer)
- 20
- 512
Correct answer: 1024
pow(2, 10) computes 2 raised to the power 10, which is 1024.
Question 30: Analyze the following nested loop. How many times will the `print('*')` statement be executed? ```python for i in range(3): for j in range(i + 1): print('*') ```
- 6 (Correct answer)
- 5
- 3
- 9
Correct answer: 6
The outer loop iterates with `i` taking values 0, 1, and 2. - When `i` is 0, the inner loop `range(1)` runs once (j=0). - When `i` is 1, the inner loop `range(2)` runs twice (j=0, 1). - When `i` is 2, the inner loop `range(3)` runs three times (j=0, 1, 2). The total number of executions for `print('*')` is 1 + 2 + 3 = 6.
Question 31: What does re.findall(r'\d+', 'abc123def456') return?
- ['123', '456'] (Correct answer)
- [123, 456]
- ['1', '2', '3', '4', '5', '6']
- '123'
Correct answer: ['123', '456']
\d+ matches one or more consecutive digits. re.findall returns a list of all non-overlapping matches as strings. The two digit sequences '123' and '456' are found, giving ['123', '456'].
Question 32: Which built-in function converts a string to an integer?
- str_to_int()
- int() (Correct answer)
- parse()
- integer()
Correct answer: int()
int() converts a string (or other numeric type) to an integer.
Question 33: Which module provides the `wraps` decorator used to preserve a wrapped function's metadata?
- operator
- itertools
- inspect
- functools (Correct answer)
Correct answer: functools
`functools.wraps` copies `__name__`, `__doc__`, and other attributes from the wrapped function to the wrapper.
Question 34: What is the time complexity of `collections.deque.appendleft()`?
- O(log n)
- O(1) (Correct answer)
- O(n)
- O(n log n)
Correct answer: O(1)
deque is implemented as a doubly-linked list, so appendleft() is O(1) unlike list.insert(0, x) which is O(n).
Question 35: Which except clause syntax lets you capture the exception instance as a variable named 'e'?
- except Exception: e
- except e = Exception:
- except Exception as e: (Correct answer)
- except(Exception) as e:
Correct answer: except Exception as e:
The `except ExceptionType as variable:` syntax binds the caught exception instance to the given variable name.
Question 36: What does `inspect.signature(func)` return?
- The number of arguments the function accepts
- The function's source code as a string
- A Signature object describing the function's parameters (Correct answer)
- The function's return type annotation
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 37: What will `'hello'[1:4]` evaluate to?
- 'hell'
- 'ello'
- 'hel'
- 'ell' (Correct answer)
Correct answer: 'ell'
Slicing `[1:4]` extracts characters at indices 1, 2, and 3, yielding `'ell'`.
Question 38: 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))) ```
- [4, 5]
- [1, 2, 3, 6, 7, 8] (Correct answer)
- [1, 2, 3]
- [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 39: What happens when you access a dictionary key that does not exist using `dict['key']`?
- Returns an empty string
- Returns None
- Raises IndexError
- Raises KeyError (Correct answer)
Correct answer: Raises KeyError
Accessing a missing key with bracket notation raises a `KeyError` exception.
Question 40: What will be the output of the following Python code snippet?
- Canis familiaris, Canis lupus
- Canis lupus, Canis lupus
- Canis familiaris, Canis familiaris (Correct answer)
- Canis lupus, Canis familiaris
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 41: 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 42: What is multiple inheritance in Python?
- An instance can belong to multiple classes simultaneously
- A method is defined multiple times in the same class
- A class derives from more than one parent class (Correct answer)
- 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 43: Which of the following statements about the `collections.deque` object in Python is true?
- It is immutable and cannot be changed after creation.
- It provides O(1) time complexity for append and pop operations from both ends. (Correct answer)
- It provides O(n) performance for appends and pops from both ends.
- It is optimized for fast random access to elements in the middle of the sequence.
Correct answer: It provides O(1) time complexity for append and pop operations from both ends.
`collections.deque` is a double-ended queue implemented as a doubly-linked list. This structure allows for highly efficient additions and removals from both the left and right sides (the 'ends' of the queue) with constant time complexity, O(1). In contrast, a standard list has O(n) complexity for appends and pops from the left.
Question 44: How do you define a class method (not an instance method) in Python?
- Use @classmethod decorator with 'cls' as first parameter (Correct answer)
- Use @classmethod decorator with 'self' as first parameter
- 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.
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
These practice questions were written with AI tools. They are not real exam questions. Exam facts are checked against the official sources listed below. Not reviewed by a subject-matter expert. Editorial policy
Sources & references
Exam facts on this page (fees, format, dates, passing scores) are checked against these official sources; the date is our last check. Editorial policy
- help.hackerrank.com — Test delivery, retake policy, score release · verified Oct 2026
- hackerrank.com — Exam format · verified Oct 2026