Python Interview Questions

We have compiled a list of top Python interview questions which are classified into 4 sections, namely:

  • Basic Interview Questions
  • OOPS Interview Questions
  • Basic Python Programs

Learn the skills to tackle any interview question.

Basic Interview Questions:

Question 1: What is the difference between a list and a tuple?

ListTuple
A list consists of mutable objects. (Objects which can be changed after creation)A tuple consists of immutable objects. (Objects which cannot change after creation)
List has a large memory.Tuple has a small memory.
List is stored in two blocks of memory (One is fixed sized and the other is variable sized for storing data)Tuple is stored in a single block of memory.
Creating a list is slower because two memory blocks need to be accessed.Creating a tuple is faster than creating a list.
An element in a list can be removed or replaced.An element in a tuple cannot be removed or replaced.
A list has data stored in [] brackets. For example, [1,2,3]A tuple has data stored in () brackets. For example, (1,2,3)

When to use each:

tuple should be used whenever the user is aware of what is inserted in the tuple. Suppose that a college stores the information of its students in a data structure; in order for this information to remain immutable it should be stored in a tuple.

Since lists provide users with easier accessibility, they should be used whenever similar types of objects need to be stored. For instance, if a grocery needs to store all the dairy products in one field, it should use a list.

Question 2: How would you convert a list into a tuple?

[snippet slug=python_basic_iq lang=abap]

All we have to do is create a tuple with three elements. The first element of the tuple is the first element of the list, which can be found using my_list[0].

The second element of the tuple is the last element in the list. my_list[len(my_list) - 1] will give us this element. We could also have used the pop() method, but that would alter the list.

Question 3: What is the difference between an array and a list?

ListArray
Python lists are very flexible and can hold arbitrary data.Python arrays are just a thin wrapper on C arrays.
Lists are a part of Python’s syntax, so they do not need to be declared first.Arrays need to first be imported, or declared, from other libraries (i.e. numpy).
Lists can also be re-sized quickly in a time-efficient manner. This is because Python initializes some extra elements in the list at initialization.Arrays cannot be resized. Instead, an array’s values would need to be copied to another larger array.
Lists can hold heterogeneous data.Arrays can only store homogenous data. They have values with uniform data types.
Mathematical functions cannot be directly applied to lists. Instead, they have to be individually applied to each element.Arrays are specially optimized for arithmetic computations.
Lists consume more memory as they are allocated a few extra elements to allow for quicker appending of items.Since arrays stay the size that they were when they were first initialized, they are compact.

Question 4: How is memory managed in Python?

  1. Memory management in python is managed by Python private heap space. All Python objects and data structures are located in a private heap. The programmer does not have access to this private heap. The python interpreter takes care of this instead.
  2. The allocation of heap space for Python objects is done by Python’s memory manager. The core API gives access to some tools for the programmer to code.
  3. Python also has an inbuilt garbage collector, which recycles all the unused memory and so that it can be made available to the heap space.

Question 5: How do you achieve multithreading in Python?

  1. 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.
  2. 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.
  3. 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.
  4. 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.

Question 6: What is a lambda function? Give an example of when it’s useful and when it’s not.

A lambda function is a small anonymous function, which returns an object.

The object returned by lambda is usually assigned to a variable or used as a part of other bigger functions.

Instead of the conventional def keyword used for creating functions, a lambda function is defined by using the lambda keyword.

The purpose of lambdas

A lambda is much more readable than a full function since it can be written in-line. Hence, it is a good practice to use lambdas when the function expression is small.

The beauty of lambda functions lies in the fact that they return function objects. This makes them helpful when used with functions like map or filter which require function objects as arguments.

Lambdas aren’t useful when the expression exceeds a single line.

Question 7: 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.

Question 8: 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:

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

Question 9: Explain the difference between range() and xrange()

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. The only difference is that range returns a Python list object and xrange 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.

Question 10: What is PYTHONPATH?

It is an environment variable, which is used when a module is imported. Whenever a module is imported, PYTHONPATH is also looked up to check for the presence of the imported modules in various directories. The interpreter uses it to determine which module to load.

Question 11: What is PEP 8?

PEP stands for Python Enhancement Proposal. It is a set of rules that specify how to format Python code for maximum readability.

Question 12: What are Python decorators?

A decorator is a design pattern in Python that allows a user to add new functionality to an existing object without modifying its structure. Decorators are usually called before the definition of a function you want to decorate.

Question 13: Difference between generators and iterators?

In Python, iterators are used to iterate over a group of elements (in a list, for example). The way of implementing these iterators is known as generators. It yields an expression in the function, but otherwise behaves like a normal function.

