How do i prepare for a python interview in one day?
Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Python Coding Interviews: Tips & Best Practices Show
You’ve made it past the phone call with the recruiter, and now it’s time to show that you know how to solve problems with actual code. Whether it’s a HackerRank exercise, a take-home assignment, or an onsite whiteboard interview, this is your moment to prove your coding interview skills. But interviews aren’t just about solving problems: they’re also about showing that you can write clean production code. This means that you have a deep knowledge of Python’s built-in functionality and libraries. This knowledge shows companies that you can move quickly and won’t duplicate functionality that comes with the language just because you don’t know it exists. At Real Python, we’ve put our heads together and discussed what tools we’re always impressed to see in coding interviews. This article will walk you through the best of that functionality, starting with Python built-ins, then Python’s native support for data structures, and finally Python’s powerful (and often underappreciated) standard library. In this article, you’ll learn how to:
Select the Right Built-In Function for the JobPython has a large standard library but only a small library of built-in functions, which are always available and don’t need to be imported. It’s worth going through each one, but until you get the chance to do so, here are a few built-in functions worth understanding how to use, and in the case of some of them, what alternatives to use instead. Iterate With enumerate() Instead of range()This scenario might come up more than any other in coding interviews: you have a list of elements, and you need to iterate over the list with access to both the indices and the values. There’s a classic coding interview question named FizzBuzz that can be solved by iterating over both indices and values. In FizzBuzz, you are given a list of integers. Your task is to do the following:
Often, developers will solve this problem with >>>
Range allows you to access the
elements of >>>
For each element, >>>
By using the Use List Comprehensions Instead of map() and filter()
He may have been wrong about it being uncontroversial, but Guido had
good reasons for wanting to remove Let’s first take a look at how we’d structure
a call to >>>
Both approaches, using Now we can do the same thing for the >>>
Like we saw with
Developers who come from other languages may disagree that list comprehensions are easier to read than Either way, you’ll rarely go wrong using list comprehensions in a coding interview, as it will communicate that you know what’s most common in Python. Debug With breakpoint() Instead of print()You may have debugged a small problem by adding Instead, you should be using a debugger. For non-trivial bugs, it’s almost always faster than using If you’re using Python 3.7, you don’t need to import anything and can just call
Calling
Like There are other debuggers available that you may want to try, but Format strings With f-StringsPython has a lot of different ways to handle string formatting, and it can be tricky to know what to use. In fact, we tackle formatting in depth in two separate articles: one about string formatting in general and one specifically focused on f-strings. In a coding interview, where you’re (hopefully) using Python 3.6+, the suggested formatting approach is Python’s f-strings. f-strings support use of the string formatting mini-language, as well as powerful string interpolation. These features allow you to add variables or even valid Python expressions and have them evaluated at runtime before being added to the string: >>>
The f-string allows you to put The one risk to be aware of is that if you’re outputting user-generated values, then that can introduce security risks, in which case Template Strings may be a safer option. Sort Complex Lists With sorted()Plenty of coding interview questions require some kind of sorting,
and there are multiple valid ways you can sort items. Unless the interviewer wants you to implement your own sorting algorithm, it’s usually best to use You’ve probably seen the most simple uses of sorting, such as sorting lists of numbers or strings in ascending or descending order: >>>
By default, It’s worth knowing about the optional keyword argument >>>
By passing in a lambda function that returns each element’s age, you can easily sort a list of dictionaries by a single value of each of those dictionaries. In this case, the dictionary is now sorted in ascending order by age. Leverage Data Structures EffectivelyAlgorithms get a lot of attention in coding interviews, but data structures are arguably even more important. In a coding interviewing context, picking the right data structure can have a major impact on performance. Beyond theoretical data structures, Python has powerful and convenient functionality built into its standard data structure implementations. These data structures are incredibly useful in coding interviews because they give you lots of functionality by default and let you focus your time on other parts of the problem. Store Unique Values With SetsYou’ll often need to remove duplicate elements from an existing dataset. New developers will sometimes do so with lists when they should be using sets, which enforce the uniqueness of all elements. Pretend you have a function named >>>
You’re supposed to call Bad Approach
>>>
This approach isn’t terrible, but it unnecessarily creates a list and then converts it to a set. Interviewers almost always notice (and ask about) this type of design choice. Worse Approach To avoid converting from a list to a set, you now store values in a list without using any other data structures. You then test for uniqueness by comparing new values with all elements currently in the list: >>>
This is worse than the first approach, because you have to compare every new word against every word already in the list. That means that as the number of words grows, the number of lookups grows quadratically. In other words, the time complexity grows on the order of O(N²). Good Approach Now, you skip using lists altogether and instead use a set from the start: >>>
This may not look much different than the other approaches except for making use of a set from the beginning. If you consider what’s happening within So why is using a set different from the second approach? It’s different because sets store elements in a manner that allows near-constant-time checks whether a value is in the set or not, unlike lists, which require linear-time lookups. The difference in lookup time means that the time complexity for adding to a set grows at a rate of O(N), which is much better than the O(N²) from the second approach in most cases. Save Memory With GeneratorsList comprehensions are convenient tools but can sometimes lead to unnecessary memory usage. Imagine you’ve been asked to find the sum of the first 1000 perfect squares, starting with 1. You know about list comprehensions, so you quickly code up a working solution: >>>
Your solution makes a list of every perfect square between 1 and 1,000,000 and sums the values. Your code returns the right answer, but then your interviewer starts increasing the number of perfect squares you need to sum. At first, your function keeps popping out the right answer, but soon it starts slowing down until eventually the process seems to hang for an eternity. This is the last thing you want happening in a coding interview. What’s going on here? It’s making a list of every perfect square you’ve requested and summing them all. A list with 1000 perfect squares may not be large in computer-terms, but 100 million or 1 billion is quite a bit of information and can easily overwhelm your computer’s available memory resources. That’s what’s happening here. Thankfully, there’s a quick way to solve the memory problem. You just replace the brackets with parentheses: >>>
Swapping out the brackets changes your list comprehension into a generator expression. Generator expressions are perfect for when you know you want to retrieve data from a sequence, but you don’t need to access all of it at the same time. Instead of creating a list, the generator expression returns a So when Define Default Values in Dictionaries With .get() and .setdefault()One of the most common programming tasks involves adding, modifying, or retrieving an item that may or may not be in a dictionary. Python dictionaries have elegant functionality to make these tasks clean and easy, but developers often check explicitly for values when it isn’t necessary. Imagine you have a dictionary named >>>
This approach first checks if the While explicitly checking for keys does work, it can easily be replaced with one line if you use >>>
But what if you want to update the dictionary with a default value while still accessing the >>>
Checking for the value and setting a default is a valid approach and
is easy to read, but again Python offers a more elegant method with >>>
Take Advantage of Python’s Standard LibraryBy default, Python comes with a lot of functionality that’s just an It’s hard to pick the most useful pieces from all of the available modules, so this section will focus on just a small subset of its utility functions. Hopefully, these will prove useful to you in coding interviews and also whet your appetite to learn more about the advanced functionality of these and other modules. Handle Missing Dictionary Keys With collections.defaultdict()
Pretend you have a group of students, and you need to keep track of their
grades on homework assignments. The input value is a list of tuples with the format One way to store the grade data uses a dictionary that maps student names to lists of grades: >>>
In this approach, you iterate over the students and check if their names are already properties in the dictionary. If not, you add them to the dictionary with an empty list as the default value. You then append their actual grades to that student’s list of grades. But there’s an even cleaner approach that uses a >>>
In this case, you’re creating a Leveraging a Count Hashable Objects With collections.CounterYou have a long string of words with no punctuation or capital letters and you want to count how many times each word appears. You could use a dictionary or >>>
When you pass in the list of words to Are you curious what the two most common words were? Just use >>>
Access Common String Groups With string ConstantsIt’s trivia time! Is It’s false, because the ASCII code for
Why does the answer matter? Because if you want to check if a character is part of the English alphabet, one popular way is to see if it’s between Checking the ASCII code works but is clumsy and easy to mess up in coding interviews, especially if you can’t remember whether lowercase or uppercase ASCII characters come first. It’s much easier to use the constants
defined as part of the You can see one in use in >>>
All
These are easier to use and, even more importantly, easier to read. Generate Permutations and Combinations With itertoolsInterviewers love to give real life scenarios to make coding interviews seem less intimidating, so here’s a contrived example: you go to an amusement park and decide to figure out every possible pair of friends that could sit together on a roller coaster. Unless generating these pairs is the primary
purpose of the interview question, it’s likely that generating all the possible pairs is just a tedious step on the way towards a working algorithm. You could calculate them yourself with nested for-loops, or you could use the powerful
>>>
With permutations, the order of the elements matters, so
>>>
Since the order of the values does not matter with combinations, there are fewer combinations than permutations for the same input list. Again, because we set
Conclusion: Coding Interview SuperpowersYou can now feel comfortable using some of Python’s less common, but more powerful, standard features in your next coding interview. There’s a lot to learn about the language as a whole but this article should have given you a starting point to go deeper while letting you use Python more effectively when you interview. In this article, you’ve learned different types of standard tools to supercharge your coding interview skills:
Interviewing may not be the best approximation of real software development, but it’s worth knowing how to succeed in any programming environment, even interviews. Thankfully, learning how to use Python during coding interviews can help you understand the language more deeply, which will pay dividends during day-to-day development. Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Python Coding Interviews: Tips & Best Practices Can I prepare for 1 day interview?On average, it takes about five to 10 hours to properly prepare for an interview. This amount of time is often enough to review your resume, research the company and hiring manager, and practice basic interview questions and answers.
How do I prepare for Python interview?How to Stand Out in a Python Coding Interview. Select the Right Built-In Function for the Job. Iterate With enumerate() Instead of range() ... . Leverage Data Structures Effectively. Store Unique Values With Sets. ... . Take Advantage of Python's Standard Library. ... . Conclusion: Coding Interview Superpowers.. What should I do the day before coding interview?Walk through your problem solving process. Brainstorm an algorithm. Draw out sample inputs and play around with them while talking and thinking out loud. ... . Barf out your algorithm in code. Focus on getting it all down first, and jot down notes next to the things you wanna go back and double-check later.. Debug your code.. How do I master Python interview?Do's and Don'ts of Python Developer Job Interview. Have basic knowledge about control flow of python.. Use list comprehension.. Understand the concepts of Object-Oriented Programming.. Know the use of generators.. Practice writing codes on paper or whiteboard.. |