Introduction
I love Python. It’s simple and gets the job done. Writing Python code is generally faster and easier than the other languages because it handles most of the work in the background for you instead of making you implement it. Because of this trait, I think it suits well for coding interview questions. As a third-year computer engineering student, I must always be ready to be tested. This requires me to have a language that I can write well all the time for interview questions. I generally don’t write Python or don’t solve interview questions daily. Because of that, I spend more time thinking about the syntax and programming language-related things than the actual implementation of the question. However, this must be changed. I’m writing this as a cheat sheet for myself to have a look at how things are done in Python, especially for interviews. My main source for writing this was Python for Coding Interviews - Everything you Need to Know by NeetCode video. If you want to see something more detailed, I suggest you go and check it out yourself. Too much talk, let’s dive in
Cheatsheet
Variables
Multiple assignments can be done in this way
Unfortunately, we can’t use i++
We don’t have NULL, but have None as equivalent
If Statements
Everything is straightforward in if statements except there is no else if but there is a separate keyword as elif
. Also, attention to indentation.
Parentheses are needed for multi-line conditions. For conditions, we write and
instead of &&
and or
instead of ||
.
Inline if
statements are useful for some cases
Loops
Math
The division is decimal by default
Double slash rounds down, this also includes negative numbers
For round negative numbers towards zero you can use decimal division and then convert to int.
Negative modding might not work as you might expected.
To get -1 from modding negative numbers you can use
More math helpers
Python numbers are infinite, so they never overflow. If you need to use max/min values you can use
A REALLY HUGE number will always be smaller than float("inf")
.
Arrays
Arrays are called Lists
in Python. Arrays in Python are dynamic.
Arrays can be used as stacks. Appending and popping a value is an O(1) operation.
Also, you can insert a value to a certain index. This is an O(n) operation.
You can set the value of a given index in constant time.
A list with a default value can be generated like this
The index of an array starts from 0
. Indexing -1
will give you the last value, -2
will give you the second last value, etc.
Sublisting (aka slicing) is a handy tool. Similarly to for-loop ranges, the last index is non-inclusive
Unpacking is also possible but you must be sure that num of variables matches to the array length
As the range()
function gives us a list, looping another list mechanism is pretty straightforward.
Looping multiple arrays simultaneously with using zip()
and unpacking is also possible.
Reversing an array is pretty simple
Sorting
Sorting an array is pretty straightforward
To sort in descending order you can set reverse argument True
Strings will be sorted in alphabetical order
If you need custom sorting (sorting by length for example) you can set key
argument to a lambda function
.
For this case our lambda function means: for every value ‘x’, map it with len(x).
List Comprehension
Creating lists with initial values can easily be done by using list comprehensions.
2D Arrays
You can easily create a 2D array with list comprehension
If you think this can be simplified by multiplying a list, unfortunately, it won’t work.
Strings
Strings can be generated by using '
and "
.
You can get a substring with slicing like arrays
Strings are immutable, so you can’t change a char in a certain index. Modifying a string will create a new string.
If you need the ASCII value of a char
You can combine a list of strings with .join()
Queues
In Python, queues are double-ended by default
Hash Sets
We can search and insert in O(1) in Hash Sets.
Sets can be generated from lists. And also Set comprehensions.
Hash Maps
Hash Maps (a.k.a dictionaries) is one of the most used data collections for coding interviews. Creating a hash map is easy. You can assign or update a key
to a value
. For example, string alice
is the key here and 88 is the value of the key.
We can look for if a key exists or not
Like list comprehension, also using dict comprehensions is possible.
Looping through maps is also pretty useful. The code is pretty self-exploratory
For some cases, creating the dict with defaultdict prevents a lot of edge case crashes
Tuples
Tuples are like arrays but immutable
Tuples also can be used as a key for hash map/set But lists can’t be keys
Unpacking is also possible for tuples
Heaps
Heaps might be useful for some kind of questions. Python heaps are min heaps by default. Under the hood, heaps are arrays
There is no max heaps by default. To work around this, you can use min heap but multiply the values by -1 when doing push & pop operations
Heaps can also be built with initial values.
Functions
Nested Functions
Nested functions have access to outer variables
They also can modify objects but not reassign them unless nonlocal
keyword is used
Classes
Ofc, there is a lot more about Python classes. However, knowing __init__
and usage of self
should be enough for interviews.