We have collected top Python Interview Questions and Answers and listed below. Prepare for your interview and get placed. Check the questions and answers below.
- Is Python Programming or scripting language?
Python is a programming language but it can also be used for scripting. In a general sense, it is considered as a general-purpose programming language.
- Is Python an interpreted language?
Yes, Python is an interpreted language. An interpreted language is any programming language that is not in machine-level code before runtime. Python code is executed line by line.
- State a few lines about memory management in Python.
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. Python has an inbuilt garbage collector.
- What is namespace in Python?
A namespace is a naming system used to make sure that names are unique to avoid naming conflicts. Python implements namespaces in the form of dictionaries. It maintains a name-to-object mapping where names act as keys and the objects as values.
- Is python case sensitive?
Yes, Python is case sensitive.
- What is PEP 8?
PEP stands for Python Enhancement Proposal.PEP 8 is a coding convention, a set of recommendations, about how to write your Python code more readable.
- 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 can have the __init__ method.
- What is the difference between list and tuples in Python?
The major difference is Lists are mutable i.e they can be edited and tuples are immutable (tuples are lists which can’t be edited). Lists are slower than tuples. Tuples are faster than lists.
- Why tuples are faster than lists?
Tuples are stored in a single block of memory. Tuples are immutable so, It doesn’t require extra space to store new objects.
Lists are allocated in two blocks: the fixed one with all the Python object information and a variable-sized block for the data.
- What does [::-1} do?
- What are python iterators?
Iterators are objects which can be traversed through or iterated upon.
- What are the generators in python?
Functions that return an iterable set of items are called generators.
- What is a lambda function?
An anonymous function is known as a lambda function. This function can have any number of parameters but, can have just one statement.
- What is self in Python?
Self is an instance of an object of a class. In Python, this is explicitly included as the first parameter. It helps to differentiate between the methods and attributes of a class with local variables. It is a convention to use “self” name variable.
- Which data types are supported in Python?
Python has five standard data types:
- 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 *rol and **billy but that would not be wise.
- Explain Inheritance in Python with an example.
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.
- 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.
- 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.
- What is a pass in Python?
Pass means, no-operation Python statement, or in other words, it is a place holder in a compound statement, where there should be a blank left and nothing has to be written there.
- In Python what is slicing?
A mechanism to select a range of items from sequence types like list, tuple, strings, etc. is known as slicing.
- What is a negative index in Python?
Python sequences can be index in positive and negative numbers. For positive index, 0 is the first index, 1 is the second index, and so forth. For negative index, (-1) is the last index, and (-2) is the second last index and so forth.
- What is the module and package in Python?
In Python, the module is the way to structure the program. Each Python program file is a module, which imports other modules like objects and attributes.
The folder of the Python program is a package of modules. A package can have modules or subfolders.
- Explain how can you make a Python Script executable on Unix?
To make a Python Script executable on Unix, you need to do two things,
- Script file’s mode must be executable and
- the first line must begin with # ( #!/usr/local/bin/python)
- Mention the use of the split function in Python?
The use of the split function in Python is that it breaks a string into shorter strings using the defined separator. It gives a list of all words present in the string.
- Mention what is the difference between Django, Pyramid, and Flask?
Flask is a “microframework” primarily build for a small application with simpler requirements. In a flask, you don’t have to use external libraries. Flask is ready to use.
Pyramid are built for larger applications. It provides flexibility and lets the developer use the right tools for their project. The developer can choose the database, URL structure, templating style, and more. The pyramid is heavily configurable.
Like Pyramid, Django can also be used for larger applications. It includes an ORM.
- What is the output of print list[1:3] if list = [ ‘abcd’, 786 , 2.23, ‘john’, 70.2 ]?
It will print elements starting from 2nd till 3rd. The output would be [786, 2.23].
- What is the output of print tuple * 2 if tuple = (123, ‘john’)?
It will print tuple two times. The output would be (123, ‘john’, 123, ‘john’).
- What is the purpose of ** operator?
** Exponent − Performs exponential (power) calculation on operators. a**b = 10 to the power 20, if a = 10 and b = 20.
- Is the Python platform independent?
No, there are some modules and functions in python that can only run on certain platforms.
- Is there any double data type in Python?
- Name the python Library used for Machine learning.
Scikit-learn python Library used for Machine learning
- Name the tools which python uses to find bugs
Pylint and pychecker.
- What are decorators in Python?
Decorators in Python are essentially functions that add functionality to an existing function in Python without changing the structure of the function itself. They are represented by the @decorator_name in Python and are called in a bottom-up fashion
- What is list comprehension?
List comprehension is an elegant way to define and create lists based on existing lists.
- What is the break statement in Python?
The break statement terminates the loop immediately
and the control flows to the statement after the body of the loop.
- What is the continue statement in Python?
The continue statement terminates the current iteration of the statement, skips the rest of the code in the current iteration and the control flows to the next iteration of the loop.
- What is pickling and unpickling?
Pickling is the name of the serialization process in Python. Any object in Python can be serialized into a byte stream and dumped as a file in the memory.
Unpickling is the complete inverse of pickling. It deserializes the byte stream to recreate the objects stored in the file and loads the object to memory.
- What is PYTHONPATH in Python?
PYTHONPATH is an environment variable which you can set to add additional directories where Python will look for modules and packages. This is especially useful in maintaining Python libraries that you do not wish to install in the global default location.
- What is the difference between .py and .pyc files?
.py files contain the source code of a program. Whereas, .pyc file contains the bytecode of your program. We get bytecode after compilation of .py file (source code). .pyc files are not created for all the files that you run. It is only created for the files that you import.
- What is the difference between append() and extend() methods?
Both append() and extend() methods are methods used to add elements at the end of a list.
append(element): Adds the given element at the end of the list that called this append() method
extend(another-list): Adds the elements of another list at the end of the list that called this extend() method
- Why would you use NumPy arrays instead of lists in Python?
NumPy arrays provide users with three main advantages as shown below:
NumPy arrays consume a lot less memory, thereby making the code more efficient.
NumPy arrays execute faster and do not add heavy processing to the runtime.
NumPy has a highly readable syntax, making it easy and convenient for programmers.
- How will you reverse a list in Python?
The function list.reverse() reverses the objects of a list.
- How will you remove the last object from a list in Python?
- Why zip() function is used?
The zip() function returns a zip object, which is an iterator of tuples where the first item in each passed iterator is paired together, and then the second item in each passed iterator are paired together
- How to overload constructors or methods in Python?
Python’s constructor: _init__ () is the first method of a class. Whenever we try to instantiate an object __init__() is automatically invoked by python to initialize members of an object. We can’t overload constructors or methods in Python. It shows an error if we try to overload.
- What is the difference between remove() function and del statement?
You can use the remove() function to delete a specific object in the list. If you want to delete an object at a specific location (index) on the list, you can either use del or pop.
- What is swapcase() function in the Python?
It is a string’s function which converts all uppercase characters into lowercase and vice versa
- What are the methods you know to copy an object in Python?
Commonly, we use <copy.copy()> or <copy.deepcopy()> to perform copy operation on objects. Though not all objects support these methods but most do. But some objects are easier to copy. Like the dictionary objects provide a <copy()> method.
- What is the python “with” statement designed for?
The with statement simplifies exception handling by encapsulating common preparation and cleanup tasks in so-called context managers.
For instance, the open statement is a context manager in itself, which lets you open a file, keep it open as long as the execution is in the context of the with statement where you used it, and close it as soon as you leave the context, no matter whether you have left it because of an exception or during regular control flow.