Intermediate Python Interview Question
1. What is the difference between xrange and range functions?
range() and xrange() are two functions that could be used to iterate a certain number of times in for loops in Python. In Python 3, there is no xrange, but the range function behaves like xrange in Python 2.
range() – This returns a list of numbers created using the range() function.
xrange() – This function returns the generator object that can be used to display numbers only by looping. The only particular range is displayed on demand and hence called lazy evaluation.
2. What is Dictionary Comprehension? Give an Example
Dictionary Comprehension is a syntax construction to ease the creation of a dictionary based on the existing iterable.
For Example: my_dict = {i:1+7 for i in range(1, 10)}
3. Is Tuple Comprehension? If yes, how, and if not why?
(i for i in (1, 2, 3))
Tuple comprehension is not possible in Python because it will end up in a generator, not a tuple comprehension.
4. Differentiate between List and Tuple?
Let’s analyze the differences between List and Tuple:
List
Lists are Mutable datatype.
Lists consume more memory
The list is better for performing operations, such as insertion and deletion.
The implication of iterations is Time-consuming
Tuple
Tuples are Immutable datatype.
Tuple consumes less memory as compared to the list
A Tuple data type is appropriate for accessing the elements
The implication of iterations is comparatively Faster
5. What is the difference between a shallow copy and a deep copy?
Shallow copy is used when a new instance type gets created and it keeps values that are copied whereas deep copy stores values that are already copied.
A shallow copy has faster program execution whereas a deep coy makes it slow.
6. Which sorting technique is used by sort() and sorted() functions of python?
Python uses the Tim Sort algorithm for sorting. It’s a stable sorting whose worst case is O(N log N). It’s a hybrid sorting algorithm, derived from merge sort and insertion sort, designed to perform well on many kinds of real-world data.
7. What are Decorators?
Decorators are a very powerful and useful tool in Python as they are the specific change that we make in Python syntax to alter functions easily.
8. How do you debug a Python program?
By using this command we can debug a Python program:
$ python -m pdb python-script.py
9. What are Iterators in Python?
In Python, iterators are used to iterate a group of elements, containers like a list. Iterators are collections of items, and they can be a list, tuples, or a dictionary. Python iterator implements __itr__ and the next() method to iterate the stored elements. We generally use loops to iterate over the collections (list, tuple) in Python.
10. What are Generators in Python?
In Python, the generator is a way that specifies how to implement iterators. It is a normal function except that it yields expression in the function. It does not implement __itr__ and next() method and reduces other overheads as well.
If a function contains at least a yield statement, it becomes a generator. The yield keyword pauses the current execution by saving its states and then resumes from the same when required.
11. Does Python supports multiple Inheritance?
Python does support multiple inheritances, unlike Java. Multiple inheritances mean that a class can be derived from more than one parent class.
12. 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 polymorphism.
13. Define encapsulation in Python?
Encapsulation means binding the code and the data together. A Python class is an example of encapsulation.
14. How do you do data abstraction in Python?
Data Abstraction is providing only the required details and hides the implementation from the world. It can be achieved in Python by using interfaces and abstract classes.
15. How is memory management done in Python?
Python uses its private heap space to manage the memory. Basically, all the objects and data structures are stored in the private heap space. Even the programmer can not access this private space as the interpreter takes care of this space. Python also has an inbuilt garbage collector, which recycles all the unused memory and frees the memory and makes it available to the heap space.
16. How to delete a file using Python?
We can delete a file using Python by following approaches:
os.remove()
os.unlink()
16. What is slicing in Python?
Python Slicing is a string operation for extracting a part of the string, or some part of a list. With this operator, one can specify where to start the slicing, where to end, and specify the step. List slicing returns a new list from the existing list.
Syntax: Lst[ Initial : End : IndexJump ]
17. What is a namespace in Python?
A namespace is a naming system used to make sure that names are unique to avoid naming conflicts.
Advanced Python Interview Questions & Answers
18. What is PIP?
PIP is an acronym for Python Installer Package which provides a seamless interface to install various Python modules. It is a command-line tool that can search for packages over the internet and install them without any user interaction.
19. What is a zip function?
Python zip() function returns a zip object, which maps a similar index of multiple containers. It takes an iterable, converts it into an iterator and aggregates the elements based on iterables passed. It returns an iterator of tuples.
20. What are Pickling and Unpickling?
The Pickle module accepts any Python object and converts it into a string representation and dumps it into a file by using the dump function, this process is called pickling. While the process of retrieving original Python objects from the stored string representation is called unpickling.
21. What is monkey patching in Python?
In Python, the term monkey patch only refers to dynamic modifications of a class or module at run-time.
# g.py
class GeeksClass:
def function(self):
print "function()"
import m
def monkey_function(self):
print "monkey_function()"
m.GeeksClass.function = monkey_function
obj = m.GeeksClass()
obj.function()
22. What is __init__() in Python?
Equivalent to constructors in OOP terminology, __init__ is a reserved method in Python classes. The __init__ method is called automatically whenever a new object is initiated. This method allocates memory to the new object as soon as it is created. This method can also be used to initialize variables.
23. Write a code to display the current time?
currenttime= time.localtime(time.time())
print (“Current time is”, currenttime)
24. What are Access Specifiers in Python?
Python uses the ‘_’ symbol to determine the access control for a specific data member or a member function of a class. A Class in Python has three types of Python access modifiers:
Public Access Modifier: The members of a class that are declared public are easily accessible from any part of the program. All data members and member functions of a class are public by default.
Protected Access Modifier: The members of a class that are declared protected are only accessible to a class derived from it. All data members of a class are declared protected by adding a single underscore ‘_’ symbol before the data members of that class.
Private Access Modifier: The members of a class that are declared private are accessible within the class only, the private access modifier is the most secure access modifier. Data members of a class are declared private by adding a double underscore ‘__’ symbol before the data member of that class.
25. What are unit tests in Python?
Unit Testing is the first level of software testing where the smallest testable parts of the software are tested. This is used to validate that each unit of the software performs as designed. The unit test framework is Python’s xUnit style framework. The White Box Testing method is used for Unit testing.
26. Python Global Interpreter Lock (GIL)?
Python Global Interpreter Lock (GIL) is a type of process lock that is used by Python whenever it deals with processes. Generally, Python only uses only one thread to execute the set of written statements. The performance of the single-threaded process and the multi-threaded process will be the same in Python and this is because of GIL in Python. We can not achieve multithreading in Python because we have a global interpreter lock that restricts the threads and works as a single thread.
27. What are Function Annotations in Python?
Function Annotation is a feature that allows you to add metadata to function parameters and return values. This way you can specify the input type of the function parameters and the return type of the value the function returns.
Function annotations are arbitrary Python expressions that are associated with various parts of functions. These expressions are evaluated at compile time and have no life in Python’s runtime environment. Python does not attach any meaning to these annotations. They take life when interpreted by third-party libraries, for example, mypy.
Python 3.10 above Feature:
28. What are Exception Groups in Python?
The latest feature of Python 3.11, Exception Groups. The ExceptionGroup can be handled using a new except* syntax. The * symbol indicates that multiple exceptions can be handled by each except* clause.
ExceptionGroup is a collection/group of different kinds of Exception. Without creating Multiple Exceptions we can group together different Exceptions which we can later fetch one by one whenever necessary, the order in which the Exceptions are stored in the Exception Group doesn’t matter while calling them.
try:
raise ExceptionGroup('Example ExceptionGroup', (
TypeError('Example TypeError'),
ValueError('Example ValueError'),
KeyError('Example KeyError'),
AttributeError('Example AttributeError')
))
except* TypeError:
...
except* ValueError as e:
...
except* (KeyError, AttributeError) as e:
...
29. What is Python Switch Statement
From version 3.10 upward, Python has implemented a switch case feature called “structural pattern matching”. You can implement this feature with the match and case keywords. Note that the underscore symbol is what you use to define a default case for the switch statement in Python.
Note: Before Python 3.10 Python doesn’t support match Statements.
match term:
case pattern-1:
action-1
case pattern-2:
action-2
case pattern-3:
action-3
case _:
action-default
30. What is Walrus Operator?
The Walrus Operator allows you to assign a value to a variable within an expression. This can be useful when you need to use a value multiple times in a loop, but don’t want to repeat the calculation.
The Walrus Operator is represented by the `:=` syntax and can be used in a variety of contexts including while loops and if statements.
Note: Python versions before 3.8 doesn’t support Walrus Operator.
names = ["Jacob", "Joe", "Jim"]
if (name := input("Enter a name: ")) in names:
print(f"Hello, {name}!")
else:
print("Name not found.")
No comments