Question 14: What is init?

__init__ is a method or constructor in Python. This method is automatically called to allocate memory when a new object/ instance of a class is created. All classes have the __init__ method.

Question 15: What is the ternary operator?

The ternary operator is a way of writing conditional statements in Python. As the name ternary suggests, this Python operator consists of three operands.

Note: The ternary operator can be thought of as a simplified, one-line version of the if-else statement to test a condition.

Syntax

The three operands in a ternary operator include:

  • condition: A boolean expression that evaluates to either true or false.
  • true_val: A value to be assigned if the expression is evaluated to true.
  • false_val: A value to be assigned if the expression is evaluated to false.
var = true_val if condition else false_val

The variable var on the left-hand side of the = (assignment) operator will be assigned:

  • value1 if the booleanExpression evaluates to true.
  • value2 if the booleanExpression evaluates to false.

Example

[snippet slug=python_basic_iq1 lang=abap]

Explanation

The above code is using the ternary operator to find if a number is even or odd.

  • msg will be assigned “even” if the condition (to_check % 2 == 0) is true.
  • msg will be assigned “odd” if the condition (to_check % 2 == 0) is false.

Question 16: What is polymorphism in Python?

Polymorphism means the ability to take multiple forms. So, for instance, if the parent class has a method named ABC then the child class also can have a method with the same name ABC having its own parameters and variables. Python allows for polymorphism.

Question 17: What are global and local variables in Python?

Global Variables:

Variables declared outside a function or in global space are called global variables. These variables can be accessed by any function in the program.

Local Variables:

Any variable declared inside a function is known as a local variable. This variable is present in the local space and not in the global space.

Question 18: How is try/except used in Python?

An exception is an error that occurs while the program is executing. When this error occurs, the program will stop and generate an exception which then gets handled in order to prevent the program from crashing.

The exceptions generated by a program are caught in the try block and handled in the except block.

  • Try: Lets you test a block of code for errors.
  • Except: Lets you handle the error.

Question 19: What is the join method in python?

The join method in Python takes elements of an iterable data structure and connects them together using a particular string connector value.

How does join work?

The join method in Python is a string method, which connects elements of a string iterable structure, which also contains strings or characters (array, list, etc.) by using a particular string as the connector.

Question 20: What is dictionary comprehension?

Dictionary comprehension is one way to create a dictionary in Python. It creates a dictionary by merging two sets of data which are in the form of either lists or arrays.

The data of one of the two lists/arrays will act as the keys of the dictionary while the data of the second list/array will act as the values. Each key acts as a unique identifier for each value, hence the size of both lists/arrays should be the same.

Question: 21 Explain the use of “help()” and “dir()” functions.

 In Python, the help() function is used for showing the documentation of modules, classes, functions, keywords, and so on. If the help() function receives no parameter, it launches an interactive help utility on the console.

The dir() function is used to return a valid list of attributes and methods of the object it is called upon. Since the function aims to produce the most relevant data (instead of showing the complete information), it behaves differently with different objects:

  • For modules/library objects, the dir() function returns a list of all attributes contained in that module.
  • For class objects, the dir() function returns a list of all valid attributes and base attributes.
  • When no parameters are passed to it, the dir() function returns a list of attributes in the current scope.

Question: 22 What are python modules? Name some commonly used built-in modules in Python?

 Python modules are files containing Python code that can be either function classes or variables. These modules are Python files having a .py extension. Modules can include a set of functions, classes, or variables that are both defined and implemented. You can import and initialize a module using the import statement, learning python tutorial will let us know more about python modules.

Here are some of the commonly used built-in modules in Python:

  • os
  • sys
  • math
  • random
  • data time
  • JSON

Benefits of modules in Python

There are a couple of key benefits of creating and using a module in Python:

  • Structured Code
    • Code is logically organized by being grouped into one Python file which makes development easier and less error-prone.
    • Code is easier to understand and use.
  • Reusability
    • Functionality defined in a single module can be easily reused by other parts of the application. This eliminates the need to recreate duplicate code.

Question: 23 Explain “self” in Python.

In Python, “self” is a keyword used to define an instance or object of a class. Unlike in Java, where the self is optimal, in Python, it is primarily used as the first parameter. Self helps to distinguish between the methods and attributes of a class from its local variables.

The self variable in the __init__ method refers to the newly created object or instance, while in other methods, it pertains to the object or instance whose method was called.

Question: 24 Explain the functionality of “break,” “continue,” and “pass.”

 It is one of the common questions in python interview questions and answers guide. Let’s see break, continue and pass in detail.

