Over 2,000 mentors available, including leaders at Amazon, Airbnb, Netflix, and more. Check it out
Published

Popular Python Interview Questions

Scheduling your first Python Interview or the first one after a while? Preparing for a Python Coding test? This collection of Python Interview questions should help you getting up to speed.
MentorCruise Team

The MentorCruise team shares crucial career insights in regular blog posts.

What is PEP 8?

PEP 8 is a coding convention, a set of rules, about how to make your Python code more readable.

What is the difference between list and tuples?

Lists are mutable i.e they can be edited. Tuples are immutable (tuples are lists which can’t be edited).

Lists are slower than tuples. Tuples are faster than list.

list_1 = [10, ‘Chelsea’, 20]
tup_1 = (10, ‘Chelsea’ , 20)

What is the difference between deep and shallow copy?

Shallow copy is used when a new instance type gets created and it keeps the values that are copied in the new instance. Shallow copy is used to copy the reference pointers just like it copies the values. These references point to the original objects and the changes made in any member of the class will also affect the original copy of it. Shallow copy allows faster execution of the program and it depends on the size of the data that is used.

Deep copy is used to store the values that are already copied. Deep copy doesn’t copy the reference pointers to the objects. It makes the reference to an object and the new object that is pointed by some other object gets stored. The changes made in the original copy won’t affect any other copy that uses the object. Deep copy makes execution of the program slower due to making certain copies for each object that is been called.

How is Multithreading achieved in Python?

  • Python has a multi-threading package but if you want to multi-thread to speed your code up, then it’s usually not a good idea to use it.
  • Python has a construct called the Global Interpreter Lock (GIL). The GIL makes sure that only one of your ‘threads’ can execute at any one time. A thread acquires the GIL, does a little work, then passes the GIL onto the next thread.
  • This happens very quickly so to the human eye it may seem like your threads are executing in parallel, but they are really just taking turns using the same CPU core.
  • All this GIL passing adds overhead to execution. This means that if you want to make your code run faster then using the threading package often isn’t a good idea.

Explain Inheritance in Python

Inheritance allows One class to gain all the members(say attributes and methods) of another class. Inheritance provides code reusability, makes it easier to create and maintain an application. The class from which we are inheriting is called super-class and the class that is inherited is called a derived / child class.

They are different types of inheritance supported by Python:

  • Single Inheritance – where a derived class acquires the members of a single super class.
  • Multi-level inheritance – a derived class d1 in inherited from base class base1, and d2 are inherited from base2.
  • Hierarchical inheritance – from one base class you can inherit any number of child classes
  • Multiple inheritance – a derived class is inherited from more than one base class.

What is dictionary in Python?

A dictionary is a built-in data type. It defines one-to-one relationship between keys and values. Dictionaries contain pair of keys and their corresponding values. Dictionaries are indexed by keys.

Let’s take an example:

The following example contains some keys. Country, Capital & PM. Their corresponding values are India, Delhi and Modi respectively.

location={'Country':'India','Capital':'Delhi','PM':'Modi'}
print location['Country']
>> India
print location['Capital']
>> Delhi
print location['PM']
>> Modi

What does this mean: *args, **kwargs? And why would we use it?

We use *args when we aren’t sure how many arguments are going to be passed to a function, or if we want to pass a stored list or tuple of arguments to a function. **kwargs is used when we don’t know how many keyword arguments will be passed to a function, or it can be used to pass the values of a dictionary as keyword arguments. The identifiers args and kwargs are a convention, you could also use *bob and **billy but that would not be wise.

What are negative indexes and why are they used?

The sequences in Python are indexed and it consists of the positive as well as negative numbers. The numbers that are positive uses ‘0’ that is uses as first index and ‘1’ as the second index and the process goes on like that.

The index for the negative number starts from ‘-1’ that represents the last index in the sequence and ‘-2’ as the penultimate index and the sequence carries forward like the positive number.

The negative index is used to remove any new-line spaces from the string and allow the string to except the last character that is given as S[:-1]. The negative index is also used to show the index to represent the string in correct order.

How can you generate random numbers in Python?

Random module is the standard module that is used to generate the random number. The method is defined as:

import random
random.random

The statement random.random() method return the floating point number that is in the range of [0, 1). The function generates the random float numbers. The methods that are used with the random class are the bound methods of the hidden instances. The instances of the Random can be done to show the multi-threading programs that creates different instance of individual threads. The other random generators that are used in this are:

  • randrange(a, b): it chooses an integer and define the range in-between [a, b). It returns the elements by selecting it randomly from the range that is specified. It doesn’t build a range object.
  • uniform(a, b): it chooses a floating point number that is defined in the range of [a,b).Iyt returns the floating point number
  • normalvariate(mean, sdev): it is used for the normal distribution where the mu is a mean and the sdev is a sigma that is used for standard deviation. The Random class that is used and instantiated creates an independent multiple random number generators.

What is the difference between range & xrange? (Python2)

For the most part, xrange and range are the exact same in terms of functionality. They both provide a way to generate a list of integers for you to use, however you please. The only difference is that range returns a Python list object and x range returns an xrange object.

This means that xrange doesn’t actually generate a static list at run-time like range does. It creates the values as you need them with a special technique called yielding. This technique is used with a type of object known as generators. That means that if you have a really gigantic range you’d like to generate a list for, say one billion, xrange is the function to use.

This is especially true if you have a really memory sensitive system such as a cell phone that you are working with, as range will use as much memory as it can to create your array of integers, which can result in a Memory Error and crash your program. It’s a memory hungry beast.

What is pickling and unpickling?

Pickle module accepts any Python object and converts it into a string representation and dumps it into a file by using dump function, this process is called pickling. While the process of retrieving original Python objects from the stored string representation is called unpickling.

How are arguments passed by value or by reference?

Everything in Python is an object and all variables hold references to the objects. The references values are according to the functions; as a result you cannot change the value of the references. However, you can change the objects if it is mutable.

What is pass in Python?

pass is a no-operation statement

What is monkey patching and when is it used?

Monkey patching is changing the behaviour of a function or object after it has already been defined. For example:

import datetime
datetime.datetime.now = lambda: datetime.datetime(2012, 12, 12)

One reason to monkey patch would be in testing.

What do these mean to you: @classmethod, @staticmethod, @property?

These are decorators. A decorator is a special kind of function that either takes a function and returns a function, or takes a class and returns a class. The @ symbol is just syntactic sugar that allows you to decorate something in a way that’s easy to read.

@my_decorator
def my_func(stuff):
    do_things

Is equivalent to

def my_func(stuff):
    do_things

my_func = my_decorator(my_func)

Describe Python’s garbage collection mechanism in brief.

A lot can be said here. There are a few main points that you should mention:

  • Python maintains a count of the number of references to each object in memory. If a reference count goes to zero then the associated object is no longer live and the memory allocated to that object can be freed up for something else
  • occasionally things called “reference cycles” happen. The garbage collector periodically looks for these and cleans them up. An example would be if you have two objects o1 and o2 such that o1.x == o2 and o2.x == o1. If o1 and o2 are not referenced by anything else then they shouldn’t be live. But each of them has a reference count of 1.
  • Certain heuristics are used to speed up garbage collection. For example, recently created objects are more likely to be dead. As objects are created, the garbage collector assigns them to generations. Each object gets one generation, and younger generations are dealt with first.

Sources

https://www.edureka.co/blog/interview-questions/python-interview-questions/ https://www.codementor.io/sheena/essential-python-interview-questions-du107ozr6

Find an expert mentor

Get the career advice you need to succeed. Find a mentor who can help you with your career goals, on the leading mentorship marketplace.