Python has soared in popularity and cemented its position as one of the most widely used programming languages in the tech industry. Known for its elegant syntax, readability, and versatility, Python has gained a vast community of developers and has become a go-to language for a wide range of applications, from web development and data analysis to machine learning and artificial intelligence.
As Python continues to dominate the programming landscape, it has become increasingly crucial for both hiring managers and Python developers to have a solid understanding of essential Python interview questions. These questions serve as a litmus test for assessing a candidate’s proficiency in Python programming and their ability to apply Python’s features effectively. By delving into Python interview questions, hiring managers can identify top talent, while developers can refine their skills and confidently demonstrate their abilities during job interviews.
In this article, we’ll guide you through a carefully curated collection of Python interview questions, unravel their solutions, and provide clear explanations and illustrative code snippets to help you tackle Python interviews with confidence.
What a Python Interview Looks Like
Python is a high-level, object-oriented programming language that was first introduced in 1991 by Dutch programmer Guido van Rossum. The language is well known — and loved — for its robust set of tools and libraries, which make it suitable for a wide range of applications and use cases. In addition, Python’s clean syntax and extensive community support have made it a preferred choice for both beginners and experienced developers.
A Python interview serves as an opportunity for hiring managers to assess a candidate’s Python programming skills, problem-solving abilities, and familiarity with Python’s ecosystem. While the specific format and structure may vary depending on the company and position, Python interviews typically consist of several components aimed at evaluating different aspects of a candidate’s capabilities. These can include:
- Technical screenings
- Coding challenges
- Whiteboarding exercises
- Take-home assignments
- Pair programming sessions
- Behavioral interviews
Given Python’s versatility as a programming language, Python interview questions can come up in the hiring process for a number of technical roles, including software engineers, data scientists, data analysts, and machine learning engineers — to name just a few.
#1. Reverse Words in a Sentence
This question focuses on reversing the order of words in a given sentence, demonstrating a developer’s proficiency with string manipulation, loops, conditionals, and other programming constructs.
Task: Write a Python function called reverse_words that takes a sentence as input and returns the sentence with the order of words reversed.
Input Format: The input will be a string representing the sentence.
- The sentence will contain only alphanumeric characters and spaces.
- There will be no leading or trailing spaces.
- The sentence will have at least one word.
Output Format: The output will be a string representing the sentence with the words reversed.
Sample Input: Python is awesome
Sample Output: awesome is Python
def reverse_words(sentence): words = sentence.split() reversed_sentence = ' '.join(reversed(words)) return reversed_sentence
- The reverse_words function starts by splitting the sentence into individual words using the split() method. This creates a list of words.
- Next, the function uses the reversed() function to reverse the order of the words in the list.
- The reversed words are then joined back together using the ‘ ‘.join() method, where the space character ‘ ‘ is used as the separator.
- Finally, the reversed sentence is returned.
#2. Maximum Subarray Sum
This question asks the developer to find the maximum sum of a subarray within a given array. Questions like this can be helpful for demonstrating a mastery of skills like analytical thinking optimization, algorithms, and array manipulation.
Task: Write a Python function called max_subarray_sum that takes an array of integers as input and returns the maximum sum of any contiguous subarray within the array.
Input Format: The input will be a list of integers.
- The length of the array will be at least 1.
- The array may contain both positive and negative integers.
Output Format: The output will be a single integer representing the maximum sum of a subarray.
Sample Input: [1, 2, 3, -2, 5]
Sample Output: 9
def max_subarray_sum(arr): max_sum = arr current_sum = arr for i in range(1, len(arr)): current_sum = max(arr[i], current_sum + arr[i]) max_sum = max(max_sum, current_sum) return max_sum
- The max_subarray_sum function utilizes Kadane’s algorithm to find the maximum sum of a subarray.
- It starts by initializing max_sum and current_sum to the first element of the array.
- Then, it iterates through the array, updating current_sum by either including the current element or starting a new subarray from the current element.
- At each iteration, max_sum is updated to store the maximum sum encountered so far.
- Finally, the function returns max_sum, which represents the maximum sum of any contiguous subarray within the given array.
#3. Merge Intervals
This question focuses on merging overlapping intervals within a given list, which gives recruiters insight into a developer’s ability to break down a complex problem, identify patterns, and design effective solutions, leveraging programming constructs like loops, conditionals, and list manipulation operations.
Task: Write a Python function called merge_intervals that takes a list of intervals as input and returns a new list of intervals where overlapping intervals are merged.
Input Format: The input will be a list of intervals, where each interval is represented by a list with two elements: the start and end points of the interval.
- The list of intervals will be non-empty.
- The start and end points of each interval will be integers.
Output Format: The output will be a list of merged intervals, where each interval is represented by a list with two elements: the start and end points of the merged interval.
Sample Input: [[1, 3], [2, 6], [8, 10], [15, 18]]
Sample Output: [[1, 6], [8, 10], [15, 18]]
def merge_intervals(intervals): intervals.sort(key=lambda x: x) merged =  for interval in intervals: if not merged or merged[-1] < interval: merged.append(interval) else: merged[-1] = max(merged[-1], interval) return merged
- The merge_intervals function sorts the intervals based on their start points.
- It initializes an empty list called merged to store the merged intervals.
- Then, it iterates through each interval in the sorted list.
- If the merged list is empty or the current interval does not overlap with the last merged interval, the current interval is appended to merged.
- If the current interval overlaps with the last merged interval, the end point of the last merged interval is updated to the maximum of the two end points.
- Finally, the function returns the `merged` list, which contains the merged intervals with no overlaps.
#4. Iterables and Iterators
The itertools module standardizes a core set of fast, memory efficient tools that are useful by themselves or in combination. Together, they form an iterator algebra making it possible to construct specialized tools succinctly and efficiently in pure Python.
To read more about the functions in this module, check out their documentation here.
You are given a list of N lowercase English letters. For a given integer K, you can select any K indices (assume 1-based indexing) with a uniform probability from the list.
Find the probability that at least one of the K indices selected will contain the letter: ‘a’.
Input Format: The input consists of three lines. The first line contains the integer N, denoting the length of the list. The next line consists of N space-separated lowercase English letters, denoting the elements of the list. The third and the last line of input contains the integer K, denoting the number of indices to be selected.
Output Format: Output a single line consisting of the probability that at least one of the K indices selected contains the letter: ‘a’.
Note: The answer must be correct up to 3 decimal places.
- 1 ≤ N ≤ 10
- 1 ≤ K ≤ N
All the letters in the list are lowercase English letters.
a a c d
Sample Output: 0.8333
All possible unordered tuples of length 2 comprising of indices from 1 to 4 are:
(1, 2) (1, 3) (1, 4) (2, 3) (2, 4) (3, 4)
Out of these 6 combinations, 5 of them contain either index 1 or index 2, which are the indices that contain the letter ‘a’.
Hence, the answer is ⅚.
#5. Time Delta
When users post an update on social media, such as a URL, image, status update, etc., other users in their network are able to view this new post on their news feed. Users can also see exactly when the post was published — i.e, how many hours, minutes, or seconds ago.
Since sometimes posts are published and viewed in different time zones, this can be confusing. You are given two timestamps of one such post that a user can see on his newsfeed in the following format:
Day dd Mon yyyy hh:mm:ss +xxxx
Here +xxxx represents the time zone. Your task is to print the absolute difference (in seconds) between them.
Input Format: The first line contains T, the number of test cases. Each test case contains 2 lines, representing time t₁ and time t₂.
Input contains only valid timestamps.
year ≤ 3000
Output Format: Print the absolute difference (t₁ – t₂) in seconds.
Sun 10 May 2015 13:54:36 -0700
Sun 10 May 2015 13:54:36 -0000
Sat 02 May 2015 19:54:36 +0530
Fri 01 May 2015 13:54:36 -0000
Explanation: In the first query, when we compare the time in UTC for both the time stamps, we see a difference of 7 hours, which is 7 x 3,600 seconds or 25,200 seconds.
Similarly, in the second query, the time difference is 5 hours and 30 minutes for time zone. Adjusting for that, we have a difference of 1 day and 30 minutes. Or 24 x 3600 + 30 x 60 ⇒ 88200.
#6. start() & end()
These expressions return the indices of the start and end of the substring matched by the group.
>>> import re
>>> m = re.search(r’\d+’,’1234′)
Task: You are given a string S. Find the indices of the start and end of string k in S.
Input Format: The first line contains the string S. The second line contains the string k.
0 < len(S) < 100
0 < len(k) < len(S)
Output Format: Print the tuple in this format: (start _index, end _index). If no match is found, print (-1, -1).
#7. Decorators 2 – Name Directory
Let’s use decorators to build a name directory. You are given some information about N people. Each person has a first name, last name, age, and sex. Print their names in a specific format sorted by their age in ascending order, i.e. the youngest person’s name should be printed first. For two people of the same age, print them in the order of their input.
For Henry Davids, the output should be:
Mr. Henry Davids
For Mary George, the output should be:
Ms. Mary George
Input Format: The first line contains the integer N, the number of people. N lines follow each containing the space separated values of the first name, last name, age, and sex, respectively.
Constraints: 1 ≤ N ≤ 10
Output Format: Output N names on separate lines in the format described above in ascending order of age.
Mike Thomson 20 M
Robert Bustle 32 M
Andria Bustle 30 F
Mr. Mike Thomson
Ms. Andria Bustle
Mr. Robert Bustle
Concept: For sorting a nested list based on some parameter, you can use the itemgetter library. You can read more about it here.
#8. Default Arguments
In this challenge, the task is to debug the existing code to successfully execute all provided test files. Python supports a useful concept of default argument values. For each keyword argument of a function, we can assign a default value which is going to be used as the value of said argument if the function is called without it. For example, consider the following increment function:
def increment_by(n, increment=1):
return n + increment
The functions works like this:
>>> increment_by(5, 2)
Debug the given function print_from_stream using the default value of one of its arguments.
The function has the following signature:
def print_from_stream(n, stream)
This function should print the first n values returned by get_next() method of stream object provided as an argument. Each of these values should be printed in a separate line.
Whenever the function is called without the stream argument, it should use an instance of EvenStream class defined in the code stubs below as the value of stream.
Your function will be tested on several cases by the locked template code.
Input Format: The input is read by the provided locked code template. In the first line, there is a single integer q denoting the number of queries. Each of the following q lines contains a stream_name followed by integer n, and it corresponds to a single test for your function.
- 1 ≤ q ≤ 100
- 1 ≤ n ≤ 10
Output Format: The output is produced by the provided and locked code template. For each of the queries (stream_name, n), if the stream_name is even then print_from_stream(n) is called. Otherwise, if the stream_name is odd, then print_from_stream(n, OddStream()) is called.
Explanation: There are 3 queries in the sample.
In the first query, the function print_from_stream(2, OddStream()) is executed, which leads to printing values 1 and 3 in separated lines as the first two non-negative odd numbers.
In the second query, the function print_from_stream(3) is executed, which leads to printing values 2, 4 and 6 in separated lines as the first three non-negative even numbers.
In the third query, the function print_from_stream(5, OddStream()) is executed, which leads to printing values 1, 3, 5, 7 and 9 in separated lines as the first five non-negative odd numbers.