The break statement is used for terminating a loop when a specific condition is met, and the control is transferred to the following statement.

  • The continue statement helps to terminate the current iteration of the statement when a particular condition is met, skips the rest of the code in the current iteration, and passes the control to the next iteration of the loop.
  • The pass statement is essentially a null operation that is used to fill up empty blocks of code that may execute during runtime but are yet to be written. It is represented by a semi-colon.

Question: 25  How and when would you use any() and all()?

What is any()?

any() is a function that takes in an iterable (such as a list, tuple, set, etc.) and returns True if any of the elements evaluate to True, but it returns False if all elements evaluate to False.

Passing an iterable to any() to check if any of the elements are True.

one_truth = [True, False, False]
three_lies = [0, '', None]

print(any(one_truth))

print(any(three_lies))

The first print statement prints True because one of the elements in one_truth is True.

On the other hand, the second print statement prints False because none of the elements are True, i.e., all elements are False.

Use any() when you need to check a long series of or conditions.

What is all()?

all() is another Python function that takes in an iterable and returns True if all of the elements evaluate to True, but returns False if otherwise.

Similar to any()all() takes in a list, tuple, set, or any iterable.

all_true = [True, 1, 'a', object()]
one_true = [True, False, False, 0]
all_false = [None, '', False, 0]

print(all(all_true))
print(all(one_true))
print(all(all_false))

The first function call returned True because all_true was filled with truthy values.

Passing one_true to all() returned False because the list contained one or more falsy values.

Finally, passing all_false to all() returns False because it also contained one or more falsy values.

Use all() when you need to check a long series of and conditions.

Question: 26 How to copy an object in Python?

In Python, the assignment statement (= operator) does not copy objects, but instead, it creates a binding between the existing object and the target variable name. Thus, if you wish to create copies of an object in Python, you need to use the copy module. There are two ways to create copies for a particular object using the copy module:

  • Shallow copy – It is a bit-wise copy of an object. The copied object will have an exact replica of the values contained in the original object. If any of the values are references to other objects, only the reference addresses for the same will be copied.
  • Deep copy — It copies all values recursively from source to target object, meaning, it will duplicate even the objects that are referenced by the source object.

Question: 27 What are functions?

Functions are a set of code used when we want to run the same method for more than 1 time.It reduces the length of program.Functions are defined into 2 categories –
1)function defination
2)function calling

Example
def dog():
print(“my name is tommy”)

dog();

Question: 28 Explain split() and join() functions in Python?

  • You can use split() function to split a string based on a delimiter to a list of strings.
  • You can use join() function to join a list of strings based on a delimiter to give a single string
string = "This is a string." 
string_list = string.split(' ') #delimiter is ‘space’ character or ‘ ‘ 
print(string_list) #output: ['This', 'is', 'a', 'string.'] 
print(' '.join(string_list)) #output: This is a string. 

Question: 29  What does *args and **kwargs mean?

*args

  • *args is a special syntax used in function definition to pass variable-length argument.
  • “*” means variable length and “args” is the name used by convention. You can use any other.
def multiply(a, b, *argv):     
mul = a * b     for num in argv:       
mul *= num     
return mul
 print(multiply(1, 2, 3, 4, 5)) #output: 120

**kwargs

  • **kwargs is a special syntax used in function definition to pass variable-length keyworded argument.
  • Here, also, “kwargs” is used just by convention. You can use any other name.
  • Keyworded argument means a variable which has a name when passed to a function.
  • It is actually a dictionary of variable name and its value.
def tellArguments(**kwargs):
    for key, value in kwargs.items():
        print(key + ": " + value)
tellArguments(arg1 = "argument 1", arg2 = "argument 2", arg3 = "argument 3")
#output:
# arg1: argument 1
# arg2: argument 2
# arg3: argument 3

Question: 30 What are Python namespaces? Why are they used?

A namespace in Python ensures that object names in a program are unique and can be used without any conflict. Python implements these namespaces as dictionaries with ‘name as key’ mapped to a corresponding ‘object as value’. This allows for multiple namespaces to use the same name and map it to a separate object. A few examples of namespaces are as follows:

  • Local Namespace includes local names inside a function. the namespace is temporarily created for a function call and gets cleared when the function returns.
  • Global Namespace includes names from various imported packages/ modules that is being used in the current project. This namespace is created when the package is imported in the script and lasts until the execution of the script.
  • Built-in Namespace includes built-in functions of core Python and built-in names for various types of exceptions.

Lesson Content
0% Complete 0/2 Steps